GetFileColumnNumber() public method

public GetFileColumnNumber ( ) : int
return int
Example #1
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);
        }
Example #2
0
 public ConeStackFrame(StackFrame frame)
 {
     Method = frame.GetMethod();
     File = frame.GetFileName();
     Line = frame.GetFileLineNumber();
     Column = frame.GetFileColumnNumber();
 }
Example #3
0
        /// <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();
        }
Example #4
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");
		}
Example #5
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");
		}
 /// <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();
 }
Example #7
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);
     }
 }
Example #8
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);
     }
 }
Example #9
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 ();
			}
		}
 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();
 }
Example #11
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));
        }
Example #12
0
 public static string GetStackFrameInfo(StackFrame frame, TraceInfo traceInfo)
 {
     if (frame != null)
     {
         switch (traceInfo)
         {
             case TraceInfo.LineNumber:
                 return frame.GetFileLineNumber().ToString();
             case TraceInfo.FileName:
                 return frame.GetFileName();
             case TraceInfo.Method:
                 return frame.GetMethod().Name;
             case TraceInfo.ColumnNumber:
                 return frame.GetFileColumnNumber().ToString();
             case TraceInfo.Full:
                 return new StackTrace(frame).ToString();
         }
     }
     return "Error: StackFrame==null";
 }
Example #13
0
        public override bool Equals(Object obj)
        {
            if ((obj == null) || (!(obj is StackFrame)))
            {
                return(false);
            }

            StackFrame rhs = (StackFrame)obj;

            if (!ObjectsEqual(GetMethod(), rhs.GetMethod()))
            {
                return(false);
            }

            if (!ObjectsEqual(GetFileName(), rhs.GetFileName()))
            {
                return(false);
            }

            if (GetFileLineNumber() != rhs.GetFileLineNumber())
            {
                return(false);
            }

            if (GetFileColumnNumber() != rhs.GetFileColumnNumber())
            {
                return(false);
            }

            if (GetILOffset() != rhs.GetILOffset())
            {
                return(false);
            }

            if (GetNativeOffset() != rhs.GetNativeOffset())
            {
                return(false);
            }

            return(true);
        }
Example #14
0
        /// <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();
            Filename = frame.GetFileName();
            Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null;
            Function = method.Name;
            Source = method.ToString();
            LineNumber = lineNo;
            ColumnNumber = frame.GetFileColumnNumber();
        }
Example #15
0
        private static ExceptionFrame BuildExceptionFrame(StackFrame frame)
        {
            int lineNo = frame.GetFileLineNumber();

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

            var method = frame.GetMethod();
            return new ExceptionFrame()
            {
                Filename = frame.GetFileName(),
                Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null,
                Function = method.Name,
                Source = method.ToString(),
                LineNumber = lineNo,
                ColumnNumber = frame.GetFileColumnNumber()
            };
        }
Example #16
0
 public static void WriteMethodExit(Type type, StackFrame sf)
 {
     if (StockLog.Logger.isEnabled && StockLog.Logger.isMethodLoggingEnabled)
      {
     StockLog.Logger.sw.WriteLine("{0}({1},{2}): {3}::{4} : Exit", sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber(), type.ToString(), sf.GetMethod().Name);
      }
 }
Example #17
0
 public static void WriteMethodEntry(StackFrame sf)
 {
     if (StockLog.Logger.isEnabled && StockLog.Logger.isMethodLoggingEnabled)
      {
     StockLog.Logger.sw.WriteLine("{0}({1},{2}): {3} : Entry", sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber(), sf.GetMethod().Name);
      }
 }
