/// <summary> /// This builds a string detailing the given exception. /// </summary> /// <param name="ex">The exceptions to describe.</param> /// <returns>A string detailing the given exception.</returns> public static string CreateTraceExceptionString(Exception ex) { if (ex == null) return "\tNO EXCEPTION."; StringBuilder stbException = new StringBuilder(); stbException.AppendLine("Exception: "); stbException.AppendLine("Message: ").Append("\t"); stbException.AppendLine(ex.Message); stbException.AppendLine("Full Trace: ").Append("\t"); stbException.AppendLine(ex.ToString()); if (ex is BadImageFormatException) { BadImageFormatException biex = (BadImageFormatException)ex; stbException.AppendFormat("File Name:\t{0}", biex.FileName).AppendLine(); stbException.AppendFormat("Fusion Log:\t{0}", biex.FusionLog).AppendLine(); } while (ex.InnerException != null) { ex = ex.InnerException; stbException.AppendLine("Inner Exception:"); stbException.AppendLine(ex.ToString()); } return stbException.ToString(); }
public static void WriteLine(string text, Exception ex = null, int logLevel = 4) { string content = text; if (ex != null) content += ex.ToString(); if (Convert.ToBoolean(ConfigurationManager.AppSettings["consoleDebug"])) { Console.WriteLine(content); } else { } if(logLevel <= m_vLogLevel) { lock (m_vSyncObject) { m_vTextWriter.Write(DateTime.Now.ToString("yyyy/MM/dd/HH/mm/ss")); m_vTextWriter.Write("\t"); m_vTextWriter.WriteLine(content); if (ex != null) m_vTextWriter.WriteLine(ex.ToString()); m_vTextWriter.Flush(); } } }
public void SetupGeneric(Exception exception) { try { this.Text = "Error"; this.splitter1.Visible = false; this.panel3.Dock = DockStyle.None; this.panel3.Visible = false; this.panel1.Dock = DockStyle.Fill; this.panel1.BringToFront(); var errorText = exception.ToString(); if (exception is InvalidSQLException) errorText = "FileName: '" + ((InvalidSQLException)exception).FileName + "'" + errorText; UpgradeInstaller.LogError(exception.InnerException, "[ERROR]\r\n" + errorText); if (exception.InnerException != null) txtError.Text = exception.InnerException.ToString(); else txtError.Text = exception.ToString(); cmdSkip.Visible = false; } catch (Exception ex) { //Do Nothing } }
public static void LogException(Exception exception) { if (exception != null) { Debug.Print(exception.ToString()); Logger.Error(exception.ToString()); try { var error = new VLogServerSideError(exception); VLogErrorCode weberrorcode = VLog.GetWebErrorCodeOrDefault(error.ErrorCode, VLogErrorTypes.ServerSideIIS); if (weberrorcode != null && !weberrorcode.ExcludeFromLogging) { if (VLog.OnCommitExceptionToServerRepository != null) { VLog.OnCommitExceptionToServerRepository(error); } } } catch (Exception ex) { // IMPORTANT! We swallow any exception raised during the // logging and send them out to the trace . The idea // here is that logging of exceptions by itself should not // be critical to the overall operation of the application. // The bad thing is that we catch ANY kind of exception, // even system ones and potentially let them slip by. Logger.Error(ex.ToString()); System.Diagnostics.Debug.WriteLine(ex.Message); } } }
public static Exception GetClientException(Exception exp, string MethodName) { Exception e; String str=null; if (exp is FaultException) { WriteException(exp.ToString(), str); return exp; } if (exp is CommunicationException) { WriteException(exp.ToString(), str); return exp; } if (exp is EndpointNotFoundException) { WriteException(exp.ToString(), str); } else { WriteException(exp.ToString(), str); // Exception GenException = new GenericException(exp.Message, exp); } return null; }
public void Failed(IExample example, Exception exception) { LastResult = TaskResult.Exception; _server.TaskOutput(CurrentTask, "Failed:", TaskOutputType.STDERR); _server.TaskOutput(CurrentTask, exception.ToString(), TaskOutputType.STDERR); _server.TaskFinished(CurrentTask, exception.ToString(), TaskResult.Exception); }
/// <summary> /// /// </summary> /// <param name="ex"></param> public static OpenCvSharpException CreateException(Exception ex) { StringBuilder message = new StringBuilder(); if (System.Globalization.CultureInfo.CurrentCulture.Name.Contains("ja")) { message.AppendFormat("{0}\n", ex.Message); message.Append("*** P/Invokeが原因で例外が発生しました。***\n") .Append("以下の項目を確認して下さい。\n") .Append("(1) OpenCVのDLLが実行ファイルと同じ場所に置かれていますか? またはパスが正しく通っていますか?\n") .Append("(2) Visual C++ Redistributable Packageをインストールしましたか?\n") .Append("(3) OpenCVのDLLやOpenCvSharpの対象プラットフォーム(x86またはx64)と、プロジェクトのプラットフォーム設定が合っていますか?\n") .Append("\n") .Append(ex.ToString()); } else { message.AppendFormat("{0}\n", ex.Message); message.Append("*** An exception has occurred because of P/Invoke. ***\n") .Append("Please check the following:\n") .Append("(1) OpenCV's DLL files exist in the same directory as the executable file.\n") .Append("(2) Visual C++ Redistributable Package has been installed.\n") .Append("(3) The target platform(x86/x64) of OpenCV's DLL files and OpenCvSharp is the same as your project's.\n") .Append("\n") .Append(ex.ToString()); } return new OpenCvSharpException(message.ToString(), ex); }
public static int PrintError(Exception ex) { if (ex is CommandException) { Log.Error(ex.Message); return 1; } if (ex is ReflectionTypeLoadException) { Log.Error(ex.ToString()); foreach (var loaderException in ((ReflectionTypeLoadException)ex).LoaderExceptions) { Log.Error(loaderException.ToString()); if (!(loaderException is FileNotFoundException)) continue; var exFileNotFound = loaderException as FileNotFoundException; if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { Log.Error(exFileNotFound.FusionLog); } } return 43; } Log.Error(ex.ToString()); return 100; }
/// <summary> /// Initialize w/ required values /// </summary> public DisplayableExceptionDisplayForm(Exception exception) { // // Required for Windows Form Designer support // InitializeComponent(); this.labelMessage.Font = Res.GetFont(FontSize.Large, FontStyle.Bold); this.buttonOK.Text = Res.Get(StringId.OKButtonText); // initialize controls Icon = ApplicationEnvironment.ProductIcon; pictureBoxIcon.Image = errorBitmap; DisplayableException displayableException = exception as DisplayableException; if (displayableException != null) { Text = EnsureStringValueProvided(displayableException.Title); labelMessage.Text = EnsureStringValueProvided(displayableException.Title); textBoxDetails.Text = EnsureStringValueProvided(displayableException.Text); // log the error Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "DisplayableException occurred: {0}", displayableException.ToString())); } else { // log error Trace.WriteLine("Non DisplayableException-derived exception thrown. Subsystems need to handle these exceptions and convert them to WriterExceptions:\r\n" + exception.ToString()); // give the user a full data dump Text = Res.Get(StringId.UnexpectedErrorTitle); labelMessage.Text = exception.GetType().Name; textBoxDetails.Text = exception.ToString(); } }
private static void AnomalyShow(Exception exc) { _anomaly = true; if (ApcsAccess.Logger != null) ApcsAccess.Logger.LogError(Utilities.TextTidy(exc.ToString())); MessageBox.Show(Utilities.TextTidy(exc.ToString()), "Anomaly!", MessageBoxButton.OK, MessageBoxImage.Error); }
internal static void WriteException(Exception e) { WriteLine(e.ToString()); WriteLine(e.InnerException?.ToString()); Console.WriteLine(e.ToString()); Console.WriteLine(e.InnerException?.ToString()); }
/// <summary> /// Compares the ClientExpectedException to the provided exception and verifies the exception is correct /// </summary> /// <param name="expectedClientException">Expected Client Exception</param> /// <param name="exception">Actual Exception</param> public void Compare(ExpectedClientErrorBaseline expectedClientException, Exception exception) { ExceptionUtilities.CheckAllRequiredDependencies(this); if (expectedClientException == null) { string exceptionMessage = null; if (exception != null) { exceptionMessage = exception.ToString(); } this.Assert.IsNull(exception, "Expected to not recieve an exception:" + exceptionMessage); return; } this.Assert.IsNotNull(exception, "Expected Exception to not be null"); this.Assert.AreEqual(expectedClientException.ExpectedExceptionType, exception.GetType(), string.Format(CultureInfo.InvariantCulture, "ExceptionType is not equal, receieved the following exception: {0}", exception.ToString())); if (expectedClientException.HasServerSpecificExpectedMessage) { if (this.ShouldVerifyServerMessageInClientException) { this.Assert.IsNotNull(exception.InnerException, "Expected Inner Exception to contain ODataError"); byte[] byteArrPayload = HttpUtilities.DefaultEncoding.GetBytes(exception.InnerException.Message); ODataErrorPayload errorPayload = this.ProtocolFormatStrategySelector.DeserializeAndCast<ODataErrorPayload>(null, MimeTypes.ApplicationXml, byteArrPayload); expectedClientException.ExpectedExceptionMessage.VerifyMatch(this.systemDataServicesVerifier, errorPayload.Message, true); } } else { expectedClientException.ExpectedExceptionMessage.VerifyMatch(this.systemDataServicesClientVerifier, exception.Message, true); } }
/// <summary> /// Dislays a <see cref="MessageBox"/> indication an exception. /// </summary> /// <param name="value">The screen to show the <see cref="MessageBox"/> on.</param> /// <param name="ex">The exception to display.</param> public static void ShowError(this IScreenObject value, Exception ex) { #if DEBUG Debug.WriteLine(ex.ToString()); #endif value.ShowMessageBox(ex.ToString(), "Fehler", Microsoft.LightSwitch.Presentation.Extensions.MessageBoxOption.Ok); }
public string Handle(Exception exc) { if (!QPP.Wpf.UI.Util.IsDesignMode) { if (exc is ValidationException) { RuntimeContext.Service.GetObject<IDialog>().Show(new DialogMessage() { Content = exc.Message }); } //else if (exc is System.Security.Authentication.AuthenticationException) //{ // //Messenger.Default.Send(LoginMessage.Instance); //} else { RuntimeContext.Service.Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + RuntimeContext.Service.L10N.GetText("發生錯誤:") + exc.ToString() + Environment.NewLine); RuntimeContext.Service.GetObject<IDialog>().Show(new DialogMessage() { Content = exc.ToString() }); } } return exc.Message; }
public static bool AnalyzeException(Exception exception) { //if (exception is System.NullReferenceException && exception.ToString().Contains("JsMinifier")) // return true; if (exception is System.Web.HttpException) { if (exception.ToString().Contains("ComponentNotFoundException")) return true; if (exception.ToString().Contains("A potentially dangerous Request.Path")) return true; } var ret = exception.Message.Contains("php") || exception.Message.Contains(".gif") || exception.Message.Contains(".jpg") || exception.Message.Contains(".png") // args.Exception.Message.Contains("Castle.MicroKernel.ComponentNotFoundException") || || exception is Castle.MicroKernel.ComponentNotFoundException //|| exception.Message.ToLower().Contains("jsminifier") || exception.Message.ToLower().Contains("cultureFilter") //|| exception.Message.ToLower().Contains("abs.globalize.en.js") ; return ret; }
public static void ExceptionOccur(string Decription,Exception e) { Console.WriteLine(Decription); Console.WriteLine(e.ToString()); ERRORCOUNT++; Writelog(Decription, e.ToString()); }
private void AnomalyShow(Exception exc) { LogMessage(exc.ToString()); if (DetectorsAccess.Logger != null) DetectorsAccess.Logger.LogError(Utilities.TextTidy(exc.ToString())); MessageBox.Show(Utilities.TextTidy(exc.ToString()), "Anomaly!", MessageBoxButton.OK, MessageBoxImage.Error); }
/// <summary> /// 异常处理 /// </summary> /// <param name="e">异常</param> /// <param name="isThrow">是否抛出异常</param> /// <param name="preMsg">添加在异常消息前面的文字</param> public static void DoExeption(Exception e, bool isThrow,string preMsg) { string msg =preMsg+":" + e.ToString(); if (null != e.InnerException) msg += e.ToString(); Log.Error(msg); if (isThrow) throw e; }
/// <summary> /// Constructor when an Exception has been or will be thrown. /// </summary> /// <param name="re">The corresponding Exception</param> /// <param name="fatal">Set to true if the fault requires the serial port to be closed.</param> /// <param name="receiver">The Receiver object associated with the VEMCO hardware.</param> /// <param name="portName">The name of the serial port it is connected to (i.e. COM1)</param> /// <param name="serialNumber">The serial number of the receiver.</param> /// <param name="model">The model of the receiver.</param> /// <param name="config">The json object for the configration file.</param> public ExcepReceiver(Exception re, Boolean fatal, Receiver receiver, string portName, string serialNumber, string model, FridayThe13th.JsonObject config) : base("Receiver Exception: " + receiver + "entered exception condition. Fatal? " + fatal + " Exception text: " + re.ToString(), receiver, portName, serialNumber, model, config) { this["exception"] = re; this["fatal"] = fatal; this["note"] = re.ToString(); }
static private void _OnUnresolvedExceptionHandler(object sender, System.UnhandledExceptionEventArgs args) { if (args == null) { return; } if (args.ExceptionObject == null) { return; } try { System.Type type = args.ExceptionObject.GetType(); if (type == typeof(System.Exception)) { System.Exception e = (System.Exception)args.ExceptionObject; #if (UNITY_IPHONE && !UNITY_EDITOR) string str1 = _EscapeString(e.ToString()); string str2 = _EscapeString(e.Message); string str3 = _EscapeString(e.StackTrace); Crittercism_NewException(str1, str2, str3); Crittercism_LogUnhandledException(); Crittercism_LogUnhandledExceptionWillCrash(); #else string message = e.ToString() + "\n" + e.Message + "\n" + e.StackTrace; if (args.IsTerminating) { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.LogError("CrittercismIOS: Terminal Exception: " + message); } } else { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.LogWarning(message); } } #endif } else { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.Log("CrittercismIOS: Unknown Exception Type: " + args.ExceptionObject.ToString()); } } }catch { if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.Log("CrittercismIOS: Failed to resolve exception"); } } }
public Response HandleException(NancyContext context, Exception exception) { _logger.Trace("Handling Exception"); var apiException = exception as ApiException; if (apiException != null) { _logger.WarnException("API Error", apiException); return apiException.ToErrorResponse(); } var validationException = exception as ValidationException; if (validationException != null) { _logger.Warn("Invalid request {0}", validationException.Message); return validationException.Errors.AsResponse(HttpStatusCode.BadRequest); } var clientException = exception as NzbDroneClientException; if (clientException != null) { return new ErrorModel { Message = exception.Message, Description = exception.ToString() }.AsResponse((HttpStatusCode)clientException.StatusCode); } var sqLiteException = exception as SQLiteException; if (sqLiteException != null) { if (context.Request.Method == "PUT" || context.Request.Method == "POST") { if (sqLiteException.Message.Contains("constraint failed")) return new ErrorModel { Message = exception.Message, }.AsResponse(HttpStatusCode.Conflict); } var sqlErrorMessage = string.Format("[{0} {1}]", context.Request.Method, context.Request.Path); _logger.ErrorException(sqlErrorMessage, sqLiteException); } _logger.FatalException("Request Failed", exception); return new ErrorModel { Message = exception.Message, Description = exception.ToString() }.AsResponse(HttpStatusCode.InternalServerError); }
public static void HandleException(Exception ex, bool ShowMessage = true) { string Message = string.Empty; StringBuilder msgBuilder = new StringBuilder(); //CustomErrorInfo ellenőrzés, hozzáadás üzenethez if (ex.Data.Contains("CustomErrorInfo")) { msgBuilder.Append("CustomErrorInfo: " + ex.Data["CustomErrorInfo"] + "\n"); } if (ex is ExcelToSql.InvalidRangeException) { msgBuilder.Append(ex.Message); } else if (ex is ExcelToSql.InvalidSheetException) { msgBuilder.Append(ex.Message); } else if (ex is ExcelToSql.ProtectedWorkbookModifacationException) { msgBuilder.Append(ex.Message); } else if (ex is WebException && ex.Message.Contains("Unable to connect to the remote server")) { msgBuilder.Append("Service is not available!"); } else if (ex is WebException && ex.Message.Contains("The remote name could not be resolved")) { msgBuilder.Append("Network is not avaliable!"); } else if (ex is SoapException) { if (ex.Message.Contains("Login failed")) { msgBuilder.Append("Login failed! Invalid SQL user!"); } else if (ex.Message.Contains("A network-related or instance-specific")) { msgBuilder.Append("Network error! Database is not available!"); } else { msgBuilder.Append(ex.ToString()); } } else { msgBuilder.Append(ex.ToString()); } Message = msgBuilder.ToString(); if (ShowMessage) { System.Windows.Forms.MessageBox.Show(Message); } }
/// <summary> /// Exception handler. /// Writes details of the exception to the console and to the debug /// stream. /// </summary> /// <param name="ex"></param> public static void Handle( Exception ex ) { if( ex == null ) { return; } System.Diagnostics.Debug.WriteLine( ex.ToString() ); Console.WriteLine( ex.ToString() ); }
private static void ShowException(Exception ex) { if (ex == null) return; Console.WriteLine(ex.ToString()); Console.ReadKey(); var tmpFile = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), ".txt"); System.IO.File.WriteAllText(tmpFile, ex.ToString()); Process.Start(tmpFile); }
/// <summary> /// An exception was thrown, so this will post the stack trace and message to debug. /// </summary> /// <param name="ex">The exception to log.</param> public virtual void Exception(Exception ex) { Debug.WriteLine(ex.ToString()); if (_debugFile != null) { TextWriter tw = new StreamWriter(_debugFile, true); tw.WriteLine(ex.ToString()); } }
static public void ShowError(System.Windows.Forms.IWin32Window owner, Exception Ex) { try { System.Diagnostics.Debug.WriteLine(Ex.ToString()); } catch { } //Save error to the last error log. //Vista: C:\ProgramData //XP: c:\Program Files\Common Files string path = string.Empty; //XP = 5.1 & Vista = 6.0 if (Environment.OSVersion.Platform == PlatformID.Unix) { path = Environment.GetFolderPath (Environment.SpecialFolder.Personal); path = System.IO.Path.Combine(path, ".Gurux"); } else { if (Environment.OSVersion.Version.Major >= 6) { path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); } else { path = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); } path = System.IO.Path.Combine(path, "Gurux"); } path = System.IO.Path.Combine(path, "GXDLMSDirector"); if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } path = System.IO.Path.Combine(path, "LastError.log"); System.IO.TextWriter tw = System.IO.File.CreateText(path); tw.Write(Ex.ToString()); tw.Close(); System.Windows.Forms.Control ctrl = owner as System.Windows.Forms.Control; if (ctrl != null && !ctrl.IsDisposed && ctrl.InvokeRequired) { ctrl.Invoke(new ShowErrorEventHandler(OnShowError), owner, Ex); } else { if (ctrl != null && ctrl.IsDisposed) { System.Windows.Forms.MessageBox.Show(Ex.Message); } else { System.Windows.Forms.MessageBox.Show(owner, Ex.Message); } } }
public static void Error(Exception exception) { System.Diagnostics.Debug.WriteLine(exception.ToString()); using (StreamWriter file = new StreamWriter(@"Exceptions.txt", true)) { file.WriteLine(exception.ToString()); file.Close(); } }
/// <summary> /// This method gets the stack trace for reporting purposes. /// </summary> /// <param name="ex"></param> /// <returns></returns> public string GetStackTrace(Exception ex) { if (ex.InnerException != null) { return ex.ToString() + "--------------------------" + GetStackTrace(ex.InnerException); } return ex.ToString(); }
public bool HandleError(Exception error) { if (error is UserException) Logger.Trace(() => error.ToString()); else if (error is ClientException) Logger.Info(() => error.ToString()); else Logger.Error(() => error.ToString()); return false; }
/// <summary> /// Log an exception that has been handled in code. /// This exception will be reported to the Crittercism portal. /// </summary> static public void LogHandledException(System.Exception e) { if (e == null) { return; } /* #if (UNITY_IPHONE && !UNITY_EDITOR) * string str1 = _EscapeString(e.ToString()); * string str2 = _EscapeString(e.Message); * string str3 = _EscapeString(e.StackTrace); * * Crittercism_NewException(str1, str2, str3); * Crittercism_LogHandledException(); #else */ string message = e.ToString() + "\n" + e.Message + "\n" + e.StackTrace; if (Debug.isDebugBuild == true || _ShowDebugOnOnRelease == true) { Debug.LogWarning(message); } //#endif }
public static void Main(Args _args) { try { str tenant = "XXXXXXX"; str serviceResourceId = "X-X-X-X-X"; str clientId = "X-X-X-X-X"; str appKey = "XXXXXXX"; str functionURL = "https://XXXXXXX.azurewebsites.net/api/HttpTrigger1?code=XXXXXXX=="; functionURL += "&name=Dag"; // Must use 'var' instead of 'System.Threading.Tasks.Task<System.String>' because of the F&O compiler var t = PLUtilities.AzureFunctionHelper::authAndCallFunction(tenant, serviceResourceId, clientId, appKey, functionURL); t.Wait(); str s = t.Result; info(s); } catch (Exception::CLRError) { System.Exception ex = ClrInterop::getLastException(); if (ex != null) { ex = ex.get_InnerException(); if (ex != null) { error(ex.ToString()); } } } }
public virtual void fireReportError(System.Exception e) { MessageEventHandler eventDelegate = (MessageEventHandler)((CharScanner)source).Events[Parser.ReportErrorEventKey]; if (eventDelegate != null) { messageEvent.setValues(MessageEventArgs.ERROR, e.ToString()); eventDelegate(source, messageEvent); } checkController(); }
private void AppendInnerExceptions(StringBuilder tos) { EException inner = this.InnerException; while (inner != null) { tos.AppendLine("## INNER EXCEPTION ##"); tos.AppendLine(inner.ToString()); inner = inner.InnerException; } }
/// <summary> /// If the exception is not a FriendlyException, wrap with a RuntimeException /// </summary> /// <param name="throwable"> The exception to potentially wrap </param> /// <returns> Original or wrapped exception </returns> public static System.Exception wrapUnfriendlyExceptions(System.Exception throwable) { if (throwable is FriendlyException) { return((FriendlyException)throwable); } else { return(new System.Exception(throwable.ToString())); } }
private static string BuildExceptionWithEnvironmentInfo(System.Exception ex) { StringBuilder strB = new StringBuilder(); using (StringWriter sw = new StringWriter(strB)) { sw.WriteLine(GetEnvironmentInfo()); sw.WriteLine(ex.ToString()); } return(strB.ToString()); }
protected string ToString(System.Exception ex) { string result = null; if (ex != null) { result = "============= EXCEPTION ==============\r\n"; result += ex.ToString() + "\r\n"; result += "============= ENDEXCEPTION ==============\r\n"; } return(result); }
public static void SendDataAndShowMessage(System.Exception ex) { string text = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "\n" + ex.ToString();// тут хорошо бы его отформатировать, скажем, в XML, добавить данные о времени, дате, железе и софте... try { File.AppendAllText(@"reports_ssm.txt", "\n\n\n\n" + text); } catch { } }
/// <summary> /// Puts given exception to trace output, adding the time it happends. /// </summary> /// <param name="ex">Exception to handle.</param> public static void Put(System.Exception ex) { System.Text.StringBuilder msg = new System.Text.StringBuilder(); msg.Append("Exception: " + Environment.NewLine + ex.ToString() + Environment.NewLine); msg.Append("Source: " + Environment.NewLine + ex.Source + Environment.NewLine); if (ex.InnerException != null) { msg.Append("Inner exception: " + Environment.NewLine + ex.InnerException.ToString() + Environment.NewLine); msg.Append("Source: " + Environment.NewLine + ex.InnerException.Source); } Put(msg.ToString()); }
public static void WriteWarningToLog(System.Exception Exception) { try { EventLog iLog = GetEventLog(); iLog.WriteEntry(Exception.ToString(), EventLogEntryType.Warning); } catch (Exception ex) { WriteEventToApplication(ex.ToString()); } }
protected void GHTSubTestUnexpectedExceptionCaught(System.Exception ex) { string traceText = string.Empty; traceText += "Test Failed. Unxpected "; traceText += ex.GetType().Name; traceText += " exception was caught"; traceText += "<br>Stack Trace: "; traceText += ex.ToString(); GHTSubTestAddResult(traceText); }
public LogEntry(string message, LogEntryLevel level, System.Exception exception, params LogEntryAttribute[] logEntries) { Message = message; Level = level; if (exception != null) { ExceptionText = String.Format("{0}\n\n\t {1}", exception.ToString(), exception.StackTrace); } if (logEntries != null) { Attributes = logEntries.ToList <LogEntryAttribute>(); } }
/// <summary> /// Event Handler for Button Pressed event /// </summary> private void ButtonPressed(object o, EventArgs args) { if (dButton.Label == Util.GS("Show Details")) { details.Text = ex.ToString(); dButton.Label = Util.GS("Hide Details"); } else { details.Text = Util.GS("Click \"Show Details\" below to get the full message returned with this error"); dButton.Label = Util.GS("Show Details"); } }
public void WriteErrorLog(System.Exception ex) { try { string webPageName = Path.GetFileName(Request.Path); string errorLogFilename = "ErrorLog_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt"; string path = Server.MapPath("~/ErrorLogFiles/" + errorLogFilename); if (System.IO.File.Exists(path)) { using (StreamWriter stwriter = new StreamWriter(path, true)) { stwriter.WriteLine("-------------------Error Log Start-----------as on " + DateTime.Now.ToString("hh:mm tt")); stwriter.WriteLine("WebPage Name :" + webPageName); stwriter.WriteLine("Message:" + ex.ToString()); if (ex.InnerException != null) { stwriter.WriteLine("Inner exception: " + ex.InnerException.ToString()); } stwriter.WriteLine("-------------------End----------------------------"); } } else { StreamWriter stwriter = System.IO.File.CreateText(path); stwriter.WriteLine("-------------------Error Log Start-----------as on " + DateTime.Now.ToString("hh:mm tt")); stwriter.WriteLine("WebPage Name :" + webPageName); stwriter.WriteLine("Message: " + ex.ToString()); if (ex.InnerException != null) { stwriter.WriteLine("Inner exception: " + ex.InnerException.ToString()); } stwriter.WriteLine("-------------------End----------------------------"); stwriter.Close(); } } catch (Exception ex1) { } }
public static void Create(System.Exception ex, string method, string library) { var error = new Domain.TBL_ERROR() { CAR_HEADER = ex.ToString(), CAR_MESSAGE = ex.Message, CAR_STACKTRACE = ex.StackTrace, CAR_METHOD = method, CAR_LIBRARY = library }; Save(error); }
private static void LogUnhandledException(System.Exception exception) { //var libraryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); //// iOS: Environment.SpecialFolder.Resources //var errorFilePath = Path.Combine(libraryPath, ErrorFileName); //File.WriteAllText(errorFilePath, errorMessage); // Log to Android Device Logging. //Android.Util.Log.Error("Crash Report", errorMessage); // just suppress any error logging exceptions CollectionCrashReport( $"Time: {DateTime.Now}\r\nError: Unhandled Exception\r\n{exception?.ToString() ?? ""}"); }
private string GetExceptionReport(System.Exception exc) { return exc.ToString(); //string result; //result = "Unhandled exception(" + exc.ToString() + ") occurred:\n"; //java.lang.StackTraceElement[] elements = exc.st.getStackTrace(); //for (int i = 0; i < elements.Length; i++) //{ // result += " at " + elements[i].getFileName() + ", line " // + elements[i].getLineNumber() + " (method '" + elements[i].getMethodName() + "')\n"; //} //return result; }
static new public int ToString(IntPtr l) { try { System.Exception self = (System.Exception)checkSelf(l); var ret = self.ToString(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// /// </summary> /// <param name="context"></param> public void Execute(IJobExecutionContext context) { try { _task = (ScheduledTask)context.MergedJobDataMap["ScheduledTask"]; DateTime planingTime = context.ScheduledFireTimeUtc.HasValue ? context.ScheduledFireTimeUtc.Value.LocalDateTime : DateTime.Now; planingTime = new DateTime(planingTime.Ticks - (planingTime.Ticks % TimeSpan.TicksPerMinute), planingTime.Kind); if (_task.OnlyWorkingDays) { if (HolidayCalculator.Instance.IsHoliday(planingTime, _task.RunAtHalfPublicHoliday)) { return; } } _action = Toolkit.Instance.CreateInstance <IPxTaskAction>(_task.Action); using (PeakDbContext dbContext = new PeakDbContext()) { if (dbContext.ScheduledTaskLogs.FirstOrDefault(x => x.ScheduledTaskId == _task.Id && x.ScheduledTime == planingTime) != null) { return; } ScheduledTaskLog taskLog = new ScheduledTaskLog() { ScheduledTaskId = _task.Id, State = Dal.Enums.ScheduleState.Running, ScheduledTime = planingTime, StartTime = DateTime.Now }; dbContext.ScheduledTaskLogs.Add(taskLog); dbContext.SaveChanges(); bool succeed = executeAction(planingTime, 0); taskLog.EndTime = DateTime.Now; if (succeed) { taskLog.State = Dal.Enums.ScheduleState.Succeed; } else { taskLog.State = Dal.Enums.ScheduleState.Failed; if (_lastError != null) { taskLog.ErrorMessage = _lastError.Message; taskLog.ErrorDetail = _lastError.ToString(); _lastError = null; } } dbContext.SaveChanges(); } } catch (Exception ex) { PxErrorLogger.Log(ex); } }
protected void Application_Error(object sender, EventArgs e) { System.Web.HttpContext context = HttpContext.Current; System.Exception ex = Context.Server.GetLastError(); Logger.ConsoleWriteLine(ex.ToString() + " from URL: \"" + Request.RawUrl + "\"", ConsoleColor.Red); context.Server.ClearError(); if (Request.RawUrl.Contains("Error.aspx")) { return; } Response.Redirect("/Error.aspx?reason=website_error&return=Index.aspx"); }
public string Import(string con, bool ignoreError, string filepath ) { System.Exception error = null; try { using (MySqlConnection conn = new MySqlConnection(con)) { using (MySqlCommand cmd = new MySqlCommand()) { //cmd.Connection = conn; //conn.Open(); using (MySqlBackup mb = new MySqlBackup(cmd, con)) { //mb.ImportInfo.EnableEncryption = cbImEnableEncryption.Checked; //mb.ImportInfo.EncryptionPassword = txtImPwd.Text; mb.ImportInfo.IgnoreSqlError = ignoreError; //mb.ImportInfo.TargetDatabase = txtImTargetDatabase.Text; //mb.ImportInfo.DatabaseDefaultCharSet = txtImDefaultCharSet.Text; mb.ImportInfo.ErrorLogFile = ""; mb.ImportFromFile(filepath); error = mb.LastError; } // conn.Close(); } } if (error == null) { return("done"); } else { return(error.ToString()); } // MessageBox.Show("Finished with errors." + Environment.NewLine + Environment.NewLine + error.ToString()); } catch (System.Exception ex) { throw ex; } }
public static void _BaseLog(object message, Object context, System.Exception exception, eDebugLogMode eMode) { //CommonNet.CNetLog.OutputDebugString((string)message); //m_strCommon = "[Thr:"+System.AppDomain.GetCurrentThreadId().ToString("00000") + "] "; // window only? //m_strCommon = CommonNet.CUnitUtil.TimeStamp(); message = m_strCommon + message; if (m_DebugLogView == true) { switch (eMode) { case eDebugLogMode._None: { Debug.Log(message, context); } break; case eDebugLogMode._Waring: { Debug.LogWarning(message, context); } break; case eDebugLogMode._Error: { Debug.LogError(message, context); } break; case eDebugLogMode._Exception: { Debug.LogException(exception, context); message = exception.ToString(); } break; } } // if (null == m_Log) // m_Log = new CommonNet.CEzLog("Client_debugLog.txt"); // else // { // //m_Log.ReCreate("Client_debugLog.txt"); // m_Log.Log(message.ToString(), CommonNet.LOG_TYPE.INFO); // //m_Log.Close(); // } }
public void OnError(System.Data.IDbCommand profiledDbCommand, SqlExecuteType executeType, System.Exception exception) { SbForDBLog.Clear(); SbForDBLog.Append("エラー発生SQL "); SetCommonLogString(SbForDBLog, executeType) .AppendLine() .AppendLine(exception.ToString()) .Replace(Environment.NewLine, " "); string log = SbForDBLog.ToString(); logger.LogError(log); }
public static void Message(System.Exception ex) { try { System.Windows.Forms.MessageBox.Show( ex.ToString(), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } catch { } }
/// <summary> /// Procedure that loads the exception data into the TestResult object when an /// exception is thrown. /// </summary> /// <param name="e">The exception object.</param> /// <param name="detailedExceptionMessages">boolean that determines if detailed exception /// messages should be used. /// </param> private void SetExceptionData(System.Exception e, bool detailedExceptionMessages) { // Set the ExceptionThrown member to true... this._testResult.ExceptionThrown = true; // Grab the first part of the exception message... this._testResult.ExceptionMessage = e.Message + "\n"; // if we want detailed exception messages, grab call the ToString() // method on the exception object... if (detailedExceptionMessages) { this._testResult.ExceptionMessage += e.ToString(); } // Alert the user that an exception was thrown for this test... this._testResult.ResultGeometryWKT = "Exception thrown for this test."; }
private static string gerarLog(System.Exception e) { string content = string.Empty; if (e.InnerException != null) { content += System.Environment.NewLine + gerarLog(e.InnerException) + System.Environment.NewLine; } else { content = System.Environment.NewLine + e.ToString() + System.Environment.NewLine; } return(content); }
internal void DeadRemoteLogger(IRemoteLoggerPrx remoteLogger, ILogger logger, System.Exception ex, string operation) { // // No need to convert remoteLogger as we only use its identity // if (RemoveRemoteLogger(remoteLogger)) { if (_traceLevel > 0) { logger.Trace(TraceCategory, "detached `" + remoteLogger.ToString() + "' because " + operation + " raised:\n" + ex.ToString()); } } }
private static void OutputError(System.Exception e) { FileLogger logger = new FileLogger(); logger.Log(e.ToString()); Trace.WriteLine("", m_cstrDMCLTraceCategory); Trace.Indent(); Trace.WriteLine("Stack Trace error dumped :", m_cstrDMCLTraceCategory); uint uError = GetLastError(); Trace.WriteLine(e.ToString(), m_cstrDMCLTraceCategory); // Retrieve ow the OS error uError = GetLastError(); if (0 != uError) { Trace.WriteLine("OS Error : " + uError.ToString(), m_cstrDMCLTraceCategory); SetLastError(0); } Trace.WriteLine(null, m_cstrDMCLTraceCategory); Trace.Unindent(); }
public static void LogEvent(System.Exception ex, string msg, bool sendToDev) { string message = string.Empty; try { using (StreamWriter sw = File.Exists(Constants.exceptionsFilePath) ? File.AppendText(Constants.exceptionsFilePath) : File.CreateText(Constants.exceptionsFilePath)) { byte[] dateAsByteArr = Encoding.Default.GetBytes(ex.ToString()); sw.WriteLine(ex.ToString()); sw.WriteLine(); } } catch { message = "An error has occured, unable to log exception to log file" + Environment.NewLine + ex.ToString(); } if (sendToDev) { Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application(); MailItem mail = outlook.CreateItem(OlItemType.olMailItem); mail.To = Constants.developer; mail.Subject = "Time tracking error"; mail.BodyFormat = OlBodyFormat.olFormatPlain; mail.Body = string.Format("{0}{1}{2}{3}{4}", msg, Environment.NewLine, ex.ToString(), Environment.NewLine, ex.InnerException); mail.Display(); } else { if (string.IsNullOrEmpty(message)) { message = string.Format("An error has occured - see log {0}", Constants.exceptionsFilePath); } } }
static void Error(Exception ex) { if (File.Exists(ConfigurationManager.AppSettings["Error"]) == true) { File.Delete(ConfigurationManager.AppSettings["Error"]); } using (FileStream file = File.Create(ConfigurationManager.AppSettings["Error"])) { using (StreamWriter sw = new StreamWriter(file)) { if (ex.GetType() == typeof(WebException)) { sw.Write(((WebException)ex).ToString()); System.Console.WriteLine(((WebException)ex).ToString()); } else { sw.Write(ex.ToString()); System.Console.WriteLine(ex.ToString()); } sw.Close(); } file.Close(); } }
/// <summary> /// DllImportの際にDllNotFoundExceptionかBadImageFormatExceptionが発生した際に呼び出されるメソッド。 /// エラーメッセージを表示して解決策をユーザに示す。 /// </summary> /// <param name="e"></param> public static void DllImportError(Exception e) { string nl = Environment.NewLine; if (System.Globalization.CultureInfo.CurrentCulture.Name.Contains("ja")) { MessageBox.Show( "P/Invokeが原因で例外が発生しました。" + nl + "以下の項目を確認して下さい。" + nl + nl + "1. OpenCVのDLLが実行ファイルと同じ場所に置かれていますか? またはパスが正しく通っていますか?" + nl + "2. Visual C++ Redistributable Packageをインストールしましたか?" + nl + "3. OpenCVのDLLやOpenCvSharpの対象プラットフォーム(x86またはx64)と、プロジェクトのプラットフォーム設定が合っていますか?" + nl + nl + e.ToString(), "OpenCvSharp Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } else { MessageBox.Show( "An exception has occurred because of P/Invoke." + nl + "Please check the following:" + nl + nl + "1. OpenCV's DLL files exist in the same directory as the executable file." + nl + "2. Visual C++ Redistributable Package has been installed." + nl + "3. The target platform(x86/x64) of OpenCV's DLL files and OpenCvSharp is the same as your project's." + nl + nl + e.ToString(), "OpenCvSharp Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }