ToString() public method

public ToString ( ) : string
return string
Esempio n. 1
0
        public static void LogEvent(string details)
        {
            StackTrace st = new StackTrace();
            // Putting into the string with only current program stack trace
            string stack = st.ToString().Substring(0, st.ToString().IndexOf("   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)") - 2);
            stack = stack.Replace("at", "");
            stack = stack.Replace(" ", "");
            stack = stack.Replace("\r\n", "|");
            // Reversing
            string[] all = stack.Split('|');
            Array.Reverse(all);
            stack = "";
            bool first = true;
            foreach (var s in all)
            {
                if (first == false)
                {
                    stack += "->";
                }
                else
                {
                    first = false;
                }
                stack += s;
            }

            string message = "";
            string currentDate = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.GetCultureInfo("en-US"));
            string currentTime = DateTime.Now.ToString("HH:mm:ss");

            message = currentDate + " " + currentTime + " [" + stack + "] " + details;

            StreamWriter writer = null;

            try
            {
                writer = OpenFile(DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.GetCultureInfo("en-US")));
            }
            catch (Exception e)
            {
                writer = OpenFile(DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.GetCultureInfo("en-US")) + "ERROR");
                message = e.Message;
            }

            try
            {
                writer.WriteLine(message);
            }
            catch (Exception e)
            {
                writer.Close();

                writer = new StreamWriter("ERROR.log", true);
                writer.WriteLine(message);
            }

            CloseFile(writer);
        }
Esempio n. 2
0
 public static void ER(Exception e, params string[] extras)
 {
     StackTrace st = new StackTrace();
     StackFrame[] frames = st.GetFrames();
     string methodName = "UnknownMethod";
     for(int i=0;i< frames.Length;i++)
     {
         if (frames[i].GetMethod().Name == System.Reflection.MethodInfo.GetCurrentMethod().Name)
         {
             if (i + 1 < frames.Length)
             {
                 methodName = frames[i + 1].GetMethod().Name;
                 break;
             }
         }
     }
     Console.WriteLine(String.Format("{1}[{4}:{5}][ERROR({2})]{0}:{3}", methodName, tab, Thread.CurrentThread.ManagedThreadId, e.Message, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()));
     Console.WriteLine("==========StackTrace==========");
     if (e.StackTrace != null)
         Console.WriteLine(e.StackTrace.ToString());
     else
         Console.WriteLine(st.ToString());
     Console.WriteLine("=============END==============");
     foreach (string s in extras)
         Console.WriteLine(s);
 }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (this.Worker.CancellationPending == true)
            {
                Console.WriteLine("Canceled!");

                this.IsFinish = true;
            }

            else if (!(e.Error == null))
            {
                //this.Cancelled = true;

                Console.WriteLine("Error: " + e.Error.Message);

                var l_CurrentStack = new System.Diagnostics.StackTrace(true);

                System.IO.StreamWriter file = new System.IO.StreamWriter(AppSettings.getCommonApplicationDataPath() + "\\theairlinepause.log");
                file.WriteLine(l_CurrentStack.ToString());
                file.WriteLine("------------ERROR MESSAGE--------------");
                file.WriteLine(e.Error.Message);
                file.WriteLine(e.Error.StackTrace);
                file.Close();

                this.IsError = true;

                this.Worker.RunWorkerAsync();
            }

            this.IsFinish = true;
        }
Esempio n. 4
0
        public static string GetStackTrace()
        {
            var stackTrace = new StackTrace(true);
            return stackTrace.ToString();

            //return stackTraceGetter.Invoke();
        }
        public static string FormatErrorMessage(string pEventID, string pOtherInfo, Exception exceptionToLog)
        {
            string strErrorPagePath    = String.Empty;
            string exceptionMessage    = "An exception was not generated.";
            string exceptionStackTrace = String.Empty;

            if (exceptionToLog == null)
            {
                StackTrace trace = new System.Diagnostics.StackTrace();
                exceptionStackTrace = trace.ToString();
            }
            else
            {
                strErrorPagePath = exceptionToLog.Source;
                exceptionMessage = exceptionToLog.Message;
                if (String.IsNullOrEmpty(exceptionToLog.GetBaseException().StackTrace))
                {
                    exceptionStackTrace = exceptionToLog.StackTrace;
                }
                else
                {
                    exceptionStackTrace = exceptionToLog.GetBaseException().StackTrace;
                }
            }
            string strApplicationPath = "Scheduler";

            if (_context != null)
            {
                strErrorPagePath   = _context.Request.RawUrl;
                strApplicationPath = _context.Request.ApplicationPath;
            }

            return(String.Format("Server: {0}\nDate time : {1}\nClientID: {2}\n\nLoginName: {3}\n\nFunction Name: {9}\nError Code: {4}\n\nServer Error in '{5}' Application.\n\n{6}\n\nError from page: {7}\n\nStack Trace: {8}",
                                 Environment.MachineName, DateTime.Now, _strClientID, _strLoginID, pOtherInfo, strApplicationPath, exceptionMessage, strErrorPagePath, exceptionStackTrace, pEventID));
        }
Esempio n. 6
0
 internal static void FRIEND(string ns)
 {
     StackTrace trace = new StackTrace();
     string text1 = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
     string str = trace.GetFrame(2).GetMethod().DeclaringType.Namespace;
     Assert(str.Equals(str) || str.Equals(ns), Environment.GetResourceString("RtType.InvalidCaller"), trace.ToString());
 }
Esempio n. 7
0
 public MyBaseException()
 {
     System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
     Debug.WriteLine("############# Stacktrace #############");
     Debug.WriteLine(t.ToString());
     Debug.WriteLine("############# Stacktrace #############");
 }
        internal static void LogStackTrace()
        {
            if (_context != null && _context.Result.Status == TestStatus.Failed)
            {
                var testname = _context.Test.FullName.Split('.')[2].Split('<')[0];
                var methodname = _context.Test.Name;

                var _stackFilePath = string.Format("{0}{1}.cs__{2}()__{3}__StackTrace.txt",
                    _stacktraceDir,
                    testname,
                    methodname,
                    _browser);

                var stackTrace = new StackTrace(true);

                using (var outfile = new StreamWriter(_stackFilePath, false))
                {
                    outfile.WriteLine(_result.Message);
                    outfile.WriteLine("");
                    outfile.WriteLine(stackTrace.ToString());
                }
            }

            _stackTrace = null;
            _context = null;
            _browser = null;
            _result = null;
        }
Esempio n. 9
0
		public static void Show(Exception e, StackTrace innerStackTrace = null, string customMessage = null)
		{
			var writer = new StringWriter();

			if (customMessage != null)
				WriteCustomMessage(customMessage, writer);
			else
				SetCustomMessageBasedOnTheActualError(writer, e);

			writer.Write("Message: ");
			writer.WriteLine(e.Message);
			if (string.IsNullOrWhiteSpace(UrlUtil.Url) == false)
			{
				writer.Write("Uri: ");
				writer.WriteLine(UrlUtil.Url);
			}
			writer.Write("Server Uri: ");
			writer.WriteLine(GetServerUri(e));

			writer.WriteLine();
			writer.WriteLine("-- Error Information --");
			writer.WriteLine(e.ToString());
			writer.WriteLine();

			if (innerStackTrace != null)
			{
				writer.WriteLine("Inner StackTrace: ");
				writer.WriteLine(innerStackTrace.ToString());
			}
		
			Show(writer.ToString());
		}
Esempio n. 10
0
 private void _disconnect(bool requested)
 {
     if (disconnecting)
     {
         return;
     }
     System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
     System.Diagnostics.Trace.TraceInformation(t.ToString());
     System.Diagnostics.Trace.TraceInformation("disconnect");
     disconnecting = true;
     if (requested)
     {
         reconnect = false;
     }
     if (socket != null)
     {
         socket.Close();
     }
     onDisconnected?.Invoke(this, new DisconnectEventArgs {
         requested = requested
     });
     if (reconnect && !requested)
     {
         asyncConnect();
     }
 }
Esempio n. 11
0
File: Util.cs Progetto: wcchh/fSort
        static void UnhandledExeceptionHandler(object source, UnhandledExceptionEventArgs arg)
        {
            Console.WriteLine("UnhandledException event raised in {0}: {1}",
                              AppDomain.CurrentDomain.FriendlyName, arg.ExceptionObject.GetType());

            DateTime ts      = DateTime.Now;
            string   dumpmsg = _first_exception_msg;

            _first_exception_msg = string.Empty;

            if (arg.ExceptionObject.GetType() != _first_execption_type && string.Empty == dumpmsg)
            {
                System.Text.StringBuilder msg = new System.Text.StringBuilder();
                msg.AppendLine(String.Format("{0} App {1} {2} Crash", ts.ToString(), _app_name, _app_ver));
                msg.AppendLine();
                msg.AppendLine(arg.ExceptionObject.GetType().FullName);
                System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
                msg.AppendLine(st.ToString());
                msg.AppendLine();

                dumpmsg = msg.ToString();
            }

            //Trace.WriteLine(dumpmsg); Trace.Flush();
            Log.Error(dumpmsg);
        }
Esempio n. 12
0
        private static void ReportOwnerException(PropertyInfoEx propEx, IStateObject newValue, string old_Uid)
        {
            var stackTrace = new System.Diagnostics.StackTrace(4, true);

            var ownerInfo   = " Not owner info available";
            var ownerObject = StateManager.Current.GetParentEx(newValue);

            if (ownerObject != null)
            {
                var format =
                    " The owner of the object is an instance of class {0}, it is {1}. Look for property {2}. It could have been set during a Build call that is still of process or during an Initialize.Init which is the WebMap equivalent of a constructor. If it is used as parent reference reimplement the property as a non virtual, [StateManagement(None)] calculated property using ViewManager.GetParent(), you can also use [Reference] attribute or disable interception by removing virtual from the property";
                if (StateManager.AllBranchesAttached(ownerObject))
                {
                    ownerInfo = string.Format(format,
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()), " ATTACHED ",
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
                else
                {
                    ownerInfo = string.Format(format, "NOT ATTACHED",
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()),
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
            }
            throw new InvalidOperationException(
                      "LazyBehaviour::ProcessSetter object has already an Owner." + ownerInfo + "\r\n" +
                      "UniqueID: " + old_Uid + "\r\n" +
                      "Additional Info: \r\n" +
                      "ViewModel Type: " + newValue.GetType().FullName + "\r\n" +
                      "Property Type: " + propEx.prop.PropertyType.FullName + "\r\n" +
                      "Error Location: " + stackTrace.ToString());
        }
Esempio n. 13
0
     public override AssertFilters  AssertFailure(String condition, String message, 
                               StackTrace location, StackTrace.TraceFormat stackTraceFormat,
                               String windowTitle)
 
     {
         return (AssertFilters) Assert.ShowDefaultAssertDialog (condition, message, location.ToString(stackTraceFormat), windowTitle);
     }
Esempio n. 14
0
	public static void Log(object __message) {
		if (!Debug.isDebugBuild) return;

		// Builds parameters
		System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
		string method = t.ToString().Split('\n')[1];
		method = method.Substring(method.IndexOf("at ") + 3);
		
		string currentFrame = Time.frameCount.ToString("0000000");
		string currentTime = (Time.realtimeSinceStartup * 1000).ToString("00000");
			
		// Finally, composes line
		string fullMessage = "[" + currentFrame + "@" + currentTime + "] " +  method + " :: " + __message;
		//string fullMessage = "[" + currentFrame + ":" + currentTime + " | " +  method + ": " + __message;
		
		// Writes to Unity console log and to normal log
		Debug.Log(fullMessage + "\n");
		System.Console.WriteLine(fullMessage);
		
		//Debug.Log("Flat Mesh Initialized (d)\n"); // UnityEngine.Debug.Log
		//System.Console.WriteLine("Flat Mesh Initialized");
		// Debug.isDebugBuild
		// http://docs.unity3d.com/Documentation/ScriptReference/Application.RegisterLogCallback.html

		
		// Port LoggingFramework:
		// http://forum.unity3d.com/threads/38720-Debug.Log-and-needless-spam

	}
Esempio n. 15
0
    public static object GetStackTrace()
    {
      var sf = new StackTrace(2, true);
      List<string> newst = new List<string>();
      var sfs = sf.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

      for (int i = 0; i < sfs.Length; i++)
      {
        if (sfs[i].StartsWith(@"   at Microsoft.Scripting.Hosting.ScriptEngine.ExecuteCommand(String code, IScriptModule module)") ||
          sfs[i].StartsWith("   at Microsoft.Scripting.Hosting.ScriptEngine.ExecuteCommand(System.String code, IScriptModule module)"))
        {
          break;
        }
        newst.Add(sfs[i].
          Replace("   at #.", string.Empty).
          Replace("   at ", string.Empty).
          Replace("Microsoft.Scripting.CodeContext $context, ", string.Empty).
          Replace("Microsoft.Scripting.CodeContext $context", string.Empty).
          Replace("CodeContext $context, ", string.Empty).
          Replace("CodeContext $context", string.Empty).
          Replace("System.Object ", string.Empty).
          Replace("Object ", string.Empty));
      }

      return newst.ToArray();
    }
Esempio n. 16
0
		public static void Show(Exception e, StackTrace innerStackTrace)
		{
			var details = e +
			              Environment.NewLine + Environment.NewLine +
			              "Inner StackTrace: " + Environment.NewLine +
						  (innerStackTrace == null ? "null" : innerStackTrace.ToString());
			Show(e.Message, details);
		}
Esempio n. 17
0
 protected CompoundMemento()
 {
     if (CaptureStackTrace)
     {
         var stackTrace = new StackTrace(true);
         StackTrace = stackTrace.ToString();
     }
 }
Esempio n. 18
0
            private string GetTrace()
            {
#if TRACE_LEAKS
                return(Trace == null? "": Trace.ToString());
#else
                return("Leak tracing information is disabled. Define TRACE_LEAKS on ObjectPool`1.cs to get more info \n");
#endif
            }
Esempio n. 19
0
 public static void Error(String msg, Exception ex)
 {
     if (IsEnabled)
     {
         System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex);
         System.Diagnostics.Trace.TraceError(msg + "\r\n" + trace.ToString());
     }
 }
Esempio n. 20
0
        public static void WriteLine(Exception e)
        {
            string currenttime = DateTime.Now.ToString("[d/M/yyyy HH:mm:ss.fff]");
            string message = currenttime + "  " + e.ToString();
            StackTrace st = new StackTrace(1, true);
            message += st.ToString();

            Trace.TraceError(message);
        }
Esempio n. 21
0
        public static void test()
        {
            StackFrame fr = new StackFrame(1, true);
            StackTrace st = new StackTrace(fr);
            EventLog.WriteEntry(fr.GetMethod().Name,
                                st.ToString(),
                                EventLogEntryType.Warning);


        }
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs args)
        {
            StackTrace stackTrace = new StackTrace(args.Exception, true);
            string stackTraceString = args.Exception.StackTrace == null ? stackTrace.ToString() : args.Exception.StackTrace;

            string errText = string.Format("An unhandled exception occurred: {0}\r\nStack Trace: {1}", args.Message, stackTraceString);

            Debug.WriteLine(errText);
            args.Handled = true;
        }
Esempio n. 23
0
    public static void Assert( object source, bool condition, string message )
    {
      if( !condition )
      {
        Log.WriteLine( source, "# - " + message );

        StackTrace stackTrace = new StackTrace();
        Log.WriteLine( stackTrace.ToString() );
      }
    }