Example #18
0
 private void output(string errorOrWarning, string message, params string[] tokens)
 {
     if (tokens == null || tokens.Length == 0 || tokens.All(t => t == null))
     {
         var frame = new StackFrame(2, true);
         outputLine(errorOrWarning, frame.GetFileName(), "{0},{1}".Fmt(frame.GetFileLineNumber(), frame.GetFileColumnNumber()), message);
         return;
     }
     try
     {
         var tokenRegexes = tokens.Select(tok => tok == null ? null : new Regex(@"\b" + Regex.Escape(tok) + @"\b")).ToArray();
         foreach (var f in new DirectoryInfo(_path).GetFiles("*.cs", SearchOption.AllDirectories))
         {
             var lines = File.ReadAllLines(f.FullName);
             var tokenIndex = tokens.IndexOf(t => t != null);
             for (int i = 0; i < lines.Length; i++)
             {
                 Match match;
                 var charIndex = 0;
                 while ((match = tokenRegexes[tokenIndex].Match(lines[i], charIndex)).Success)
                 {
                     do { tokenIndex++; } while (tokenIndex < tokens.Length && tokens[tokenIndex] == null);
                     if (tokenIndex == tokens.Length)
                     {
                         Console.Error.WriteLine(@"{0}({1},{2},{1},{3}): {4} CS9999: {5}",
                             f.FullName,
                             i + 1,
                             match.Index + 1,
                             match.Index + match.Length + 1,
                             errorOrWarning,
                             message
                         );
                         return;
                     }
                     charIndex = match.Index + match.Length;
                 }
             }
         }
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("Error: " + e.Message + " (" + e.GetType().FullName + ")");
     }
     Console.Error.WriteLine("{0} CS9999: {1}", errorOrWarning, message);
 }
Example #19
0
 /// <summary>
 /// Construct a <see cref="FaultException"/> describing the server side exception <paramref name="ex"/> for
 /// communication to a client.
 /// </summary>
 /// <param name="ex">The exception that occurred on the server</param>
 /// <param name="details">Optional arbitrary data associated with the exception</param>
 /// <remarks>
 /// Have been playing around with this a little, to see what can be passed back to the clients. Unsuccessful
 /// in transmitting inner exceptions and data dictionary in any exceptions. Not sure why. Does transmit the top
 /// level exception (except for data dictionary) back to the client correctly, which will do for now.
 /// 	-	Will look into these issues some point. Without inner exceptions debugging server code can be difficult.
 ///		(Server does, however, write exceptions, including inner exceptions, to console for now for debug purposes)
 /// </remarks>
 private FaultException Error(Exception ex, params object[] details)
 {
     StackFrame errorFrame = new StackFrame(1, true);
     MethodBase mb = errorFrame.GetMethod();
     MethodBody methodBody = mb.GetMethodBody();
     //			ParameterInfo[] pi = mb.GetParameters();
     StringBuilder action = new StringBuilder();
     action.AppendFormat("{0}:{1}.{2}(", mb.DeclaringType.Assembly.GetName().Name, mb.DeclaringType.FullName, mb.Name);
     //			for (int i = 0; i < pi.Length; i++)
     //				action.AppendFormat("\n\t{0}={1}{2}{3}", pi[i].Name, details[i].ToString().Contains('\n') ? "\n\t  " : "",
     //					details[i].ToString().Replace("\n", "\n\t  "), i == pi.Length - 1 && methodBody.LocalVariables.Count == 0 ? "" : ",");
     foreach (LocalVariableInfo lvInfo in methodBody.LocalVariables)
         action.AppendFormat("\n\t{0}", lvInfo.ToString());
     action.AppendFormat("){0}[{1}:{2},{3}]:\n{4}: {5}\n{6}\n", /*pi.Length > 0 ?*/ "\n", // : " ",
         errorFrame.GetFileName(), errorFrame.GetFileLineNumber(), errorFrame.GetFileColumnNumber(),
         ex.GetType().FullName, ex.Message, ex.StackTrace);
     string actionStr = action.ToString();
     if (Configuration.OutputExceptions)
         Console.WriteLine("\n{0}\n", actionStr);
     FaultException<ExceptionDetail> retEx = new FaultException<ExceptionDetail>(
         new ExceptionDetail(ex), actionStr, // ex.GetType().FullName + " caught on ArtefactService",
         FaultCode.CreateSenderFaultCode(errorFrame.GetMethod().Name, mb.DeclaringType.FullName),
         OperationContext.Current.IncomingMessageHeaders.Action);
     foreach (object detail in details)
         retEx.Data.Add(retEx.Data.Count, detail);
     return retEx;
 }
