/// <summary> /// Initializes a new instance of the <see cref="StackFrame" /> class. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="frameContext">The frame context.</param> internal StackFrame(StackTrace stackTrace, ThreadContext frameContext) { StackTrace = stackTrace; FrameContext = frameContext; sourceFileNameAndLine = SimpleCache.Create(ReadSourceFileNameAndLine); functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement); locals = SimpleCache.Create(GetLocals); arguments = SimpleCache.Create(GetArguments); clrStackFrame = SimpleCache.Create(() => Thread.ClrThread?.StackTrace.Where(f => f.InstructionPointer == InstructionOffset).FirstOrDefault()); userTypeConvertedLocals = SimpleCache.Create(() => { VariableCollection collection = Variable.CastVariableCollectionToUserType(locals.Value); GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedLocals); return collection; }); userTypeConvertedArguments = SimpleCache.Create(() => { VariableCollection collection = Variable.CastVariableCollectionToUserType(arguments.Value); GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedArguments); return collection; }); module = SimpleCache.Create(() => { var m = Process.GetModuleByInnerAddress(InstructionOffset); if (m == null && ClrStackFrame != null) m = Process.ClrModuleCache[ClrStackFrame.Module]; return m; }); }
public void SetAlarm(bool status) { StackTrace st = new StackTrace(); print(st.GetFrame(1).GetMethod().Name); //print("ALARM SET"); if (status) { foreach (Light l in lights) { l.intensity = 8; l.color = Color.red; if(l.name != "EnemyCamera") l.GetComponent<AudioSource>().Play(); } } else { foreach (Light l in lights) { if (l.name != "EnemyCamera") { l.intensity = 1; l.color = Color.white; l.GetComponent<AudioSource>().Pause(); } else { l.color = Color.green; l.intensity = 10; } } } }
/// <summary> /// Initializes a new instance of the <see cref="ClrThread"/> class. /// </summary> /// <param name="thread">The thread.</param> /// <param name="clrThread">The CLR thread.</param> /// <param name="process">The process.</param> internal ClrThread(Thread thread, Microsoft.Diagnostics.Runtime.ClrThread clrThread, Process process) : base(thread != null ? thread.Id : uint.MaxValue, clrThread.OSThreadId, process) { ClrThread = clrThread; runtime = SimpleCache.Create(() => Process.ClrRuntimes.Single(r => r.ClrRuntime == clrThread.Runtime)); appDomain = SimpleCache.Create(() => Runtime.AppDomains.Single(a => a.ClrAppDomain.Address == clrThread.AppDomain)); clrStackTrace = SimpleCache.Create(() => { StackTrace stackTrace = new StackTrace(this); uint frameNumber = 0; stackTrace.Frames = ClrThread.StackTrace.Where(f => f.Method != null).Select(f => { return new StackFrame(stackTrace, new ThreadContext(f.InstructionPointer, f.StackPointer, ulong.MaxValue)) { FrameNumber = frameNumber++, InstructionOffset = f.InstructionPointer, StackOffset = f.StackPointer, FrameOffset = ulong.MaxValue, ReturnOffset = ulong.MaxValue, ClrStackFrame = f, }; }).ToArray(); return stackTrace; }); lastThrownException = SimpleCache.Create(() => ClrThread.CurrentException != null ? new ClrException(this, ClrThread.CurrentException) : null); }
private static string GetCallingMethod(StackTrace stack) { StackFrame frame = stack.GetFrame(0); string className = frame.GetMethod().DeclaringType.ToString(); string functionName = frame.GetMethod().Name; return string.Format("{0}.{1}", className, functionName); }
/// <summary> /// The object to lock. /// </summary> /// <param name="o">The object to lock.</param> /// <param name="timeout">The timeout.</param> /// <returns></returns> /// <exception cref="LockTimeoutException"> /// </exception> public static TimedLock Lock(object o, TimeSpan timeout) { var tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { #if DEBUG GC.SuppressFinalize(tl._leakDetector); StackTrace blockingTrace; lock (Sentinel.StackTraces) { blockingTrace = Sentinel.StackTraces[o] as StackTrace; } throw new LockTimeoutException(blockingTrace); #else throw new LockTimeoutException(); #endif } #if DEBUG // Lock acquired. Store the stack trace. var trace = new StackTrace(); lock (Sentinel.StackTraces) { Sentinel.StackTraces.Add(o, trace); } #endif return tl; }
void RecursiveAddFilteredChildren (StackTrace trace) { if (Store.Options.Filters.Contains (trace.TopMethod.Class.Assembly.BaseName)) foreach (StackTrace child in trace.CalledFrames) RecursiveAddFilteredChildren (child); else children.Add (new CallsNode (Store, this, trace)); }
public static void PrintMethodName() { StackTrace st = new StackTrace (); StackFrame sf = st.GetFrame (1); MethodBase currentMethodName = sf.GetMethod (); UnityEngine.Debug.Log ("I'm in "+currentMethodName); }
// Constructor public CallerInfo(StackTrace trace) { this = new CallerInfo(); MethodName = trace.GetFrame(1).GetMethod().Name; ClassName = trace.GetFrame(1).GetMethod().ReflectedType.Name; FileName = trace.GetFrame(1).GetFileName(); LineNumber = trace.GetFrame(1).GetFileLineNumber(); }
public static void WriteString(string message) { OpenLogFile(); string caller = new StackTrace().GetFrame(1).GetMethod().Name; sw.WriteLine("{0:G} {1}:: {2}\n", System.DateTime.Now, caller, message); logUsed = true; CloseLogFile(); }
public static void log(string msg, params object[] objs) { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(1); Console.Write("[{0}({1})] ", sf.GetFileName(), sf.GetFileLineNumber()); Console.WriteLine(msg, objs); }
public TestMessage(string m, StackTrace t, Exception e) { message = m; if(t != null) trace = FilterStackTrace(t); exception = e; FilterStackTrace(t); }
/// <summary> /// Returns the <see cref="MethodBase"/> object identiying the caller of the current method. /// </summary> /// <returns>The MethodBase object of the caller of the current method.</returns> public static MethodBase CallingMethod() { var stack = new StackTrace(); var frame = stack == null ? null : stack.GetFrame( 2 ); var method = frame == null ? null : frame.GetMethod(); return method; }
public static void Assert(bool condition, string exprTag) { if (!condition) { StackTrace st = new StackTrace(new StackFrame(true)); StackFrame sf = st.GetFrame(1); throw new Exception("Assertion( " + exprTag + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + "."); } }
/// <summary> /// Returns a string in the form "Type.Method" identifying the caller of the current method. /// </summary> /// <returns>A string identifying the caller of the current method.</returns> public static string CalledFrom() { var stack = new StackTrace(); var frame = stack == null ? null : stack.GetFrame( 2 ); var method = frame == null ? null : frame.GetMethod(); if( method == null ) return "n/a"; return string.Format( "{0}.{1}", method.DeclaringType.Name, method.Name ); }
static void _Log(string message, LOG_TYPE log_type) { var st = new StackTrace(true); var sf = st.GetFrame(2); var fpath = sf.GetFileName(); var fline = sf.GetFileLineNumber(); XCon.Inst.Log(new LogData{message= message, fpath= fpath, fline= fline, log_type= log_type}); }
public static void Assert(bool condition) { if (!condition) { StackTrace st = new StackTrace(new StackFrame(true)); StackFrame sf = st.GetFrame(1); UnityEngine.Debug.LogError("Assertion( " + sf.ToString() + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + "."); throw new Exception(); } }
public static void Main() { StackTrace stackTrace = new StackTrace(); // get call stack StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) // write call stack method names foreach (StackFrame stackFrame in stackFrames) { Console.WriteLine(stackFrame.GetMethod().Name); // write method name } }
public static void ResolveCallback(IAsyncResult ar) { Console.WriteLine("ResolveCallback()"); StackTrace st = new StackTrace(); frame_count = st.FrameCount; for(int i = 0; i < st.FrameCount; i++) { StackFrame sf = st.GetFrame(i); Console.WriteLine("method: {0}", sf.GetMethod()); } Console.WriteLine("ResolveCallback() complete"); }
public static GameObject InstantiatePrefab(GameObject prefab, Vector3 location, Quaternion rotation) { StackTrace st = new StackTrace(true); GameObject obj = Instantiate(prefab,location,rotation) as GameObject; objects.Add(obj, st.GetFrame(1)); obj.AddComponent<FancyGizmos>(); return obj; }
private static int ExecuteScript(string script, string arguments, out string output) { StackFrame sf = new StackFrame(true); StackTrace st = new StackTrace(sf); sf = st.GetFrame(0); string dir = Path.GetDirectoryName(sf.GetFileName()); string fileName = Path.Combine(dir, script); AddExecutablePermissionToScript(fileName); return Execute(fileName, arguments, out output); }
public void LogCallMethod(bool isStart) { var stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); if (isStart) { SiAuto.Main.EnterMethod(this, methodBase.Name); } else { SiAuto.Main.LeaveMethod(this, methodBase.Name); } }
/// <summary> /// Writes event to log file specified above. /// </summary> /// <param name="output"></param> public static void write(string output) { if (logToFile) { StackTrace st = new StackTrace (true); // TODO: Colan commented it out because it isn't used int lineNumber = st.GetFrame (1).GetFileLineNumber (); // Output format: "(Time delta from program start in format m:ss.sss) :: (Log message)" writer.WriteLine (string.Format ("{0:00}:{1:00.000}", Time.realtimeSinceStartup / 60, Time.realtimeSinceStartup % 60f) + " :: \"" + st.GetFrame (1).GetMethod ().ReflectedType.Name + "\" (Line: " + lineNumber + ") :: " + output); // Flushes buffer to force a write writer.Flush (); } }
public static string GetStackTrace(string indent) { #if SILVERLIGHT var trace = new System.Diagnostics.StackTrace().ToString(); #elif PORTABLE var trace = new StackTrace().ToString(); #else var skipCount = new System.Diagnostics.StackTrace().GetFrames().TakeWhile(frame => frame.GetMethod().DeclaringType.Assembly == typeof(DebugView).Assembly).Count(); var trace = new System.Diagnostics.StackTrace(skipCount, true).ToString(); #endif return "\n".Join(trace .Split('\n') .Select(p => indent + p.Trim())); }
private static bool GetProtectionDomains(List<java.security.ProtectionDomain> array, [email protected] callerID, StackTrace stack) { // first we have to skip all AccessController related frames, because we can be called from a doPrivileged implementation (not the privileged action) // in which case we should ignore the doPrivileged frame int skip = 0; for (; skip < stack.FrameCount; skip++) { Type type = stack.GetFrame(skip).GetMethod().DeclaringType; if (type != typeof(Java_java_security_AccessController) && type != typeof(java.security.AccessController)) { break; } } java.security.ProtectionDomain previous_protection_domain = null; for (int i = skip; i < stack.FrameCount; i++) { bool is_privileged = false; java.security.ProtectionDomain protection_domain; MethodBase method = stack.GetFrame(i).GetMethod(); if (method.DeclaringType == typeof(java.security.AccessController) && method.Name == "doPrivileged") { is_privileged = true; java.lang.Class caller = callerID.getCallerClass(); protection_domain = caller == null ? null : Java_java_lang_Class.getProtectionDomain0(caller); } else if (Java_sun_reflect_Reflection.IsHideFromStackWalk(method)) { continue; } else { protection_domain = GetProtectionDomainFromType(method.DeclaringType); } if (previous_protection_domain != protection_domain && protection_domain != null) { previous_protection_domain = protection_domain; array.Add(protection_domain); } if (is_privileged) { return true; } } return false; }
public static void CallStack() { // This method reports the callstack (not including the current class). StackTrace st = new StackTrace(true); Int32 StackCount = st.FrameCount; for (Int32 StackNo = 2; StackNo < StackCount; StackNo++) { StackFrame sf = st.GetFrame(StackNo); string Caller = string.Format("{0} (line {1})", sf.GetMethod().DeclaringType.FullName, sf.GetFileLineNumber()); Debug.WriteLine(string.Format("{0}: {1}", ClassTimeAndDate.HhMmSs(DateTime.Now), Caller)); } }
private static void TriggerAssert(string message) { var myTrace = new StackTrace(true); var myFrame = myTrace.GetFrame(2); var assertMsg = "Assert Hit! \n\n" + message + "\n\n" + "Filename: " + myFrame.GetFileName() + "\nMethod: " + myFrame.GetMethod() + "\nLine: " + myFrame.GetFileLineNumber(); #if UNITY_EDITOR switch (_handleMethod) { case AssertHandleMethod.LogAndContinue: Debug.LogError(assertMsg); break; case AssertHandleMethod.MessageBox: if (!_shouldStop) { var choice = EditorUtility.DisplayDialogComplex("Assert Hit!", assertMsg, "Go To", "Ignore", "Stop"); Debug.LogError(assertMsg); if (choice == 0 || choice == 2) { EditorApplication.isPlaying = false; _shouldStop = true; } if (choice == 0) { InternalEditorUtility.OpenFileAtLineExternal(myFrame.GetFileName(), myFrame.GetFileLineNumber()); } } break; case AssertHandleMethod.Exception: throw new AssertException(assertMsg); default: Util.Assert(false); break; } #endif }
public void Abort() { lock (this.ThisLock) { if (this.State == LifetimeState.Closed || this.aborted) return; #if DEBUG_EXPENSIVE if (closeStack == null) closeStack = new StackTrace(); #endif this.aborted = true; this.state = LifetimeState.Closing; } this.OnAbort(); this.state = LifetimeState.Closed; }
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } #if !NET_CF StackTraceUsage stu = targets.GetStackTraceUsage(); if (stu != StackTraceUsage.None && !logEvent.HasStackTrace) { StackTrace stackTrace; #if !SILVERLIGHT stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource); #else stackTrace = new StackTrace(); #endif int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType); logEvent.SetStackTrace(stackTrace, firstUserFrame); } #endif int originalThreadId = Thread.CurrentThread.ManagedThreadId; AsyncContinuation exceptionHandler = ex => { if (ex != null) { if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } } }; for (var t = targets; t != null; t = t.NextInChain) { if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler)) { break; } } }
/// <summary> /// Performs a stack trace to see where things went wrong /// for error reporting. /// </summary> public static string GetErrorLocation(int level = 1) { StackTrace stackTrace = new StackTrace(); string result = ""; string declaringType = ""; for (int v = stackTrace.FrameCount - 1; v > level; v--) { if (v < stackTrace.FrameCount - 1) result += " --> "; StackFrame stackFrame = stackTrace.GetFrame(v); if (stackFrame.GetMethod().DeclaringType.ToString() == declaringType) result = ""; // only report the last called method within every class declaringType = stackFrame.GetMethod().DeclaringType.ToString(); result += declaringType + ":" + stackFrame.GetMethod().Name; } return result; }
private void InserirErro(Exception e) { string sDiretorio = ConfigurationSettings.AppSettings["LogDirectory"].ToString(); if (!Directory.Exists(@sDiretorio)) Directory.CreateDirectory(@sDiretorio); StackTrace stacktrace = new StackTrace(); StackFrame[] stackframes = stacktrace.GetFrames(); string Classe = stacktrace.GetFrame(1).GetMethod().ReflectedType.Name; string Metodo = stacktrace.GetFrame(1).GetMethod().Name; StreamWriter oSw = File.AppendText(@sDiretorio + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"); oSw.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm.ss") + " > Class{ " + Classe + " } : Listar{ " + Metodo + " } - Message{ " + e.Message + " }"); oSw.Flush(); oSw.Close(); oSw = null; }
private static bool isCondition() { string varName = FormDebug.conditionName.ToLower(); Primitive varValue = FormDebug.conditionValue; varValue = Text.ConvertToLowerCase(varValue); if (varName == "" || varValue == "") { return(false); } try { if (applicationThread.ThreadState != System.Threading.ThreadState.Running) { applicationThread.Suspend(); } StackTrace stackTrace = new StackTrace(applicationThread, false); StackFrame frame = stackTrace.GetFrame(stackTrace.FrameCount - 1); MethodBase method = frame.GetMethod(); Type type = method.DeclaringType; FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { Primitive var = (Primitive)(fields[i].GetValue(null)); var = Text.ConvertToLowerCase(var); int pos = varName.IndexOf("["); string variable = pos < 0 ? varName : varName.Substring(0, pos); if (fields[i].Name.ToLower() == variable) { string arrayName = fields[i].Name.ToLower(); if (SBArray.IsArray(var)) { Primitive Indices1 = SBArray.GetAllIndices(var); for (int j = 1; j <= SBArray.GetItemCount(Indices1); j++) { Primitive var1 = var[Indices1[j]]; arrayName = ((string)(fields[i].Name + "[" + Indices1[j] + "]")).ToLower(); if (SBArray.IsArray(var1)) { Primitive Indices2 = SBArray.GetAllIndices(var1); for (int k = 1; k <= SBArray.GetItemCount(Indices2); k++) { Primitive var2 = var1[Indices2[k]]; arrayName = ((string)(fields[i].Name + "[" + Indices1[j] + "]" + "[" + Indices2[k] + "]")).ToLower(); if (SBArray.IsArray(var2)) { Primitive Indices3 = SBArray.GetAllIndices(var2); for (int l = 1; l <= SBArray.GetItemCount(Indices3); l++) { Primitive var3 = var2[Indices3[l]]; arrayName = ((string)(fields[i].Name + "[" + Indices1[j] + "]" + "[" + Indices2[k] + "]" + "[" + Indices3[l] + "]")).ToLower(); if (arrayName.StartsWith(varName) && checkCondition(var3, varValue)) { return(true); } } } else { if (arrayName.StartsWith(varName) && checkCondition(var2, varValue)) { return(true); } } } } else { if (arrayName.StartsWith(varName) && checkCondition(var1, varValue)) { return(true); } } } } else { if (checkCondition(var, varValue)) { return(true); } } } } return(false); } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); if (Utilities.bShowErrors) { TextWindow.WriteLine("ThreadState " + applicationThread.ThreadState.ToString()); } return(false); } }
/** * Print a log entry for TextureReplacer. `String.Format()`-style formatting is supported. */ public static void log(string s, params object[] args) { Type callerClass = new StackTrace(1, false).GetFrame(0).GetMethod().DeclaringType; UnityEngine.Debug.Log("[TR." + callerClass.Name + "] " + String.Format(s, args)); }
//-- //-- enhanced stack trace generator (no params) //-- private static string EnhancedStackTrace() { StackTrace objStackTrace = new StackTrace(true); return(EnhancedStackTrace(objStackTrace, "ExceptionManager")); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { string defaultDir = "C:\\\\ant\\\\_03_LinearModel\\\\_04_LinearSupportVectorRegression\\\\"; string dataFile = null; string targetFile = null; string resultFile = "result.txt"; string workingDir = null; bool fit = false; string Logs = ""; //Optional Data: double C = 1.0; string loss = "epsilon_insensitive"; double epsilon = 0.1; bool dual = true; double tol = 1e-4; bool fit_intercept = true; double intercept_scaling = 1.0; int verbose = 0; string random_state = "None"; int max_iter = 1000; List <double> predicTData = new List <double>(); if (!DA.GetData(0, ref dataFile)) { return; } if (dataFile == null) { return; } if (!DA.GetData(1, ref targetFile)) { return; } if (targetFile == null) { return; } if (!DA.GetData(2, ref workingDir)) { return; } if (workingDir == null) { return; } if (!DA.GetDataList(3, predicTData)) { return; } if (predicTData == null) { return; } if (!DA.GetData(4, ref fit)) { return; } if (fit == false) { return; } long ticks0 = DateTime.Now.Ticks; try { DA.GetData(5, ref C); DA.GetData(6, ref loss); DA.GetData(7, ref epsilon); DA.GetData(8, ref dual); DA.GetData(9, ref tol); DA.GetData(10, ref fit_intercept); DA.GetData(11, ref intercept_scaling); DA.GetData(12, ref verbose); DA.GetData(13, ref random_state); DA.GetData(14, ref max_iter); } catch (Exception ex) { var st = new StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += line.ToString() + "\n"; } // 01 Specify the working directory at which pythonFile exists, note that this Python file should run separately using Proccess2 (see 5). process2.StartInfo.WorkingDirectory = workingDir; try { // 02 Initiate helperFunctions HelperFunction helpFunctions = new HelperFunction(); // Put inputData in one list of strings. List <string> dataInput = new List <string>(new string[] { C.ToString(), @"'" + loss + @"'", epsilon.ToString(), dual == true?"True":"False", tol.ToString(), fit_intercept == true?"True":"False", intercept_scaling.ToString(), verbose.ToString(), @"'" + random_state + @"'", max_iter.ToString() }); // 03 Convert data from grasshopper syntax to python NumPy like array. string newString = helpFunctions.dataInput2Python(workingDir, predicTData); // 04 Write the Python file in the working directory helpFunctions.PythonFile(defaultDir, dataFile, targetFile, workingDir, resultFile, newString, "True", workingDir + "logFile.txt", allResources._04_LinearSupportVectorRegressionPy, dataInput); } catch (Exception e) { this.Message = e.ToString(); } // 05 Start running Python file. and wait until it is closed i.e. raising the process_Exited event. process2.Start(); while (!processhasexit) { } try { doc.Load(workingDir + "res.xml"); //TODO : add all the output variables here //AllData = {"prediction":result, "score":sroce, "support":support, "support_vectors":support_vectors, "n_support": n_support, "dual_coef": dual_coef, "coef": coeff, "intercept":intercept} XmlNode res_node = doc.DocumentElement.SelectSingleNode("/result/prediction"); XmlNode score_node = doc.DocumentElement.SelectSingleNode("/result/score"); XmlNode coef_node = doc.DocumentElement.SelectSingleNode("/result/coef"); XmlNode intercept_node = doc.DocumentElement.SelectSingleNode("/result/intercept"); string res = res_node.InnerText; string score = score_node.InnerText; string coef = coef_node.InnerText; string intercept = intercept_node.InnerText; //string res = System.IO.File.ReadAllText(workingDir + "result.txt"); res = res.Replace("[", "").Replace("]", ""); DA.SetData(1, res); DA.SetData(2, score); DA.SetData(3, coef); DA.SetData(4, intercept); long ticks1 = DateTime.Now.Ticks; double timeElaspsed = ((double)ticks1 - (double)ticks0) / 10000000; Logs += "Success !! in : " + timeElaspsed + " Seconds\n "; } catch (Exception e) { var st = new StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logs += e.Message + line.ToString() + "\n"; } DA.SetData(0, Logs); processhasexit = false; }
IEnumerator LoadMods() { loading.transform.GetChild(2).GetComponent <Text>().text = string.Format("MSCLoader <color=green>v{0}</color>", Version); ModConsole.Print("Loading mods..."); Stopwatch s = new Stopwatch(); s.Start(); ModConsole.Print("<color=#505050ff>"); loading.SetActive(true); loading.transform.GetChild(3).GetComponent <Slider>().minValue = 1; loading.transform.GetChild(3).GetComponent <Slider>().maxValue = LoadedMods.Count - 2; int i = 1; foreach (Mod mod in LoadedMods) { loading.transform.GetChild(0).GetComponent <Text>().text = string.Format("Loading mods: <color=orage><b>{0}</b></color> of <color=orage><b>{1}</b></color>. Please wait...", i, LoadedMods.Count - 2); loading.transform.GetChild(3).GetComponent <Slider>().value = i; loading.transform.GetChild(3).GetChild(1).GetChild(0).GetComponent <Image>().color = new Color32(0, 113, 0, 255); if (mod.ID.StartsWith("MSCLoader_")) { continue; } i++; if (!mod.isDisabled) { loading.transform.GetChild(1).GetComponent <Text>().text = mod.Name; } yield return(new WaitForSeconds(.05f)); try { if (!mod.isDisabled) { mod.OnLoad(); FsmHook.FsmInject(GameObject.Find("ITEMS"), "Save game", mod.OnSave); } } catch (Exception e) { StackFrame frame = new StackTrace(e, true).GetFrame(0); string errorDetails = string.Format("{2}<b>Details: </b>{0} in <b>{1}</b>", e.Message, frame.GetMethod(), Environment.NewLine); ModConsole.Error(string.Format("Mod <b>{0}</b> throw an error!{1}", mod.ID, errorDetails)); UnityEngine.Debug.Log(e); } } loading.SetActive(false); ModConsole.Print("</color>"); allModsLoaded = true; ModSettings_menu.LoadBinds(); IsModsDoneLoading = true; s.Stop(); if (s.ElapsedMilliseconds < 1000) { ModConsole.Print(string.Format("Loading mods completed in {0}ms!", s.ElapsedMilliseconds)); } else { ModConsole.Print(string.Format("Loading mods completed in {0} sec(s)!", s.Elapsed.Seconds)); } }
private static void DoLog(LogEntry.LogTypes logType, DateTime timeStamp, string message, StackTrace stacktrace, object[] oparams, Exception exception) { DoLog(new LogEntry( logType, timeStamp, message, stacktrace, oparams, exception, System.Threading.Thread.CurrentThread )); }
private void AddStack(object who) { m_stacks[who] = new StackTrace(true); }
public void CheckTheChangeInDefinitionTable() { DataTable dTable = new DataTable(); using (SqlConnection sConnection = new SqlConnection("Data Source=(localdb)MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False")) { try { /* Possible exception .open() cause*/ /* Invalid operation exception, Sql exception, Configuration.Configuration error exception */ sConnection.Open(); } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); sqlExMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } using (SqlCommand sCommand = new SqlCommand("[dbo].[GET_definitiontablewiththehelpofURLAddress", sConnection)) { sCommand.CommandType = CommandType.StoredProcedure; sCommand.Parameters.AddWithValue("@URLAddress", urlAddress); using (SqlDataAdapter sAdapter = new SqlDataAdapter(sCommand)) { try { /*Possible Exception .fill(...) cause*/ /*Invalid operation exception */ sAdapter.Fill(dTable); } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); sqlExMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } } } } foreach (DataRow dRow in dTable.Rows) { try { /* Possible exceptions .ToInt32(...) cause */ /*Format exception, Invalid cast exception, Overflow exception */ timeoutValue = Convert.ToInt32(dRow["TimeoutValue"]); sleepTime = Convert.ToInt32(dRow["SleepTime"]); /* Possible exceptions .ToBoolean(...) cause */ /*Format exception, Invalid cast exception */ isActive = Convert.ToBoolean(dRow["isActive"]); } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); sqlExMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } hourInformation = dRow["hourinformation"].ToString(); daysOfWeekAsNumber = dRow["daysofweekasnumber"].ToString(); } }
/// <summary><para> /// Several routines within the trace implementation require that the line and module and method information are /// generated for the statement that they are on. This routine generates a stack trace from its current location /// then walks back up the trace until it finds the first stack frame that is not related to the trace library. /// this frame is the frame that the calling code was and this information is then returned in the ref parameters.</para> /// </summary> /// <param name="className">The classname where the code was called from</param> /// <param name="methodName">The method name where the code was called from</param> /// <param name="fileName">The filename containing the code where this was called from</param> /// <param name="lineNumber">The line number that the calling line of code was on relative to the filename</param> /// <param name="parameters">The parameter information</param> /// <param name="getParameters">Determines whether or not extra work should be done to populate the parameters field. If this is false parameters returns an empty string</param> internal void GetStackInfoBeforeTraceClass(out string className, out string methodName, out string fileName, out string lineNumber, out string parameters, bool getParameters) { /* This method is called a lot for all of the stack information that is written. It is surprisingly slow and is the single biggest * overhead in all of the logging. During Tex 2.0.x.x there were methods which hard coded starting at Stacktrace(4) but that made * the code significantly more complex and added only a tiny performance gain. Therefore I reverted this code back to its current * state. */ parameters = string.Empty; lineNumber = string.Empty; fileName = string.Empty; methodName = string.Empty; className = string.Empty; bool queryFileInformation = AllowedFileIOPermission();; // We skip the first two frames as we know there are always at least two Tex methods above this call. StackTrace currentStack = new StackTrace(2, queryFileInformation); for (int frameIdx = 0; frameIdx < currentStack.FrameCount; frameIdx++) // go through the stack frames { StackFrame nextFrame = currentStack.GetFrame(frameIdx); MethodBase theMethod = nextFrame.GetMethod(); className = InternalUtil.GetClassNameFromMethodbase(theMethod); if (theMethod.ReflectedType.Assembly == InternalUtil.TraceAssemblyCache) { // skip anything in this assembly. continue; } methodName = theMethod.Name; if (queryFileInformation) { lineNumber = nextFrame.GetFileLineNumber().ToString(); fileName = Path.GetFileName(nextFrame.GetFileName()); } else { fileName = string.Empty; lineNumber = "0"; } if (getParameters) { // Retested this a couple of times, the stringbuilder is consistantly slower. ParameterInfo[] prams = theMethod.GetParameters(); int parameterIndex = 0; parameters = "( "; while (parameterIndex < prams.Length) { parameters += prams[parameterIndex].ParameterType.Name + " " + prams[parameterIndex].Name; parameterIndex++; if (parameterIndex != prams.Length) { parameters += ", "; } } parameters += " )"; } return; } }
public static DynamicStackFrame[] GetDynamicStackFrames(Exception e, bool filter) { List <DynamicStackFrame> frames = e.Data[typeof(DynamicStackFrame)] as List <DynamicStackFrame>; if (frames == null) { // we may have missed a dynamic catch, and our host is looking // for the exception... frames = ExceptionHelpers.AssociateDynamicStackFrames(e); ExceptionHelpers.DynamicStackFrames = null; } if (frames == null) { return(new DynamicStackFrame[0]); } if (!filter) { return(frames.ToArray()); } #if !SILVERLIGHT frames = new List <DynamicStackFrame>(frames); List <DynamicStackFrame> res = new List <DynamicStackFrame>(); // the list of _stackFrames we build up in ScriptingRuntimeHelpers can have // too many frames if exceptions are thrown from script code and // caught outside w/o calling GetDynamicStackFrames. Therefore we // filter down to only script frames which we know are associated // w/ the exception here. try { StackTrace outermostTrace = new StackTrace(e); IList <StackTrace> otherTraces = ExceptionHelpers.GetExceptionStackTraces(e) ?? new List <StackTrace>(); List <StackFrame> clrFrames = new List <StackFrame>(); foreach (StackTrace trace in otherTraces) { clrFrames.AddRange(trace.GetFrames() ?? new StackFrame[0]); // rare, sometimes GetFrames returns null } clrFrames.AddRange(outermostTrace.GetFrames() ?? new StackFrame[0]); // rare, sometimes GetFrames returns null int lastFound = 0; foreach (StackFrame clrFrame in InterpretedFrame.GroupStackFrames(clrFrames)) { MethodBase method = clrFrame.GetMethod(); for (int j = lastFound; j < frames.Count; j++) { MethodBase other = frames[j].GetMethod(); // method info's don't always compare equal, check based // upon name/module/declaring type which will always be a correct // check for dynamic methods. if (method.Module == other.Module && method.DeclaringType == other.DeclaringType && method.Name == other.Name) { res.Add(frames[j]); frames.RemoveAt(j); lastFound = j; break; } } } } catch (MemberAccessException) { // can't access new StackTrace(e) due to security } return(res.ToArray()); #else return(frames.ToArray()); #endif }
private AirbrakeTraceLine[] BuildBacktrace(Exception exception, out MethodBase catchingMethod) { Assembly assembly = Assembly.GetExecutingAssembly(); if (assembly.EntryPoint == null) { assembly = Assembly.GetCallingAssembly(); } if (assembly.EntryPoint == null) { assembly = Assembly.GetEntryAssembly(); } catchingMethod = assembly == null ? null : assembly.EntryPoint; List <AirbrakeTraceLine> lines = new List <AirbrakeTraceLine>(); var stackTrace = new StackTrace(exception); StackFrame[] frames = stackTrace.GetFrames(); if (frames == null || frames.Length == 0) { // Airbrake requires that at least one line is present in the XML. AirbrakeTraceLine line = new AirbrakeTraceLine("none", 0); lines.Add(line); return(lines.ToArray()); } foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); catchingMethod = method; int lineNumber = frame.GetFileLineNumber(); if (lineNumber == 0) { //this.log.Debug(f => f("No line number found in {0}, using IL offset instead.", method)); lineNumber = frame.GetILOffset(); } string file = frame.GetFileName(); if (String.IsNullOrEmpty(file)) { // ReSharper disable ConditionIsAlwaysTrueOrFalse file = method.ReflectedType != null ? method.ReflectedType.FullName : "(unknown)"; // ReSharper restore ConditionIsAlwaysTrueOrFalse } AirbrakeTraceLine line = new AirbrakeTraceLine(file, lineNumber) { Method = method.Name }; lines.Add(line); } return(lines.ToArray()); }
protected static RaygunErrorStackTraceLineMessage[] BuildStackTrace(Exception exception) { var stackTrace = new StackTrace(exception, true); return(BuildStackTrace(stackTrace)); }
public void LifeCycle() { int counter = 0; while (true) { if (DBOpt.RowCountForField((Object)this) != 0) { CheckTheChangeInDefinitionTable(); if (isActive == true) { if (CheckHourFormat() && CheckDayFormat()) { if (CheckTimeSpanwithCurrentTimeSpan() && CompareDatesAndDecideWhatNextActionWillBe()) { uniqueString = seq.GetUniqueString(); GenerateWebRequest(); GetResponse(); } else { uniqueString = seq.GetUniqueString(); threadId = Thread.CurrentThread.ManagedThreadId; try { /* Possible Exception that name cause */ /* Invalid Operation Example */ threadName = Thread.CurrentThread.Name; } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); /* https://msdn.microsoft.com/en-us/library/system.exception.getbaseexception(v=vs.110).aspx */ exMsgList.Add(ex.GetBaseException().ToString()); /* https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframe(v=vs.110).aspx */ stTraceFramee.Add(st.GetFrame(0).ToString()); } urlAddress = urlAddress; statusCode = -99; requestTime = DateTime.Now; responseTime = DateTime.Now; theDifference = TimeSpan.Zero; responseExist = -99; } } else if (!CheckHourFormat() || !CheckDayFormat()) { uniqueString = seq.GetUniqueString(); threadId = Thread.CurrentThread.ManagedThreadId; try { /* Possible Exception that name cause */ /* Invalid Operation Example */ threadName = Thread.CurrentThread.Name; } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); /* https://msdn.microsoft.com/en-us/library/system.exception.getbaseexception(v=vs.110).aspx */ exMsgList.Add(ex.GetBaseException().ToString()); /* https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.getframe(v=vs.110).aspx */ stTraceFramee.Add(st.GetFrame(0).ToString()); } urlAddress = urlAddress; statusCode = -0; requestTime = DateTime.Now; responseTime = DateTime.Now; theDifference = TimeSpan.Zero; responseExist = -1; exMsgList.Add("Check the format"); stTraceFramee.Add("Format must be correct."); } } else { uniqueString = seq.GetUniqueString(); threadId = Thread.CurrentThread.ManagedThreadId; try { threadName = Thread.CurrentThread.Name; } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); exMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } urlAddress = urlAddress; statusCode = -99; requestTime = DateTime.Now; responseTime = DateTime.Now; theDifference = TimeSpan.Zero; responseExist = -99; } } else { if (counter < 10) { uniqueString = seq.GetUniqueString(); threadId = Thread.CurrentThread.ManagedThreadId; try { threadName = Thread.CurrentThread.Name; } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); exMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } urlAddress = urlAddress; statusCode = -0; requestTime = DateTime.Now; responseTime = DateTime.Now; theDifference = TimeSpan.Zero; responseExist = -1; counter++; } else { Console.WriteLine("Life Cycle is terminated"); break; } } InsertIntoDBorIntoFıle(); determineTheExceotion = DBOpt.Warning((Object)this); exMsgList = new ConcurrentBag <string>(); stTraceFramee = new ConcurrentBag <string>(); sqlExMsgList = new ConcurrentBag <string>(); sqlStTraceFrame = new ConcurrentBag <string>(); checkDayFormat = false; checkHourFormat = false; timeSpanChecker = false; listofTime = new List <List <TimeSpan> >(); listOfDays = new List <int>(); try { Thread.Sleep(this.sleepTime); } catch (Exception e) { Exception ex = new Exception(); StackTrace st = new StackTrace(); exMsgList.Add(ex.GetBaseException().ToString()); stTraceFramee.Add(st.GetFrame(0).ToString()); } } }
internal static object[] AddTo(this StackTrace self, object[] args) { return(Add(args, self)); }
/// <summary> /// Create .lnk to ClickOnce shortcut with autostart parameters /// </summary> public static void CreateAutoStartLink() { Logging.AddLog("CreateAutoStartLink enter", LogLevel.Debug); try { ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; if (ad.IsFirstRun) { Logging.AddLog("Creating autostart link file", LogLevel.Debug); Assembly assembly = Assembly.GetEntryAssembly(); string company = string.Empty; string description = string.Empty; string productname = string.Empty; string StartMenuShortcutName = string.Empty; // Get company name if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute))) { AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute)); company = ascompany.Company; } // Get shortcut description if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute))) { AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute)); description = asdescription.Description; } // Get shortcut product name if (Attribute.IsDefined(assembly, typeof(AssemblyProductAttribute))) { AssemblyProductAttribute asproduct = (AssemblyProductAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute)); productname = asproduct.Product; } Logging.AddLog(company + " | " + description + " | " + productname, LogLevel.Debug); // Concat clickonce shortcut full path if (!string.IsNullOrEmpty(company)) { StartMenuShortcutName = string.Concat( Environment.GetFolderPath(Environment.SpecialFolder.Programs), "\\", company, "\\", productname, ".appref-ms"); } //if everything is ok - create shortcut if (!string.IsNullOrEmpty(StartMenuShortcutName)) { string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); Utils.CreateLink(_PROGRAM_AUTOSTART_SHORTCUT_NAME, desktopPath, StartMenuShortcutName, "-start"); } else { Logging.AddLog("Couldn't locate ClickOnce shortcut in start menu", LogLevel.Debug); } } } catch (Exception ex) { StackTrace st = new StackTrace(ex, true); StackFrame[] frames = st.GetFrames(); string messstr = ""; // Iterate over the frames extracting the information you need foreach (StackFrame frame in frames) { messstr += String.Format("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); } string FullMessage = "Error in creating Autostart link. "; FullMessage += "IOException source: " + ex.Data + " | " + ex.Message + " | " + messstr; Logging.AddLog(FullMessage, LogLevel.Important); } Logging.AddLog("CreateAutoStartLink exit", LogLevel.Trace); }
protected bool Equals(InnerError other) { return(String.Equals(Message, other.Message) && String.Equals(Type, other.Type) && String.Equals(Code, other.Code) && Equals(Data, other.Data) && Equals(Inner, other.Inner) && StackTrace.CollectionEquals(other.StackTrace) && Equals(TargetMethod, other.TargetMethod)); }
public ConstructionEvent() { stack = new StackTrace(true); }
/// <summary> /// Default constructor. /// </summary> /// <param name="x"></param> /// <param name="stackTrace"></param> public Error_EventArgs(Exception x, StackTrace stackTrace) { m_pException = x; m_pStackTrace = stackTrace; }
public void TestDMD() { Counter = 0; // Run the original method. Assert.Equal(Tuple.Create(StringOriginal, 1), ExampleMethod(1)); MethodInfo original = typeof(DynamicMethodDefinitionTest).GetMethod(nameof(ExampleMethod)); MethodBase patched; using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(original)) { Assert.Equal("i", dmd.Definition.Parameters[0].Name); // Modify the MethodDefinition. foreach (Instruction instr in dmd.Definition.Body.Instructions) { if (instr.Operand as string == StringOriginal) { instr.Operand = StringPatched; } else if (instr.MatchCallOrCallvirt <DynamicMethodDefinitionTest>(nameof(ExampleMethod))) { instr.Operand = dmd.Definition; } } // Generate a DynamicMethod from the modified MethodDefinition. patched = dmd.Generate(); } // Generate an entirely new method that just returns a stack trace for further testing. DynamicMethod stacker; using (DynamicMethodDefinition dmd = new DynamicMethodDefinition("Stacker", typeof(StackTrace), new Type[0])) { using (ILContext il = new ILContext(dmd.Definition)) il.Invoke(_ => { ILCursor c = new ILCursor(il); for (int i = 0; i < 32; i++) { c.Emit(OpCodes.Nop); } c.Emit(OpCodes.Newobj, typeof(StackTrace).GetConstructor(new Type[0])); for (int i = 0; i < 32; i++) { c.Emit(OpCodes.Nop); } c.Emit(OpCodes.Ret); }); stacker = (DynamicMethod)DMDEmitDynamicMethodGenerator.Generate(dmd, null); } using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(typeof(ExampleGenericClass <int>).GetMethod(nameof(ExampleMethod)))) { Assert.Equal(0, ((Func <int>)dmd.Generate().CreateDelegate(typeof(Func <int>)))()); Assert.Equal(0, ((Func <int>)DMDCecilGenerator.Generate(dmd).CreateDelegate(typeof(Func <int>)))()); Assert.Equal(dmd.Name = "SomeManualDMDName", dmd.Generate().Name); Counter -= 2; // This was indirectly provided by Pathoschild (SMAPI). // Microsoft.GeneratedCode can be loaded multiple times and have different contents. // This tries to recreate that scenario... and this is the best place to test it at the time of writing. #if NETFRAMEWORK && true AssemblyBuilder abDupeA = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName() { Name = "MonoMod.UnitTest.AssemblyDupe" }, AssemblyBuilderAccess.RunAndSave ); ModuleBuilder mbDupeA = abDupeA.DefineDynamicModule($"{abDupeA.GetName().Name}.dll"); TypeBuilder tbDupeA = mbDupeA.DefineType( "DupeA", System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Sealed | System.Reflection.TypeAttributes.Class ); Type tDupeA = tbDupeA.CreateType(); AssemblyBuilder abDupeB = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName() { Name = abDupeA.GetName().Name }, AssemblyBuilderAccess.RunAndSave ); ModuleBuilder mbDupeB = abDupeB.DefineDynamicModule($"{abDupeB.GetName().Name}.dll"); TypeBuilder tbDupeB = mbDupeB.DefineType( "DupeB", System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Sealed | System.Reflection.TypeAttributes.Class ); Type tDupeB = tbDupeB.CreateType(); Assert.Equal(tDupeA.Assembly.FullName, tDupeB.Assembly.FullName); Assert.NotEqual(tDupeA.Assembly, tDupeB.Assembly); TypeReference trDupeA = dmd.Module.ImportReference(tDupeA); TypeReference trDupeB = dmd.Module.ImportReference(tDupeB); Assert.Equal(trDupeA.Scope.Name, trDupeB.Scope.Name); // "Fun" fact: both share matching AssemblyNames, so the first scope gets reused! // Assert.NotEqual(trDupeA.Scope, trDupeB.Scope); Assert.Equal(tDupeA, trDupeA.ResolveReflection()); Assert.Equal(tDupeB, trDupeB.ResolveReflection()); #endif } // Run the DynamicMethod. Assert.Equal(Tuple.Create(StringPatched, 3), patched.Invoke(null, new object[] { 2 })); Assert.Equal(Tuple.Create(StringPatched, 3), patched.Invoke(null, new object[] { 1337 })); // Detour the original method to the patched DynamicMethod, then run the patched method. using (new Detour(original, patched)) { // The detour is only active in this block. Assert.Equal(Tuple.Create(StringPatched, 6), ExampleMethod(3)); } // Run the original method again. Assert.Equal(Tuple.Create(StringOriginal, 10), ExampleMethod(4)); // Verify that we can still obtain the real DynamicMethod. // .NET uses a wrapping RTDynamicMethod to avoid leaking the mutable DynamicMethod. // Mono uses RuntimeMethodInfo without any link to the original DynamicMethod. if (Type.GetType("Mono.Runtime") != null) { stacker.Pin(); } StackTrace stack = ((Func <StackTrace>)stacker.CreateDelegate(typeof(Func <StackTrace>)))(); MethodBase stacked = stack.GetFrames().First(f => f.GetMethod()?.IsDynamicMethod() ?? false).GetMethod(); Assert.NotEqual(stacker, stacked); Assert.Equal(stacker, stacked.GetIdentifiable()); Assert.Equal(stacker.GetNativeStart(), stacked.GetNativeStart()); // This will always be true on .NET and only be true on Mono if the method is still pinned. Assert.IsAssignableFrom <DynamicMethod>(stacked.GetIdentifiable()); if (Type.GetType("Mono.Runtime") != null) { stacker.Unpin(); } }
/// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { this.StackTrace = stackTrace; this.UserStackFrameNumber = userStackFrame; }
internal void SetStackTrace(StackTrace stackTrace, int userStackFrame) { _stackTrace = stackTrace; _userStackFrame = userStackFrame; }
/// <summary> /// Формирование XML с описанием и цепочкой исключений, вызванных ошибкой /// </summary> /// <param name="ex">исключение, по которому надо получить отладочную информацию</param> /// <returns>XML с данными об ошибке</returns> private XmlElement GetErrorXml(Exception ex) { XmlDocument Document = new XmlDocument(); XmlElement root = Document.CreateElement("Error"); Document.AppendChild(root); XmlElement node; string type = "", message = "", priority = Enum.GetName(typeof(Priority), Priority.Info), build = "", version = "", method = "", SQLWarning = ""; int hResult = 0; bool sendMail = false; #region Формирование информации об исключениях в цепочке исключений // Подготовка цепочки исключений в след. порядке: сперва самые "глубокие" исключения, далее - оборачивающие их ArrayList exList = new ArrayList(); while (ex != null) { exList.Insert(0, ex); ex = ex.InnerException; if (ex != null && string.IsNullOrEmpty(ex.StackTrace)) { break; } } XmlElement exceptions = Document.CreateElement("Exceptions"); for (int exOrder = 0; exOrder < exList.Count; exOrder++) { ex = (Exception)exList[exOrder]; // Сообщение и тип оригинального исключения if (exOrder == 0) { type = ex.GetType().FullName; message = ex.Message; hResult = Marshal.GetHRForException(ex); if (exList.Count == 1) { if (!(ex is LogicalException || ex is DetailedException)) { priority = Enum.GetName(typeof(Priority), Priority.Error); } if (ex is SqlException) { sendMail = !((SqlException)ex).Class.Equals(12); SQLWarning = WarningSQL; hResult = ((SqlException)ex).Number; } else if (ex is DetailedException) { sendMail = (ex as DetailedException).SendMail; if ((int)(ex as DetailedException).PriorityLevel < 1) { priority = Enum.GetName(typeof(Priority), Priority.Error); } } else if (ex is LogicalException) { sendMail = true; if ((int)(ex as LogicalException).PriorityLevel < 1) { priority = Enum.GetName(typeof(Priority), Priority.Error); } } else { sendMail = true; } } else { if (ex is SqlException) { sendMail = !((SqlException)ex).Class.Equals(12); hResult = ((SqlException)ex).Number; } else if (ex is DetailedException) { sendMail = (ex as DetailedException).SendMail; } else if (ex is LogicalException) { sendMail = true; } } } else { // Если пришедшее исключение не было обернуто Detailed или LogicalException if (!(ex is LogicalException || ex is DetailedException)) { priority = Enum.GetName(typeof(Priority), Priority.Error); if (ex is SqlException) { sendMail |= !((SqlException)ex).Class.Equals(12); } else { sendMail = true; } } } #region Получение информации о месте возникновения исключительной ситуации if (ex is LogicalException) { LogicalException lex = ex as LogicalException; build = lex.Build; version = lex.Version; method = lex.Method; } else { StackTrace stack = new StackTrace(ex, true); for (int j = 0; j < stack.FrameCount; j++) { StackFrame frame = stack.GetFrame(j); MethodBase m = frame.GetMethod(); if (method != null) { Type declaringType = m.DeclaringType; if (declaringType != null) { string componentName = declaringType.Assembly.GetName(false).Name; if (kescoBuilds.IndexOf(componentName) == -1) { //Повторная загрузка сборок авторства холдинга kescoBuilds.Clear(); Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); kescoBuilds.AddRange(asms.Where(a => a.GetCustomAttributes(typeof(AssemblyIsKescoAttribute), false).Length > 0 && (a.GetCustomAttributes(typeof(AssemblyIsKescoAttribute), false)[0] as AssemblyIsKescoAttribute).IsKesco).Select(a => a.GetName().Name).ToArray()); } if (kescoBuilds.IndexOf(componentName) != -1) { build = declaringType.Assembly.GetName(false).Name; version = declaringType.Assembly.GetName().Version.ToString(); method = m.Name; break; } } } } } #endregion XmlElement exception = Document.CreateElement("Ex"); // Сообщение node = Document.CreateElement("Node"); node.SetAttribute("id", "Message"); node.SetAttribute("name", "Сообщение"); node.SetAttribute("value", XmlTextEncoder.Encode(ex.Message)); exception.AppendChild(node); // Тип исключения node = Document.CreateElement("Node"); node.SetAttribute("id", "Type"); node.SetAttribute("name", "Тип исключения"); node.SetAttribute("value", XmlTextEncoder.Encode(ex.GetType().FullName)); exception.AppendChild(node); if (ex is SoapHeaderException || ex is SoapException || ex is DetailedException || ex is LogicalException) { #region Приоритет ошибки Priority pr; if (ex is DetailedException) { pr = (ex as DetailedException).PriorityLevel; // Отправка письма осуществляется если хотя бы для одного письма в цепочке это предусмотрено sendMail |= (ex as DetailedException).SendMail; } else if (ex is LogicalException) { pr = (ex as LogicalException).PriorityLevel; } else { pr = Priority.Error; } node = Document.CreateElement("Node"); node.SetAttribute("id", "Priority"); node.SetAttribute("name", "Приоритет"); node.SetAttribute("value", Enum.GetName(typeof(Priority), pr)); exception.AppendChild(node); // Приоритет всей цепочки сообщений определяется наивысшим уровнем (Alarm > ExternalError > Error > Info) if (priority != Enum.GetName(typeof(Priority), Priority.Alarm)) { if (pr == Priority.Alarm) { priority = Enum.GetName(typeof(Priority), Priority.Alarm); } else if (pr == Priority.ExternalError && priority != Enum.GetName(typeof(Priority), Priority.ExternalError)) { priority = Enum.GetName(typeof(Priority), Priority.ExternalError); } else if (pr == Priority.Error && priority != Enum.GetName(typeof(Priority), Priority.Error)) { priority = Enum.GetName(typeof(Priority), Priority.Error); } } #endregion #region Дополнительная отладочная информация string details; if (ex is SoapHeaderException) { details = "XML Web service URL : " + (ex as SoapHeaderException).Actor; } else if (ex is SoapException) { details = "XML Web service URL : " + (ex as SoapException).Actor; } else if (ex is Win32Exception) { details = "ErrorCode (HRESULT) : " + (ex as Win32Exception).ErrorCode + "\nNativeErrorCode : " + (ex as Win32Exception).NativeErrorCode; } else if (ex is DetailedException) { details = (ex as DetailedException).Details; } else { details = (ex as LogicalException).Details; } if (details != "") { node = Document.CreateElement("Node"); node.SetAttribute("id", "Details"); node.SetAttribute("code", "1"); node.SetAttribute("name", "Details"); node.SetAttribute("value", XmlTextEncoder.Encode(ClearPassword(details))); exception.AppendChild(node); } #endregion } if (ex.TargetSite != null) { // Полная версия сборки node = Document.CreateElement("Node"); node.SetAttribute("id", "Component"); node.SetAttribute("name", "Версия сборки"); node.SetAttribute("value", XmlTextEncoder.Encode(ex.TargetSite.DeclaringType.Assembly.FullName)); exception.AppendChild(node); // Метод node = Document.CreateElement("Node"); node.SetAttribute("id", "Method"); node.SetAttribute("name", "Метод"); node.SetAttribute("value", XmlTextEncoder.Encode(ex.TargetSite.DeclaringType.FullName + "." + ex.TargetSite.Name + "(...)")); exception.AppendChild(node); } // Stack Trace if (ex.StackTrace != null) { node = Document.CreateElement("Node"); node.SetAttribute("id", "Trace"); node.SetAttribute("code", "1"); node.SetAttribute("name", "Stack Trace"); node.SetAttribute("value", XmlTextEncoder.Encode(ex.StackTrace.TrimEnd(new char[] { '\n', '\r' }))); exception.AppendChild(node); } #region Команда и строка подключения для SqlException if (ex.InnerException != null && ex.InnerException is SqlException) { if (ex is DetailedException && (ex as DetailedException).SqlCmd != null) { IDbCommand cmd = (ex as DetailedException).SqlCmd; node = Document.CreateElement("Node"); node.SetAttribute("id", "Connection"); node.SetAttribute("name", "Sql Connection"); node.SetAttribute("value", cmd.Connection != null ? XmlTextEncoder.Encode(ClearPassword(cmd.Connection.ConnectionString)) : ""); exception.AppendChild(node); node = Document.CreateElement("Node"); node.SetAttribute("id", "Command"); node.SetAttribute("code", "1"); node.SetAttribute("name", "Sql Command"); node.SetAttribute("value", cmd != null ? XmlTextEncoder.Encode(cmd.CommandText) : ""); exception.AppendChild(node); node = Document.CreateElement("Node"); node.SetAttribute("id", "CommandTimeout"); node.SetAttribute("name", "Sql Timeout"); node.SetAttribute("value", cmd != null ? XmlTextEncoder.Encode(cmd.CommandTimeout.ToString() + " сек.") : ""); exception.AppendChild(node); if (cmd.Parameters != null && cmd.Parameters.Count > 0) { string sParams = ""; foreach (SqlParameter p in cmd.Parameters) { sParams += String.Format("{0}='{1}';\n", p.ParameterName, p.Value); } node = Document.CreateElement("Node"); node.SetAttribute("id", "Parameters"); node.SetAttribute("code", "1"); node.SetAttribute("name", "Sql Parameters"); node.SetAttribute("value", XmlTextEncoder.Encode(sParams.TrimEnd(new char[] { '\n', '\r' }))); exception.AppendChild(node); } } else { SQLWarning = WarningSQL; } } #endregion // Помечаем первое DetailedException, оборачивающее оригинальное исключение if (ex is LogicalException || ex is DetailedException && (ex.InnerException == null || ex.InnerException != null && !(ex.InnerException is DetailedException))) { exception.SetAttribute("first", "1"); } exceptions.AppendChild(exception); } root.AppendChild(exceptions); #endregion #region Сбор информации о контексте выполнения программы XmlElement info = Document.CreateElement("Info"); // Название приложения node = Document.CreateElement("Node"); node.SetAttribute("id", "AppName"); node.SetAttribute("name", "Приложение"); node.SetAttribute("value", XmlTextEncoder.Encode(_appName)); info.AppendChild(node); #region Задание свойств текущей ошибке на основании разорбанной цепочки исключений info.SetAttribute("type", XmlTextEncoder.Encode(type)); info.SetAttribute("message", XmlTextEncoder.Encode(message)); info.SetAttribute("mail", sendMail ? "1" : "0"); if (build == "" || version == "" || method == "") { info.SetAttribute("Build", XmlTextEncoder.Encode(WarningBuild)); } if (SQLWarning != "") { info.SetAttribute("SQL", XmlTextEncoder.Encode(SQLWarning)); } // Приоритет node = Document.CreateElement("Node"); node.SetAttribute("id", "Priority"); node.SetAttribute("name", "Приоритет"); node.SetAttribute("value", XmlTextEncoder.Encode(priority)); info.AppendChild(node); // Сборка if (build != "") { node = Document.CreateElement("Node"); node.SetAttribute("id", "Component"); node.SetAttribute("name", "Сборка"); node.SetAttribute("value", XmlTextEncoder.Encode(build)); info.AppendChild(node); } // Версия сборки if (version != "") { node = Document.CreateElement("Node"); node.SetAttribute("id", "ComponentVersion"); node.SetAttribute("name", "Версия сборки"); node.SetAttribute("value", XmlTextEncoder.Encode(version)); info.AppendChild(node); } // Функция if (method != "") { node = Document.CreateElement("Node"); node.SetAttribute("id", "Function"); node.SetAttribute("name", "Функция"); node.SetAttribute("value", XmlTextEncoder.Encode(method)); info.AppendChild(node); } // HRESULT if (hResult != 0) { node = Document.CreateElement("Node"); node.SetAttribute("id", "hresult"); node.SetAttribute("name", "HRESULT"); node.SetAttribute("value", hResult.ToString()); info.AppendChild(node); } #endregion // Рабочая папка приложения node = Document.CreateElement("Node"); node.SetAttribute("id", "BaseDirectory"); node.SetAttribute("name", "Base directory"); node.SetAttribute("value", XmlTextEncoder.Encode(AppDomain.CurrentDomain.BaseDirectory)); info.AppendChild(node); // Компьютер node = Document.CreateElement("Node"); node.SetAttribute("id", "Computer"); node.SetAttribute("name", "Компьютер"); node.SetAttribute("value", XmlTextEncoder.Encode(Dns.GetHostName())); info.AppendChild(node); // Пользователь node = Document.CreateElement("Node"); node.SetAttribute("id", "UserLogin"); node.SetAttribute("name", "Пользователь"); node.SetAttribute("value", XmlTextEncoder.Encode( Thread.CurrentPrincipal.Identity.Name != WindowsIdentity.GetCurrent().Name ? Thread.CurrentPrincipal.Identity.Name + "(" + WindowsIdentity.GetCurrent().Name + ")" : Thread.CurrentPrincipal.Identity.Name)); info.AppendChild(node); // Время ошибки node = Document.CreateElement("Node"); node.SetAttribute("id", "TimeError"); node.SetAttribute("name", "Время ошибки"); node.SetAttribute("value", DateTime.UtcNow.ToString("dd.MM.yyyy HH:mm:ss")); info.AppendChild(node); // Версия Framework node = Document.CreateElement("Node"); node.SetAttribute("id", "Framework"); node.SetAttribute("name", "Framework"); node.SetAttribute("value", XmlTextEncoder.Encode(Environment.Version.ToString())); info.AppendChild(node); // Для веб приложений собираем заголовки запроса и путь, по которому открыли страницу if (System.Web.HttpContext.Current != null) { System.Web.HttpRequest req = System.Web.HttpContext.Current.Request; if (req != null) { if (!string.IsNullOrEmpty(req.UserHostAddress)) { try { IPHostEntry entry = Dns.GetHostEntry(req.UserHostAddress); string domname = (entry != null ? entry.HostName : ""); domname = domname.Substring(domname.IndexOf(".") + 1); if (!domname.Equals(_domain_name, StringComparison.InvariantCultureIgnoreCase)) { _domain_name = ""; } } catch { } } node = Document.CreateElement("Node"); node.SetAttribute("id", "UserHostAddress"); node.SetAttribute("name", "UserHostAddress"); node.SetAttribute("value", XmlTextEncoder.Encode(req.UserHostAddress)); info.AppendChild(node); node = Document.CreateElement("Node"); node.SetAttribute("id", "URI"); node.SetAttribute("name", "URI"); node.SetAttribute("value", XmlTextEncoder.Encode(req.Url.AbsoluteUri)); info.AppendChild(node); node = Document.CreateElement("Node"); node.SetAttribute("id", "RequestType"); node.SetAttribute("name", "RequestType"); node.SetAttribute("value", req.RequestType); info.AppendChild(node); string headers = ""; foreach (string key in req.Headers.AllKeys) { headers += String.Format("{0}->[{1}]\n", key, (key == "Authorization" && req.Headers[key].Length > 100 ? req.Headers[key].Substring(0, 100) : req.Headers[key])); } node = Document.CreateElement("Node"); node.SetAttribute("id", "RequestHeaders"); node.SetAttribute("code", "1"); node.SetAttribute("name", "Request headers"); node.SetAttribute("value", XmlTextEncoder.Encode(headers.Trim())); info.AppendChild(node); } } // Используется памяти node = Document.CreateElement("Node"); node.SetAttribute("id", "MemoryUsed"); node.SetAttribute("name", "Занято памяти"); node.SetAttribute("value", GC.GetTotalMemory(true).ToString("### ### ### ### ###")); info.AppendChild(node); root.AppendChild(info); #endregion return(Document.DocumentElement); }
//-- //-- enhanced stack trace generator (exception) //-- private static string EnhancedStackTrace(Exception objException) { StackTrace objStackTrace = new StackTrace(objException, true); return(EnhancedStackTrace(objStackTrace)); }
private void _DigestBackground() { try { while (true) { if (LastTaskRecv == 0) { LastTaskRecv = Epoch.Now; } var notified = BackgroundNotify.WaitOne(BACKGROUND_NOTIFY_TIMEOUT); List <Callback> tasks = new List <Callback>(); lock (BackgroundTasks) { tasks.AddRange(BackgroundTasks); BackgroundTasks.Clear(); } if (tasks.Count > 1000) { LOG.Error("Surprising number of background tasks for lot with dbid = " + Context.DbId + ": " + tasks.Count); } if (tasks.Count > 0) { LastTaskRecv = Epoch.Now; //BgTimeoutExpiredCount = 0; } else if (Epoch.Now - LastTaskRecv > BACKGROUND_TIMEOUT_SECONDS) //++BgTimeoutExpiredCount > BACKGROUND_TIMEOUT_ABANDON_COUNT) { BgTimeoutExpiredCount = int.MinValue; //Background tasks stop when we shut down if (!ShuttingDown) { LOG.Error("Main thread for lot with dbid = " + Context.DbId + " entered an infinite loop and had to be terminated!"); bool IsRunningOnMono = (Type.GetType("Mono.Runtime") != null); //suspend and resume are deprecated, but we need to use them to analyse the stack of stuck main threads //sorry microsoft if (!IsRunningOnMono) { MainThread.Suspend(); var trace = new StackTrace(MainThread, false); MainThread.Resume(); LOG.Error("Trace (immediately when aborting): " + trace.ToString()); } else { LOG.Error("on mono, so can't obtain immediate trace."); } MainThread.Priority = ThreadPriority.BelowNormal; Container.AbortVM(); //MainThread.Abort(); //this will jolt the thread out of its infinite loop... into immediate lot shutdown Shutdown(); //it also doesnt tend to work too nicely on release builds. immediately free the lot. return; } } foreach (var task in tasks) { try { task?.Invoke(); if (task == null) { LastActivity = Epoch.Now; } } catch (ThreadAbortException ex) { if (BgKilled) { LOG.Error("Background thread locked for lot with dbid = " + Context.DbId + "! TERMINATING! " + ex.ToString()); MainThread.Abort(); //this will jolt the thread out of its infinite loop... into immediate lot shutdown return; } } catch (Exception ex) { LOG.Info("Background task failed on lot with dbid = " + Context.DbId + "! (continuing)" + ex.ToString()); } if (Epoch.Now - LastTaskRecv > 10) { LOG.Info("WARNING: Unusually long background task for dbid = " + Context.DbId + "! " + (Epoch.Now - LastTaskRecv) + "seconds"); } LastTaskRecv = Epoch.Now; } } } catch (ThreadAbortException ex2) { if (BgKilled) { LOG.Error("Background thread locked for lot with dbid = " + Context.DbId + "! TERMINATING! " + ex2.ToString()); MainThread.Abort(); //this will jolt the thread out of its infinite loop... into immediate lot shutdown return; } //complete remaining tasks LastActivity = Epoch.Now; List <Callback> tasks = new List <Callback>(); lock (BackgroundTasks) { tasks.AddRange(BackgroundTasks); BackgroundTasks.Clear(); } foreach (var task in tasks) { try { task.Invoke(); } catch (Exception ex) { LOG.Info("Background task failed on lot " + Context.DbId + "! (when ending)" + ex.ToString()); } } } }
public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return(Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)")); }
private static string GetStackTrace() { var stack = new StackTrace(); return(stack.ToString()); }
protected override void Write(LogEventInfo logEvent) { var record = new Dictionary <string, object> { { "level", logEvent.Level.Name }, { "message", Layout.Render(logEvent) }, { "logger_name", logEvent.LoggerName }, { "sequence_id", logEvent.SequenceID }, }; if (this.EmitStackTraceWhenAvailable && logEvent.HasStackTrace) { var transcodedFrames = new List <Dictionary <string, object> >(); StackTrace stackTrace = logEvent.StackTrace; foreach (StackFrame frame in stackTrace.GetFrames()) { var transcodedFrame = new Dictionary <string, object> { { "filename", frame.GetFileName() }, { "line", frame.GetFileLineNumber() }, { "column", frame.GetFileColumnNumber() }, { "method", frame.GetMethod().ToString() }, { "il_offset", frame.GetILOffset() }, { "native_offset", frame.GetNativeOffset() }, }; transcodedFrames.Add(transcodedFrame); } record.Add("stacktrace", transcodedFrames); } if (this.IncludeAllProperties && logEvent.Properties.Count > 0) { foreach (var property in logEvent.Properties) { var propertyKey = property.Key.ToString(); if (string.IsNullOrEmpty(propertyKey)) { continue; } record[propertyKey] = SerializePropertyValue(propertyKey, property.Value); } } try { EnsureConnected(); } catch (Exception ex) { NLog.Common.InternalLogger.Warn("Fluentd Connect - " + ex.ToString()); throw; // Notify NLog of failure } try { this.emitter?.Emit(logEvent.TimeStamp, this.Tag, record); } catch (Exception ex) { NLog.Common.InternalLogger.Warn("Fluentd Emit - " + ex.ToString()); throw; // Notify NLog of failure } }
protected virtual void OnEnable() { _stackTrace = new StackTrace(Target); _stackTrace.OnRepaint.AddListener(Repaint); }
public static string GetMyMethodName() { var st = new StackTrace(new StackFrame(1)); return(st.GetFrame(0).GetMethod().Name); }
void FormatStack(StackTrace stackTrace, int index1, StringBuilder stringBuilder) { var frame = stackTrace.GetFrame(index1); var method = frame.GetMethod(); if (method != null) { var declaringType = method.DeclaringType; if (declaringType != null) { var str1 = declaringType.Namespace; if (!string.IsNullOrEmpty(str1)) { stringBuilder.Append(str1); stringBuilder.Append("."); } stringBuilder.Append(declaringType.Name); stringBuilder.Append(":"); stringBuilder.Append(method.Name); stringBuilder.Append("("); var index2 = 0; var parameters = method.GetParameters(); var flag = true; for (; index2 < parameters.Length; ++index2) { if (!flag) { stringBuilder.Append(", "); } else { flag = false; } stringBuilder.Append(parameters[index2].ParameterType.Name); } stringBuilder.Append(")"); var str2 = frame.GetFileName(); if (str2 != null && (!(declaringType.Name == "Debug") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "Logger") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "DebugLogHandler") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "Assert") || !(declaringType.Namespace == "UnityEngine.Assertions")) && (!(method.Name == "print") || !(declaringType.Name == "MonoBehaviour") || !(declaringType.Namespace == "UnityEngine"))) { stringBuilder.Append(" (at "); #if UNITY_EDITOR str2 = str2.Replace(@"\", "/"); if (!string.IsNullOrEmpty(projectFolder) && str2.StartsWith(projectFolder)) { str2 = str2.Substring(projectFolder.Length, str2.Length - projectFolder.Length); } #endif stringBuilder.Append(str2); stringBuilder.Append(":"); stringBuilder.Append(frame.GetFileLineNumber().ToString()); stringBuilder.Append(")"); } stringBuilder.Append("\n"); } } }