Esempio n. 24
0
 public static void Move(string srcpath, string destpath)
 {
     StackTrace trace = new StackTrace();
     DeleteHistory delete = new DeleteHistory();
     delete.path = srcpath;
     delete.path2 = destpath;
     delete.traceinfo = trace.ToString();
     historys.Add(delete);
     System.IO.Directory.Move(srcpath, destpath);
 }
Esempio n. 25
0
 public static void Delete(string path)
 {
     StackTrace trace = new StackTrace();
     DeleteHistory delete = new DeleteHistory();
     delete.path = path;
     delete.path2 = "";
     delete.traceinfo = trace.ToString();
     historys.Add(delete);
     System.IO.Directory.Delete(path);
 }
Esempio n. 26
0
 /// <summary>
 ///     Writes the trace.
 /// </summary>
 /// <param name = "enteringFunction">if set to <c>true</c> [entering function].</param>
 public static void WriteTrace(bool enteringFunction)
 {
     var callingFunctionName = "Undetermined method";
     var callingParentFunctionName = "";
     var action = enteringFunction ? "Entering" : "Exiting";
     var test = "";
     try
     {
         //Determine the name of the calling function.
         var stackTrace = new StackTrace();
         callingFunctionName = stackTrace.GetFrame(1).GetMethod().Name;
         callingParentFunctionName = " Parent: " + stackTrace.GetFrame(2).GetMethod();
         test = stackTrace.ToString().Substring(0, stackTrace.ToString().IndexOf("at System.Web"));
     }
     catch (Exception ex)
     {
         Trace.TraceWarning(ex.Message);
     }
     HttpContext.Current.Trace.Write(action, callingFunctionName + callingParentFunctionName + test);
 }
Esempio n. 27
0
        private static void ReportInvalidStateObject(PropertyInfoEx propEx, IStateObject newValue)
        {
            var stackTrace = new System.Diagnostics.StackTrace(3, true);

            throw new InvalidOperationException(
                      "LazyBehaviour::ProcessSetter old_Uid was null. This might happen if the ViewModel is instantiated with new instead of using Container.Resolve<T>.\r\n" +
                      "Additional Info: \r\n" +
                      "ViewModel Type: " + newValue.GetType().FullName + "\r\n" +
                      "Property Type: " + propEx.prop.PropertyType.FullName + "\r\n" +
                      "Error Location: " + stackTrace.ToString());
        }
			private void GetResourceStringCode(object userDataIn)
			{
				Environment.ResourceHelper.GetResourceStringUserData getResourceStringUserData = (Environment.ResourceHelper.GetResourceStringUserData)userDataIn;
				Environment.ResourceHelper resourceHelper = getResourceStringUserData.m_resourceHelper;
				string key = getResourceStringUserData.m_key;
				CultureInfo arg_1B_0 = getResourceStringUserData.m_culture;
				Monitor.Enter(resourceHelper, ref getResourceStringUserData.m_lockWasTaken);
				if (resourceHelper.currentlyLoading != null && resourceHelper.currentlyLoading.Count > 0 && resourceHelper.currentlyLoading.Contains(key))
				{
					try
					{
						StackTrace stackTrace = new StackTrace(true);
						stackTrace.ToString(System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup);
					}
					catch (StackOverflowException)
					{
					}
					catch (NullReferenceException)
					{
					}
					catch (OutOfMemoryException)
					{
					}
					getResourceStringUserData.m_retVal = "[Resource lookup failed - infinite recursion or critical failure detected.]";
					return;
				}
				if (resourceHelper.currentlyLoading == null)
				{
					resourceHelper.currentlyLoading = new Stack(4);
				}
				if (!resourceHelper.resourceManagerInited)
				{
					RuntimeHelpers.PrepareConstrainedRegions();
					try
					{
					}
					finally
					{
						RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle);
						RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle);
						RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle);
						RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle);
						resourceHelper.resourceManagerInited = true;
					}
				}
				resourceHelper.currentlyLoading.Push(key);
				if (resourceHelper.SystemResMgr == null)
				{
					resourceHelper.SystemResMgr = new ResourceManager(this.m_name, typeof(object).Assembly);
				}
				string @string = resourceHelper.SystemResMgr.GetString(key, null);
				resourceHelper.currentlyLoading.Pop();
				getResourceStringUserData.m_retVal = @string;
			}
        public SQLiteMonTransaction(SQLiteTransaction transaction)
        {
            this.wrappedTrans = transaction;

            StackTrace trace = new StackTrace(true);

            lock (readerInfoLock)
            {
                readerInfo.Add(this.wrappedTrans, trace.ToString());
            }
        }
        public SQLiteMonDataReader(SQLiteDataReader reader)
        {
            this.wrappedReader = reader;

            StackTrace trace = new StackTrace(true);

            lock (readerInfoLock)
            {
                readerInfo.Add(this.wrappedReader, trace.ToString());
            }
        }
Esempio n. 31
0
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            var message = e.Exception.GetFlattenInnerMessage();
            var stack   = new System.Diagnostics.StackTrace(e.Exception, true);

            Log.Fatal("* Application_ThreadException:{0}\r\n{1}", message, stack.ToString());

            //if (ExceptionHandler.DoApplicationThreadException(e.Exception) == DialogResult.Abort)
            //{
            //	Application.Exit();
            //}
        }