Example #20
0
 private MongoDbLogStackFrame ToStackFrame(StackFrame stackFrame)
 {
     return new MongoDbLogStackFrame()
     {
         Column      = stackFrame.GetFileColumnNumber(),
         Line        = stackFrame.GetFileLineNumber(),
         Filename    = stackFrame.GetFileName(),
         MethodName  = stackFrame.GetMethod().Name,
         TypeName    = stackFrame.GetMethod().DeclaringType.FullName
     };
 }
Example #21
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
    }
Example #22
0
		internal void SetDebugInfo(StackFrame/*!*/ frame)
		{
			this.line = frame.GetFileLineNumber();
			this.column = frame.GetFileColumnNumber();
			this.file = frame.GetFileName();
		}
        public static Action<Binding[], int> CreateMethodFrame(string description, StackFrame frame)
        {
            lock (Module)
            {
                const string methodName = " ";
                var className = description;
                if (ClassNames.Contains(className))
                {
                    className += " /" + ClassNames.Count;
                }
                ClassNames.Add(className);

                var type = Module.DefineType(className, TypeAttributes.Class | TypeAttributes.Public);
                var method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static, typeof(void), new[] { typeof(Binding[]), typeof(int) });
                method.SetImplementationFlags(MethodImplAttributes.NoOptimization);

                var il = method.GetILGenerator();

                var binding = il.DeclareLocal(typeof(Binding));
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldelem_I4);
                il.Emit(OpCodes.Stloc_S, binding);

                var fileName = frame?.GetFileName();
                if (!string.IsNullOrEmpty(fileName))
                {
                    var symbolDocument = Module.DefineDocument(fileName, SymDocumentType.Text, SymLanguageType.CSharp, SymLanguageVendor.Microsoft);
                    il.MarkSequencePoint(symbolDocument, frame.GetFileLineNumber(), frame.GetFileColumnNumber(), frame.GetFileLineNumber(), frame.GetFileColumnNumber() + 2);

                    method.DefineParameter(1, ParameterAttributes.None, "bindings");
                    method.DefineParameter(2, ParameterAttributes.None, "index");
                }

                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Call, typeof(Binding[]).GetProperty("Length").GetGetMethod());
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Sub);

                var lblFin = il.DefineLabel();
                il.Emit(OpCodes.Bge_S, lblFin);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Add);
                il.Emit(OpCodes.Ldelem_I4);
                il.Emit(OpCodes.Ldfld, typeof(Binding).GetField("DebugContext"));
                il.Emit(OpCodes.Callvirt, typeof(DebugContext).GetProperty("VirtualFrame").GetGetMethod());
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Add);
                il.Emit(OpCodes.Call, typeof(Action<Binding[], int>).GetMethod("Invoke"));
                il.Emit(OpCodes.Ret);
                il.MarkLabel(lblFin);
                il.Emit(OpCodes.Ldloc, binding);
                il.Emit(OpCodes.Callvirt, typeof(Binding).GetMethod("Execute"));
                il.Emit(OpCodes.Ret);

                if (!string.IsNullOrEmpty(fileName))
                {
                    binding.SetLocalSymInfo("binding", 0, il.ILOffset);
                }

                var actualType = type.CreateType();
                return (Action<Binding[], int>)actualType.GetMethod(methodName).CreateDelegate(typeof(Action<Binding[], int>));
            }
        }