Esempio n. 32
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 (StackTrace st)
		{
			if (st.FrameCount > 0)
				Assert.IsNotNull (st.GetFrame (0), "GetFrame");
			else
				Assert.IsNull (st.GetFrame (0), "GetFrame");
			if (st.FrameCount > 0)
				Assert.IsNotNull (st.GetFrames (), "GetFrames");
			else
				Assert.IsNull (st.GetFrames (), "GetFrames");
			Assert.IsNotNull (st.ToString (), "ToString");
		}
        private void WriteStackTrace()
        {
            var stackTrace = new StackTrace(true);
            var stackTraceMessage = stackTrace.ToString();

            if (AlternativeWriter != null)
            {
                AlternativeWriter.WriteLine(stackTraceMessage);
                return;
            }

            Debug.WriteLine(stackTraceMessage);
        }
Esempio n. 34
0
 public void LogError(string message, StackTrace stackTrace)
 {
     Event workEvent = new Event("Error",
                                DateTime.Now,
                                System.Environment.MachineName,
                                Process.GetCurrentProcess().ProcessName,
                                message,
                                null,
                                stackTrace.GetFrame(0).GetMethod().ReflectedType.Name + "." + stackTrace.GetFrame(0).GetMethod().Name,
                                stackTrace.GetFrame(0).GetFileLineNumber(),
                                stackTrace.ToString());
     Log(workEvent);
 }
Esempio n. 35
0
		public static string GetStrackTrace(int skipFrames)
		{
			StackTrace stackTrace = new StackTrace(skipFrames + 1);
			string str = stackTrace.ToString();
			if (str.Length >= 0xfa0)
			{
				return str.Substring(0, 0xfa0);
			}
			else
			{
				return str;
			}
		}
Esempio n. 36
0
        public override void Fail(string message1, string message2)
        {
            StackTrace stack = new StackTrace();

            Environment.GetEnvironmentVariables();
            string sDisplay = message1 + "\n" + message2 + "\n" + "Launch Debugger?\n\n" + stack.ToString();

            DialogResult dr = MessageBox.Show(sDisplay, "Assertion failed.",MessageBoxButtons.YesNo,MessageBoxIcon.Error ,MessageBoxDefaultButton.Button1,MessageBoxOptions.DefaultDesktopOnly);
            if (dr == DialogResult.Yes)
            {
                Debugger.Break();
            }
        }
        public override void Write(string message)
        {
            StackTrace stackTrace = new StackTrace(true);
            Log log = new Log();
            log.LogGuid = Guid.NewGuid().ToString();
            log.LogDate = DateTime.UtcNow;
            log.LogCategory = string.Empty;
            log.LogDescription = message;
            log.StackTrace = stackTrace.ToString();
            log.DetailedErrorDescription = string.Empty;

            OnLogCreated(log);
        }
Esempio n. 38
0
        public static bool ContractProvides(bool isContractOkay, ProvideStringDelegate provideStringProviderDelegate)
        {
            if (!isContractOkay)
            {
                // TODO: (Future enhancement) Build a string representation of isContractOkay if stringProviderDelegate is null
                string message = provideStringProviderDelegate(null) ?? "NO MESSAGE PROVIDED";
                var trace   = new StackTrace(1);

                LogError("[CONTRACT VIOLATION] {0}\nLocation:\n{1}",  message, trace.ToString());
                throw new ContractException(message);
            }

            return isContractOkay;
        }
Esempio n. 39
0
        public static void WriteStackTraceLog(string extMsg)
        {
            try
            {
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(1, true);

                //记录异常日志文件
                string logStr = string.Format("{0}\r\n{1}", extMsg, stackTrace.ToString());
                LogManager.WriteException(logStr);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 40
0
        public void ProcessInfo(IncludeInfoStrategy strategy, AbstractInfo info)
        {
            if (!strategy.IncludeInfoStrategyForLocationInfo.Include) return;

            var locationInfo = new LocationInfo()
            {
                AppDomainName = AppDomain.CurrentDomain.FriendlyName,
                ManagedThreadId = Thread.CurrentThread.ManagedThreadId,
            };

            StackTrace strackTrace = new StackTrace();
            StackFrame[] stackFrames = strackTrace.GetFrames();
            int skip = 1;
            for (int i = 0; i < stackFrames.Length; i++)
            {
                if (stackFrames[i].GetMethod().ReflectedType != null &&
                    stackFrames[i].GetMethod().ReflectedType.Assembly.FullName.Contains("Adhesive.AppInfoCenter"))
                {
                    skip++;
                }
            }
            if (stackFrames.Length >= skip)
            {
                StackFrame stackFrame = stackFrames[skip];
                if (stackFrame != null)
                {
                    var methodBase = stackFrame.GetMethod();

                    if (methodBase != null)
                    {
                        locationInfo.AssemblyName = methodBase.Module.Assembly.ToString();
                        locationInfo.ModuleName = methodBase.Module.ToString();
                        locationInfo.TypeName = methodBase.ReflectedType.ToString();
                        locationInfo.MethodName = methodBase.ToString();
                    }
                }

                StackTrace skipped = new StackTrace(skip, true);
                if (skipped != null)
                {
                    if (strategy.IncludeInfoStrategyForLocationInfo.IncludeStackTrace)
                        locationInfo.StackTrace = skipped.ToString();
                    else
                        locationInfo.StackTrace = string.Empty;
                }
            }

            info.LocationInfo = locationInfo;
        }
Esempio n. 41
0
        public override void Fail(string message, string detailMessage)
        {
            var stackTrace = new System.Diagnostics.StackTrace(skipFrames: 4, fNeedFileInfo: true);

            if (string.IsNullOrWhiteSpace(message))
            {
                Log.WriteLine("Assert failed!", ConsoleColor.Red);
            }
            else
            {
                Log.WriteLine("Assert failed: ", ConsoleColor.Red);
                Log.WriteLine(message, ConsoleColor.Gray);
            }
            Log.WriteLine(stackTrace.ToString(), ConsoleColor.DarkRed);
        }
Esempio n. 42
0
File: Util.cs Progetto: wcchh/fSort
        static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs arg)
        {
            Console.WriteLine("FirstChanceException event raised in {0}: {1}",
                              AppDomain.CurrentDomain.FriendlyName, arg.Exception.Message);

            bool dump = true;

            if (null != _first_execption_type)
            {
                if (_first_execption_type == arg.Exception.GetType() &&
                    String.Compare(_exception_msg, arg.Exception.Message) == 0)
                {
                    return;
                }
            }

            System.Text.StringBuilder     msg = new System.Text.StringBuilder();
            System.Diagnostics.StackTrace st  = new System.Diagnostics.StackTrace();
            string stackmsg = st.ToString();

            if (arg.Exception.GetType() == typeof(System.IO.IOException))
            {
                if (-1 != stackmsg.IndexOf("LocalDataKit.IsFileLocked("))
                {
                    dump = false;
                    //Trace.WriteLine(arg.Exception.Message); Trace.Flush();
                    Log.Error(arg.Exception.Message);
                }
            }

            if (dump)
            {
                DateTime ts = DateTime.Now;
                msg.AppendLine(String.Format("{0} App {1} {2} Crash", ts.ToString(), _app_name, _app_ver));
                msg.AppendLine();
                msg.AppendLine(arg.Exception.GetType().FullName);
                msg.AppendLine(arg.Exception.Message);
                msg.AppendLine(stackmsg);
                msg.AppendLine();

                _first_execption_type = arg.Exception.GetType();
                _exception_msg        = arg.Exception.Message;
                _first_exception_msg  = msg.ToString();

                //Trace.WriteLine(msg);Trace.Flush();
                Log.Error(_first_exception_msg);
            }
        }
Esempio n. 43
0
        public static void WriteStackTraceLog(string extMsg)
        {
            try
            {
                System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(1);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(extMsg);
                stringBuilder.AppendFormat("\r\n{0}", stackTrace.ToString());

                //记录异常日志文件
                LogManager.WriteException(stringBuilder.ToString());
            }
            catch (Exception)
            {
            }
        }
Esempio n. 44
0
        /// <summary>
        /// 格式化堆栈信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void WriteFormatStackLog(System.Diagnostics.StackTrace stackTrace, string extMsg)
        {
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendFormat("应   用程序出现了对象锁定超时错误:\r\n");

                stringBuilder.AppendFormat("\r\n 额外信息: {0}", extMsg);
                stringBuilder.AppendFormat("\r\n {0}", stackTrace.ToString());

                //记录异常日志文件
                LogManager.WriteException(stringBuilder.ToString());
            }
            catch (Exception)
            {
            }
        }
Esempio n. 45
0
    public static void Log(object o)
    {
        if (Application.isEditor)
        {
            string __t = System.DateTime.Now.ToString() + "(+" + Time.realtimeSinceStartup + " s) " + o.ToString();
            UnityEngine.Debug.Log(__t);
        }
        else
        {
            /*
             * System.Diagnostics.Debug.WriteLine(String.Format("{0} ({1}) {2}\n\t{3}",System.DateTime.Now.ToString(), Time.realtimeSinceStartup, o.ToString(), __t));
             */

            StackTrace __trace = new System.Diagnostics.StackTrace();
            string     __t     = __trace.ToString();

//			__t = __t.Substring(__t.LastIndexOf(" at "));
//			System.Diagnostics.Debug.WriteLine(String.Format("* {0} ({1}) #{2} * {3}\n{4}",System.DateTime.Now.ToString(), Time.realtimeSinceStartup, __uid, o.ToString(), __t));
            UnityEngine.Debug.Log(String.Format("* {0} ({1}) * {2}\n{3}", System.DateTime.Now.ToString(), Time.realtimeSinceStartup, o.ToString(), __t));
        };
    }
Esempio n. 46
0
 private void asyncConnectTimeout(object state, bool timedOut)
 {
     if (socket == null || !socket.Connected)
     {
         System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
         System.Diagnostics.Trace.TraceInformation(t.ToString());
         Trace.TraceInformation("Async connect timeout");
         if (socket != null)
         {
             socket.Close();
         }
         if (reconnect)
         {
             asyncConnect();
         }
     }
     if (socket != null && socket.Connected)
     {
         receive();
     }
 }