Example #24
0
        /// <summary>
        /// ログを出力します。
        /// </summary>
        /// <remarks>
        /// メッセージには"プロセス名(プロセスID)-マネージスレッドID(ネイティブスレッドID): "が先頭に付与されます。
        /// </remarks>
        /// <param name="depth">ログの呼び出し元からのコールスタックの深さ</param>
        /// <param name="level">ログレベル</param>
        /// <param name="message">メッセージ</param>
        protected void Log(int depth, LogLevel level, string message)
        {
            if (!this.IsEnabled(level)) return;
            try
            {
                {
                    Process process;
                    int nativeThreadId;
                    int managedThreadId;
                    StackFrame frame;
                    string fileName;
                    int fileLineNumber;
                    int fileColumnNumber;
                    MethodBase method;
                    string className;
                    string methodName;

                    process = Process.GetCurrentProcess();
            #pragma warning disable 618
                    nativeThreadId = AppDomain.GetCurrentThreadId();
            #pragma warning restore 618
                    managedThreadId = Thread.CurrentThread.ManagedThreadId;
                    frame = new StackFrame(++depth);
                    fileName = frame.GetFileName();
                    if (fileName == null) fileName = "{unknown}";
                    fileLineNumber = frame.GetFileLineNumber();
                    fileColumnNumber = frame.GetFileColumnNumber();
                    method = frame.GetMethod();
                    className = method.DeclaringType.FullName;
                    methodName = method.Name;
                    if (".ctor".Equals(methodName)) methodName = "{constructor}";
                    message = String.Format(
                        "{0}({1:D})-{2:D}({3:D}): {4}::{5} ({6}:{7}-{8})\r\n{9}",
                        process.ProcessName, process.Id, managedThreadId, nativeThreadId,
                        className, methodName, fileName, fileLineNumber, fileColumnNumber,
                        message);
                }
                this.WriteLog(level, message);
            }
            catch (Exception)
            {
            #if DEBUG
                throw;
            #endif
            }
        }
Example #25
0
        /// <summary>
        /// Initialises a new instance of the FieldLogStackFrame class.
        /// </summary>
        /// <param name="stackFrame">The StackFrame instance.</param>
        public FieldLogStackFrame(StackFrame stackFrame)
        {
            MethodBase method = stackFrame.GetMethod();

            if (method.DeclaringType != null)
            {
                Module = method.DeclaringType.Module.FullyQualifiedName;
                Token = method.MetadataToken;
                ILOffset = stackFrame.GetILOffset();
                TypeName = FormatTypeName(method.DeclaringType);
            }
            MethodName = method.Name;

            // TODO: Include 'extern' indicator from the following tests (needs new file format)
            //bool isPInvoke = (method.Attributes & MethodAttributes.PinvokeImpl) != 0;
            //bool isInternalCall = (method.GetMethodImplementationFlags() & MethodImplAttributes.InternalCall) != 0;

            MethodInfo methodInfo = method as MethodInfo;
            StringBuilder sigSb = new StringBuilder();
            if (methodInfo != null)
            {
                sigSb.Append(FormatTypeName(methodInfo.ReturnType));
            }
            else
            {
                sigSb.Append("void");   // Dummy return value for constructors
            }
            ParameterInfo[] parameters = method.GetParameters();
            sigSb.Append("(");
            for (int i = 0; i < parameters.Length; i++)
            {
                if (i > 0)
                {
                    sigSb.Append(", ");
                }
                sigSb.Append(FormatTypeName(parameters[i].ParameterType));
            }
            sigSb.Append(")");
            MethodSignature = sigSb.ToString();

            FileName = stackFrame.GetFileName();
            Line = stackFrame.GetFileLineNumber();
            Column = stackFrame.GetFileColumnNumber();

            Size = (Module != null ? Module.Length * 2 : 0) +
                (TypeName != null ? TypeName.Length * 2 : 0) +
                (MethodName != null ? MethodName.Length * 2 : 0) +
                (MethodSignature != null ? MethodSignature.Length * 2 : 0) +
                (FileName != null ? FileName.Length * 2 : 0) +
                4 + 4;
        }
Example #26
0
 /// <summary>
 /// 获取追踪信息所在列
 /// </summary>
 /// <param name="frame"></param>
 /// <returns></returns>
 public static String GetColumnNumber(StackFrame frame)
 {
     const String unknow = "NULL";
     if (frame == null) return unknow;
     var columnNumber = frame.GetFileColumnNumber();
     return String.IsNullOrEmpty(columnNumber.ToString(CultureInfo.InvariantCulture))
         ? unknow
         : columnNumber.ToString(CultureInfo.InvariantCulture);
 }
        private static string StackFrameToString(StackFrame sf)
        {
            var sb = new StringBuilder();
            MemberInfo mi = sf.GetMethod();

            sb.AppendFormat("   {0}.{1}.{2}",
                mi.DeclaringType.Namespace,
                mi.DeclaringType.Name,
                mi.Name);

            ParameterInfo[] parameters = sf.GetMethod().GetParameters();
            sb.Append("(");
            sb.Append(String.Join(", ", parameters.Select(p => String.Format("{0} {1}", p.ParameterType.Name, p.Name)).ToArray()));
            sb.Append(")");
            sb.AppendLine();

            sb.Append("       ");
            if (String.IsNullOrEmpty(sf.GetFileName()))
            {
                sb.Append(Path.GetFileName(ParentAssembly.CodeBase));
                sb.Append(": N ");
                sb.AppendFormat("{0:#00000}", sf.GetNativeOffset());
            }
            else
            {
                sb.Append(Path.GetFileName(sf.GetFileName()));
                sb.AppendFormat(": line {0:#0000}, col {1:#00}", sf.GetFileLineNumber(), sf.GetFileColumnNumber());
                if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
                {
                    sb.AppendFormat(", IL {0:#0000}", sf.GetILOffset());
                }
            }
            sb.AppendLine();

            return sb.ToString();
        }