Esempio n. 47
0
        private async void calculateAirmassButton_Click_1(object sender, EventArgs e)
        {
            //this.cancelButton.Enabled = true;
            //this.calculateAirmassButton.Enabled = false;

            var progressIndicator = new Progress <int>(ReportProgress);

            cts = new CancellationTokenSource();
            try
            {
                await EmulatePCM(progressIndicator, cts.Token);


                //EmulatePCMSync();
            }
            catch (OperationCanceledException)
            {
                this.progressBar.Value = 0;
            }
            catch (Exception ex)
            {
                var    currentStack = new System.Diagnostics.StackTrace(true);
                string stackTrace   = currentStack.ToString();

                FlexibleMessageBox.Show("Failed to process file due to: " + Environment.NewLine + stackTrace,
                                        "Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information,
                                        MessageBoxDefaultButton.Button2);
            }
            finally
            {
                this.cancelButton.Enabled           = false;
                this.calculateAirmassButton.Enabled = true;
            }

            this.progressBar.Value = 0;

            return;
        }
Esempio n. 48
0
        public static void log(string astrlog, LOG_LEVEL aenumLogLevel = LOG_LEVEL.INFO, Boolean abPrintStack = true)
        {
            try
            {
                lock (m_strLogLocker)
                {
                    if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) != null &&
                        (ThreadUiController.m_nlogLevel <= (int)aenumLogLevel) &&
                        astrlog != null &&
                        (InitLog() || !IsLogExceedLength())
                        )
                    {
                        FileInfo info = new FileInfo(GetlogFileName());
                        m_logger = new StreamWriter(info.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
                        string        format  = "{0} | [{1}] | {2} \r\n";
                        StringBuilder builder = new StringBuilder();
                        string        str2    = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
                        builder.AppendFormat(format, str2, aenumLogLevel, astrlog);


                        if (aenumLogLevel == LOG_LEVEL.FATAL || aenumLogLevel == LOG_LEVEL.ERROR || abPrintStack)
                        {
                            var    l_CurrentStack = new System.Diagnostics.StackTrace(true);
                            String lstrData       = l_CurrentStack.ToString();
                            builder.Append(lstrData);
                        }
                        m_logger.Write(builder.ToString());
                        m_logger.Flush();
                        m_logger.Close();
                        m_logger = null;
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Esempio n. 49
0
        private static void CurrentDomain_UnhadledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception  = e.ExceptionObject as Exception;
            var message    = string.Empty;
            var stackTrace = string.Empty;

            if (exception != null)
            {
                var stack = new System.Diagnostics.StackTrace(exception, true);

                message    = exception.GetFlattenInnerMessage();
                stackTrace = stack.ToString();
            }

            Log.Fatal("* CurrentDomain_UnhadledException:{0}\r\n{1}", message, stackTrace);

            //if (ExceptionHandler.DoUnhandledException(exception) == DialogResult.Abort)
            //{
            //	// Application.ThreadException은 해당 Exception을 처리하여 다음으로 진행하는데
            //	// CurrentDomain.UnhandledException은 종료 후에도 해당 Exception이 지속되어서 문제 발생
            //	// 다음으로 진행하는 버튼은 제거한다.
            //	System.Diagnostics.Process.GetCurrentProcess().Kill();
            //}
        }
Esempio n. 50
0
 public void Err(string msg, System.Diagnostics.StackTrace st)
 {
     Debug.LogError(msg + $" [trace is <color=red>{st?.ToString()}</color>]");
 }
Esempio n. 51
0
    // 把 callstack 印出來
    public static string GetCallStack()
    {
        var l_CurrentStack = new System.Diagnostics.StackTrace(true);

        return(l_CurrentStack.ToString());
    }
Esempio n. 52
0
 public void SwapStackTopValueTo(object pValue)
 {
     if (m_valueStack.Count > 0)
     {
         m_valueStack.Pop();
         m_valueStack.Push(pValue);
     }
     else
     {
         System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
         Console.WriteLine("SwapStackTopValueTo '" + pValue + "' but stack is empty, stacktrace: " + t.ToString());
         throw new Error("Can't return value (stack empty)");
     }
 }
Esempio n. 53
0
        // Load a CSV file into an array of rows and columns.
        // Assume there may be blank lines but every line has
        public static bool LoadCsv(string filename, out string[] _csvHeaders, out double[][] _csvData)
        {
            // Get the file's text.
            string []   csvHeaders = new string[0];
            double [][] csvData    = new double[0][];

            try
            {
                string whole_file = System.IO.File.ReadAllText(filename);

                // Split into lines.
                whole_file = whole_file.Replace('\n', '\r');
                string[] lines = whole_file.Split(new char[] { '\r' },
                                                  StringSplitOptions.RemoveEmptyEntries);

                //Check if empty
                if (lines.Length < 2)
                {
                    MessageBox.Show("CSV file requires at least one entry", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                if (string.IsNullOrEmpty(lines[0]))
                {
                    MessageBox.Show("CSV file missing header", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                int headerRow    = 0;
                int firstDataRow = 1;
                if (lines[0].Contains("HP Tuners CSV Log File"))
                {
                    //We have a HPL file
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (lines[i].Equals("[Channel Data]"))
                        {
                            firstDataRow = i + 1;
                        }
                        if (lines[i].Equals("[Channel Information]"))
                        {
                            headerRow = i + 2;
                        }
                        if (firstDataRow != 1 && headerRow != 0)
                        {
                            break;
                        }

                        if (i == lines.Length - 2)
                        {
                            MessageBox.Show("Could not find [Channel Data] Or [Channel Information] within HPT CSV log file, giving up.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                            return(false);
                        }
                    }
                }

                // See how many rows and columns there are.
                int num_rows = lines.Length - firstDataRow - 1;
                int num_cols = lines[headerRow].Split(',').Length;

                // Allocate the data array.
                csvHeaders = new string[num_cols];
                csvData    = new double[num_rows - 1][];

                // Load the array.

                string[] headerLine = lines[headerRow].Split(',');
                if (headerLine.Length < 3)
                {
                    MessageBox.Show("Not enough headers in CSV file! Need at least three, possibly wrong file format? I'm giving up, sorry bro.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                csvHeaders = headerLine;

                Parallel.For(firstDataRow, num_rows, r =>
                {
                    string[] line_r = lines[r].Split(',');
                    csvData[r - 1]  = new double[num_cols];
                    for (int c = 0; c < num_cols; c++)
                    {
                        double result;
                        if (String.IsNullOrEmpty(line_r[c]))
                        {
                            continue;
                        }
                        if (Double.TryParse(line_r[c], out result))
                        {
                            csvData[r - 1][c] = result;
                        }
                        else
                        {
                            csvData[r - 1][c] = double.NaN;
                        }
                    }
                });


                return(true);
            }
            catch (Exception e)
            {
                var    currentStack = new System.Diagnostics.StackTrace(true);
                string stackTrace   = currentStack.ToString();

                FlexibleMessageBox.Show("Failed to open file due to error: " + e.Message + Environment.NewLine + "Stacktrace: " + Environment.NewLine + stackTrace,
                                        "Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information,
                                        MessageBoxDefaultButton.Button2);
                return(false);
            } finally
            {
                _csvHeaders = csvHeaders;
                _csvData    = csvData;
            }
        }
        // Token: 0x0600325D RID: 12893 RVA: 0x000C1544 File Offset: 0x000BF744
        private static string GetManagedStackTraceStringHelper(bool fNeedFileInfo)
        {
            StackTrace stackTrace = new StackTrace(0, fNeedFileInfo);

            return(stackTrace.ToString());
        }
 public override AssertFilters AssertFailure(string condition, string message, StackTrace location, StackTrace.TraceFormat stackTraceFormat, string windowTitle)
 {
     return((AssertFilters)Assert.ShowDefaultAssertDialog(condition, message, location.ToString(stackTraceFormat), windowTitle));
 }
Esempio n. 56
0
 public override AssertFilters AssertFailure(string condition, string message, StackTrace location)
 {
     return((AssertFilters)Assert.ShowDefaultAssertDialog(condition, message, location.ToString()));
 }
Esempio n. 57
0
 public static void WriteExceptionLogEx(Exception ex, string extMsg)
 {
     try
     {
         System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(2, true);
         string logStr = string.Format("{0}\r\n{1}\r\n{2}", extMsg, ex.ToString(), stackTrace.ToString());
         LogManager.WriteException(logStr.ToString());
     }
     catch (Exception)
     {
     }
 }
Esempio n. 58
0
 private void LogHandler(string message, string stacktrace, LogType type)
 {
     System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
     // Now use trace.ToString(), or extract the information you want.
     Debug.Log(trace.ToString());
 }
    public void HandleLog(string logString, string stackTrace, LogType type)
    {
        if (logString == null)
        {
            logString = "nullString";
        }
        if (stackTrace == null)
        {
            stackTrace = "nullString";
        }
        string logTypeString = type.ToString();
        BTLoggerConfigEntry loggerConfigEntry;

        if (config != null && config.loggerConfig.ContainsKey(logTypeString))
        {
            loggerConfigEntry = config.loggerConfig[logTypeString];
        }
        else
        {
            loggerConfigEntry = new BTLoggerConfigEntry();
        }

        if (!loggerConfigEntry.AnythingToLog())
        {
            return;
        }

        if (config != null && config.logMessageFilter.Any(filter => Regex.IsMatch(logString, filter)))
        {
            return;
        }

        StringBuilder logBuilder = new StringBuilder();

        logBuilder
        .Append("[")
        .Append(logTypeString)
        .Append("]\t[")
        .Append(DateTime.Now.ToString("T"))
        .Append("]");

        if (loggerConfigEntry.logMessage)
        {
            logBuilder
            .Append("\n")
            .Append(logString);
        }

        if (loggerConfigEntry.logStackTrace)
        {
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
            logBuilder
            .Append("\n")
            .Append(trace.ToString());
        }

        logBuilder.Append("\n");

        using (StreamWriter writer = new StreamWriter((basePath + logFileName).Replace('/', Path.DirectorySeparatorChar), true)){
            writer.WriteLine(logBuilder.ToString());
        }
    }
Esempio n. 60
0
 private static string GetStackTrace()
 {
     System.Diagnostics.StackTrace ss = new System.Diagnostics.StackTrace(true);
     return(ss.ToString());
 }