Example #28
0
 private static string StackFrameToString(StackFrame sf, ref string errorFrom)
 {
     StringBuilder sb = new StringBuilder();
     int intParam;
     MemberInfo mi = sf.GetMethod();
     Type type = mi.DeclaringType;
     string namspace = type.Namespace ?? string.Empty;
     if (namspace.Equals("ExamineSystem.utility.eslog"))
     {
         return sb.ToString();
     }
     if (string.IsNullOrEmpty(errorFrom))
     {
         try
         {
             if (type.IsSubclassOf(typeof(System.Web.UI.Page)))
             {
                 errorFrom = type.FullName;
             }
             else if (type.IsSubclassOf(typeof(System.Web.UI.Control)))
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpHandler") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpAsyncHandler") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpModule") != null)
             {
                 errorFrom = type.FullName;
             }
             else if (type.GetInterface("System.Web.IHttpHandlerFactory") != null)
             {
                 errorFrom = type.FullName;
             }
         }
         catch (Exception)
         {
             errorFrom = string.Empty;
         }
     }
     sb.Append("   ");
     sb.Append(namspace);
     sb.Append(".");
     sb.Append(type.Name);
     sb.Append(".");
     sb.Append(mi.Name);
     // -- build method params
     sb.Append("(");
     intParam = 0;
     foreach (ParameterInfo param in sf.GetMethod().GetParameters())
     {
         if (intParam > 0)
             sb.Append(" , ");
         sb.Append(param.Name);
         sb.Append(" As ");
         sb.Append(param.ParameterType.Name);
         intParam += 1;
     }
     sb.Append(")");
     sb.Append(Environment.NewLine);
     // -- if source code is available, append location info
     sb.Append("       ");
     if (string.IsNullOrEmpty(sf.GetFileName()))
     {
         sb.Append("(unknown file)");
         //-- native code offset is always available
         sb.Append(": N ");
         sb.Append(String.Format("{0:#00000}", sf.GetNativeOffset()));
     }
     else
     {
         sb.Append(System.IO.Path.GetFileName(sf.GetFileName()));
         sb.Append(": line ");
         sb.Append(String.Format("{0:#0000}", sf.GetFileLineNumber()));
         sb.Append(", col ");
         sb.Append(String.Format("{0:#00}", sf.GetFileColumnNumber()));
         if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
         {
             sb.Append(", IL ");
             sb.Append(String.Format("{0:#0000}", sf.GetILOffset()));
         }
     }
     sb.Append(Environment.NewLine);
     return sb.ToString();
 }
        //--
        //-- turns a single stack frame object into an informative string
        //--
        private static string StackFrameToString(StackFrame sf)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            int intParam = 0;
            MemberInfo mi = sf.GetMethod();

            var _with1 = sb;
            //-- build method name
            _with1.Append("   ");
            _with1.Append(mi.DeclaringType.Namespace);
            _with1.Append(".");
            _with1.Append(mi.DeclaringType.Name);
            _with1.Append(".");
            _with1.Append(mi.Name);

            //-- build method params
            ParameterInfo[] objParameters = sf.GetMethod().GetParameters();
            ParameterInfo objParameter = null;
            _with1.Append("(");
            intParam = 0;
            foreach (ParameterInfo objParameter_loopVariable in objParameters)
            {
                objParameter = objParameter_loopVariable;
                intParam += 1;
                if (intParam > 1)
                    _with1.Append(", ");
                _with1.Append(objParameter.Name);
                _with1.Append(" As ");
                _with1.Append(objParameter.ParameterType.Name);
            }
            _with1.Append(")");
            _with1.Append(Environment.NewLine);

            //-- if source code is available, append location info
            _with1.Append("       ");
            if (sf.GetFileName() == null || sf.GetFileName().Length == 0)
            {
                _with1.Append(System.IO.Path.GetFileName(ParentAssembly().CodeBase));
                //-- native code offset is always available
                _with1.Append(": N ");
                _with1.Append(string.Format("{0:#00000}", sf.GetNativeOffset()));
            }
            else
            {
                _with1.Append(System.IO.Path.GetFileName(sf.GetFileName()));
                _with1.Append(": line ");
                _with1.Append(string.Format("{0:#0000}", sf.GetFileLineNumber()));
                _with1.Append(", col ");
                _with1.Append(string.Format("{0:#00}", sf.GetFileColumnNumber()));
                //-- if IL is available, append IL location info
                if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
                {
                    _with1.Append(", IL ");
                    _with1.Append(string.Format("{0:#0000}", sf.GetILOffset()));
                }
            }
            _with1.Append(Environment.NewLine);
            return sb.ToString();
        }
Example #30
0
		/// <summary>
		/// Traces up the stack frame containing the method call that has caused an error.
		/// </summary>
		/// <returns>Found stack info.</returns>
		/// <remarks>
		/// Starts with a frame of a calling method and ends with the first frame belonging to user routine.
		/// If there was <see cref="ImplementsFunctionAttribute"/> found during the walk the last one's value
		/// is considered as the caller.
		/// If there was not such attribute found (error occured in an operator, directly in the code etc.) 
		/// the last inspected method's debug info is returned.
		/// If the trace ends up with a function or method inside transient assembly an eval hierarchy is inspected
		/// and added to the resulting source position information.
		/// </remarks>
		internal static ErrorStackInfo TraceErrorFrame(ScriptContext/*!*/ context)
		{
			Debug.Assert(context != null);

			ErrorStackInfo result = new ErrorStackInfo();
			int cl_function_idx = -1;
			string cl_function_name = null;
			StackFrame frame;
			int eval_id = TransientAssembly.InvalidEvalId;

			// stack trace without debug info is constructed:
#if !SILVERLIGHT
			StackTrace trace = new StackTrace(1, false);

			// note: method stack frame contains a debug info about the call to the callee
			// hence if we find a method that reported the error we should look the next frame 
			// to obtain a debug info

			int i = 0;
			for (; ; )
			{
				// gets frame:
				frame = trace.GetFrame(i++);

				// error has been thrown directly by Core without intermediary user code (all frames are invisible):
				if (frame == null)
				{
					// cl_function_idx can be non-minus-one here because a callback can be called directly from Core 
					// (e.g. output buffer filter targeting class library function):
					if (cl_function_idx != -1)
					{
						result.Caller = cl_function_name;
						result.LibraryCaller = true;
					}

					return result;
				}

				FrameKinds frame_kind = GetFrameKind(frame);

				if (frame_kind == FrameKinds.Visible)
				{
					MethodBase method = frame.GetMethod();

					int eid = TransientModule.GetEvalId(context.ApplicationContext, method);

					if (eval_id == TransientAssembly.InvalidEvalId)
						eval_id = eid;

					if (eid == TransientAssembly.InvalidEvalId)
						break;
				}
				else if (frame_kind == FrameKinds.ClassLibraryFunction)
				{
					MethodBase method = frame.GetMethod();

					cl_function_idx = i;
					cl_function_name = ImplementsFunctionAttribute.Reflect(method).Name;
				}
			}

			// skips i frames (the very first frame has been skipped in the previous 
			// trace construction and we want to skip i-1 frames from that trace => i frames totally):
			frame = new StackFrame(1 + i - 1, true);

			// extracts a source info (file & position):
			if (eval_id != TransientAssembly.InvalidEvalId)
			{
				FillEvalStackInfo(context, eval_id, ref result, false);
			}
			else
			{
				result.Line = frame.GetFileLineNumber();
				result.Column = frame.GetFileColumnNumber();
				result.File = frame.GetFileName();
			}

			// determines a caller (either a library function or a user function/method):
			if (cl_function_idx >= 0)
			{
				result.Caller = cl_function_name;
				result.LibraryCaller = true;
			}
			//else
			//{
			//  MethodBase method = frame.GetMethod();
			//  Type type = method.DeclaringType;

			//  // the caller has already been set by FillEvalStackInfo 
			//  // if we are in eval and the function is Main helper of the script type:
			//  if (eval_id == TransientAssembly.InvalidEvalId)
			//  {
			//    result.LibraryCaller = false;

			//    if (type != null)
			//    {
			//      result.Caller = String.Concat(DTypeDesc.MakeFullName(type), "::", DRoutineDesc.MakeFullName(method));
			//    }
			//    else
			//    {
			//      result.Caller = DRoutineDesc.MakeFullName(method);
			//    }  
			//  } 
			//}
#endif

            // add missing info about file and line
            context.LastErrorLine = result.Line;
            context.LastErrorFile = result.File;

            //
			return result;
		}
Example #31
0
 /// <summary>
 /// Assert the specified condition, logging result to <see cref="AutoTraceSource.Trace"/>
 /// </summary>
 /// <param name="condition">Condition</param>
 public void Assert(bool condition)
 {
     //Debug.Assert(condition);
     StackFrame sf = new StackFrame(1);
     if (condition)
         Trace.Log(Trace.Level.Verbose, "Assert OK at {0}+{1} (in file {2}:{3},{4}", sf.GetMethod().Name,
             sf.GetILOffset(), sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber());
     else
         Trace.Log(Trace.Level.Warning, "Assert FAILED at {0}+{1} (in file {2}:{3},{4})", sf.GetMethod().Name,
             sf.GetILOffset(), sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber());
 }
Example #32
0
 private static bool AreSameAddress(SourceAddress groupAddress, StackFrame frame)
 {
     return frame.GetFileLineNumber() - 1 == groupAddress.LineIndex
         && frame.GetFileColumnNumber() - 1 == groupAddress.ExpressionIndex
         && frame.GetFileName() == groupAddress.FileName;
 }
Example #33
0
        private CallingMethodInfo getStackFrameInfo(StackFrame stackFrame, bool onlyIncludeInfoWithFileLine)
        {
            var methodInfo = new CallingMethodInfo { StackTrace = string.Empty };

            if (stackFrame == null)
                return null;

            var method = stackFrame.GetMethod();
            if (method == null)
                return null;

            method = getRealMethodFromAsyncMethod(method);

            var type = method.ReflectedType;
            if (type == null)
                return null;

            var assemblyName = method.Module.Assembly.GetName().Name;
            if (_assembliesToExclude.Contains(assemblyName) ||
                _methodsToExclude.Contains(method.Name) ||
                shouldExcludeType(method) ||
                isMicrosoftType(method))
            {
                if (!WontExcludeTypes) return null;
            }

            var methodString = method.ToString();

            var returnName = string.Empty;
            var methodSignature = methodString;

            var splitIndex = methodString.IndexOf(' ');
            if (splitIndex > 0)
            {
                returnName = methodString.Substring(0, splitIndex);
                methodSignature = methodString.Substring(splitIndex + 1, methodString.Length - splitIndex - 1);
            }

            var typeNameFull = type.FullName;
            var lineNumber = stackFrame.GetFileLineNumber();

            var fileLine = string.Empty;
            var filePath = stackFrame.GetFileName();

            if (isTempFile(filePath))
                return null;

            if (!string.IsNullOrEmpty(filePath))
            {
                var fileName = Path.GetFileName(filePath);
                fileLine = string.Format("File={0}, Line={1}", fileName, lineNumber);

                methodInfo.CallingFile = fileName;
                methodInfo.CallingLine = lineNumber;
                methodInfo.CallingCol = stackFrame.GetFileColumnNumber();
                methodInfo.CallingFileFullName = filePath;
            }

            //there is no valid .pdb file
            if (onlyIncludeInfoWithFileLine && !File.Exists(filePath))
                return null;

            //couldn't extract the source file name
            if (onlyIncludeInfoWithFileLine && string.IsNullOrWhiteSpace(fileLine))
                return null;

            var methodSignatureFull = string.Format("{0} {1}.{2}", returnName, typeNameFull, methodSignature);
            methodInfo.CallingMethod = method.Name;
            methodInfo.StackTrace = string.Format("{0}", methodSignatureFull);
            methodInfo.AssemblyName = type.Assembly.FullName;

            return methodInfo;
        }
        private static string StackFrameToString(StackFrame sf)
        {
            var sb = new StringBuilder();
            MemberInfo mi = sf.GetMethod();

            sb.Append("   ");
            sb.Append(mi.DeclaringType.Namespace);
            sb.Append(".");
            sb.Append(mi.DeclaringType.Name);
            sb.Append(".");
            sb.Append(mi.Name);
            
            var objParameters = sf.GetMethod().GetParameters();
            sb.Append("(");
            
            var intParam = 0;
            
            foreach (var objParameter in objParameters)
            {
                intParam++;
                if (intParam > 1)
                {
                    sb.Append(", ");
                }
                sb.Append(objParameter.Name);
                sb.Append(" As ");
                sb.Append(objParameter.ParameterType.Name);
            }
            sb.Append(")");
            sb.Append(Environment.NewLine);
            sb.Append("       ");
            if ((sf.GetFileName() == null) || (sf.GetFileName().Length == 0))
            {
                sb.Append(Path.GetFileName(ParentAssembly().CodeBase));
                sb.Append(": N ");
                sb.Append(string.Format("{0:#00000}", sf.GetNativeOffset()));
            }
            else
            {
                sb.Append(Path.GetFileName(sf.GetFileName()));
                sb.Append(": line ");
                sb.Append(string.Format("{0:#0000}", sf.GetFileLineNumber()));
                sb.Append(", col ");
                sb.Append(string.Format("{0:#00}", sf.GetFileColumnNumber()));
                if (sf.GetILOffset() != -1)
                {
                    sb.Append(", IL ");
                    sb.Append(string.Format("{0:#0000}", sf.GetILOffset()));
                }
            }
            sb.Append(Environment.NewLine);
            
            return sb.ToString();
        }