My service code resided in OnStart() throws Exception(I) and service is stopped. I don't know why is there any ex. thrown?.. This is my code:
public Service1()
{
InitializeComponent();
}
Thread thread;
protected override void OnStart(string[] args)
{
thread = new Thread(delegate()
{
string path = #"D:\levani\FolderListenerTest\ListenedFolder";
FileSystemWatcher listener;
listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
});
thread.Start();
}
public void listener_Created(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
protected override void OnStop()
{
thread.Abort();
}
Log
Log Name: Application
Source: .NET Runtime
Date: 6/11/2012 5:33:27 PM
Event ID: 1026
Task Category: None
Level: Error
Keywords: Classic
User: N/A
Computer: Levan-PC
Description:
Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.File.InternalCopy(System.String, System.String, Boolean)
at System.IO.File.Copy(System.String, System.String)
at FolderListenerService.Service1.listener_Created(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name=".NET Runtime" />
<EventID Qualifiers="0">1026</EventID>
<Level>2</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2012-06-11T14:33:27.000000000Z" />
<EventRecordID>18314</EventRecordID>
<Channel>Application</Channel>
<Computer>Levan-PC</Computer>
<Security />
</System>
<EventData>
<Data>Application: FolderListenerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException
Stack:
at System.IO.__Error.WinIOError(Int32, System.String)
at System.IO.File.InternalCopy(System.String, System.String, Boolean)
at System.IO.File.Copy(System.String, System.String)
at FolderListenerService.Service1.listener_Created(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
</Data>
</EventData>
</Event>
It could be any number of reasons. See File.Copy() documentation, especially the Exceptions section that document all the exceptions that could be thrown.
You need to wrap your File.Copy() and catch any exceptions so you can react appropriately:
public void listener_Created(object sender, FileSystemEventArgs e)
{
try
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
catch {FileNotFoundException e)
{
//do something if file isn't there
}
catch {UnauthorizedAccessException e)
{
//do something if invalid permissions
}
//etc
}
Extra parameter true in File.Copy will overwrite the file if already exists. I think the error is of file already exist.
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name,true);
Put the code in try..catch block and catch the IOException exception. You can do logging in file for further debugging.
We get the WinIOError error (as we get in call stack) when The filename , directory name, or volume label syntax is incorrect. So just check for the correct path and filename.
I don't know why but after I surrounded my code by try {} catch {} it works excellent, Have any idea? This is code:
public Service1()
{
InitializeComponent();
}
Thread thread;
protected override void OnStart(string[] args)
{
try
{
thread = new Thread(delegate()
{
string path = #"D:\levani\FolderListenerTest\ListenedFolder";
FileSystemWatcher listener; listener = new FileSystemWatcher(path);
listener.Created += new FileSystemEventHandler(listener_Created);
listener.EnableRaisingEvents = true;
});
thread.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"D:\levani\bussite.txt", "thread: " + ex.ToString());
}
}
public void listener_Created(object sender, FileSystemEventArgs e)
{
try
{
File.Copy(e.FullPath, #"D:\levani\FolderListenerTest\CopiedFilesFolder\F" + e.Name);
}
catch (Exception ex)
{
File.WriteAllText(#"D:\levani\bussite.txt", "File copy ex: " + ex.ToString());
}
}
protected override void OnStop()
{
thread.Abort();
}
If you create a new thread, you need to be sure to handle all exceptions thrown on that thread. Any unhandled exceptions that occur on a thread created by Thread.Start() will cause your application to terminate.
Specifically, the constructor FileSystemWatcher(string path) and File.Copy(string sourceFileName, string destFileName) throw several exceptions that you are not handling in your current code. Both of these are being called on a separate thread. It is most likely that you are getting an IOException, due to the file already existing (multiple changes to the same file will cause your code to try to copy it more than once, causing a collision on any copies after the first).
You should probably update your File.Copy call to use File.Copy(string sourceFileName, string destFileName, bool overwrite) and wrap your listener_Created function in a try/catch block that does soemthing with the exception (other than rethrowing it).
Related
I am using VS 2017 and SQL server 2016 to do the job. I create a script task that tries to send email by using SendGrid. If I put a break point inside the script task, I won't have problem to execute my SSIS package and then get the email. However, if I simply execute the package, the entire package still can be executed successfully but I cannot get the email, which I suspect that script task does not get executed. The following is the code of my script task
public void Main()
{
string User_Email = Dts.Variables["User::UserEmail"].Value.ToString();
try
{
if (!File.Exists(Dts.Variables["User::OutputPath"].Value.ToString()))
throw new FileNotFoundException();
File.Copy(Dts.Variables["User::OutputPath"].Value.ToString(), Dts.Variables["User::DestinationPath"].Value.ToString() + Dts.Variables["User::co_num"].Value.ToString() + ".pdf", true);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
SendGridMailHelper.SendOrderVerification(User_Email, "user name");
}
catch (FileNotFoundException)
{
MessageBox.Show("The file is not found in the specified location");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.Contains("SendGrid"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "SendGrid.dll"));
}
if (args.Name.Contains("System.Net.Http"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "System.Net.Http.dll"));
}
if (args.Name.Contains("Newtonsoft.Json"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "Newtonsoft.Json.dll"));
}
return null;
}
To be safe, I checked the windows log and it showed the run time error when I run the package without adding check points. However, I cannot figure it out what it means. Any thoughts will be very helpful. Thank you.
Application: DtsDebugHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.MissingMethodException
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7, ST_b240be27e55248ea869be51aa06a2018, Version=1.0.6877.42064, Culture=neutral, PublicKeyToken=null]](<_SendEmail>d__7 ByRef)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper._SendEmail(System.Collections.Generic.List`1, System.Object, System.String)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
In my App.xaml.cs, I have these codes to catch the exceptions and log them
public App()
{
SetupExceptionHandlingInApp();
// other codes
}
private void SetupExceptionHandlingInApp()
{
this.DispatcherUnhandledException += (s, e) =>
{
e.Handled = true;
//LOGGING CODE HERE
this.Shutdown(-1);
};
}
[STAThread]
public static void Main()
{
SetupExceptionHandlingInMain();
//other codes
}
private static void SetupExceptionHandlingInMain()
{
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
//LOGGING CODE HERE
Environment.Exit(1);
};
System.Windows.Forms.Application.ThreadException += (s, e) =>
{
//LOGGING CODE HERE
Environment.Exit(1);
};
TaskScheduler.UnobservedTaskException += (s, e) =>
{
//LOGGING CODE HERE
};
}
Almost cases, I can catch the exception and log it. But the application crashes sometimes while execution, and I can't find an error logged about the exception that caused the crash.
Am I missing a method besides the methods above to catch the exception? I looked at some article on SO but almost them used these methods above.
The log4net works well because I can see all ERROR and INFO log.
EDIT
After following the suggestion of Panagiotis Kanavos, I found out the error:
Application : xxx.exe
Version du Framework : v4.0.30319
Description : le processus a été arrêté en raison d'une erreur interne dans le runtime .NET à l'adresse IP 547541C4 (54380000) avec le code de sortie 80131506.
TRANSLATE
Application: xxx.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an internal error in
the .NET Runtime at IP 547541C4 (54380000) with exit code 80131506.
Perhaps you got an exception that corrupted the state of the process? From the documentation:
Starting with the .NET Framework 4, this event is not raised for
exceptions that corrupt the state of the process, such as stack
overflows or access violations, unless the event handler is
security-critical and has the
HandleProcessCorruptedStateExceptionsAttribute attribute.
Perhaps you can temporarily specify that your handler is security-critical to be able to catch the exception during debugging.
I have a server which listens to HTTP POSTs that several client make sending information. I use Grapevine as http server because methods are really simple and didn't need the complexity of ASP.
Sometimes I get this random
error:
2017-12-12 15:39:25.5642|ERROR|Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController|System.Net.HttpListenerException (0x80004005): The I/O operation has been aborted because of either a thread exit or an application request
at System.Net.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Grapevine.Interfaces.Server.HttpRequest.get_Payload()
at Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController.PostPatente(IHttpContext context)
This is the
class/method:
namespace Omnibox_Server.Modelo.HttpServer.Controllers
{
[RestResource(BasePath = "/openalpr")]
public class OpenALPRController
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
public IHttpContext PostPatente(IHttpContext context)
{
try
{
context.Response.StatusCode = HttpStatusCode.Ok;
context.Response.ContentType = ContentType.JSON;
context.Response.ContentEncoding = Encoding.UTF8;
var fotoOpenAlpr = JsonConvert.DeserializeObject<FotoOpenALPR>(context.Request.Payload); //<--- exception occurs here? shouldn't try/catch work?
var ip = context.Request.RemoteEndPoint;
if (fotoOpenAlpr.agent_uid != null)
Task.Run(async () =>
{
if (fotoOpenAlpr.is_parked) return;
await fotoOpenAlpr.ObtenerFoto(ip.Address);
try
{
var foto = new Foto(fotoOpenAlpr);
if (foto.IdOmnibox == 0) Logger.Info("Omnibox sin ID con IP " + ip.Address);
await foto.Procesar();
}
catch (Exception e)
{
}
});
context.Response.SendResponse(HttpStatusCode.Ok); //or maybe exception triggers here?
}
catch (Exception e)
{
Logger.Error(e);
}
return context;
}
}
}
An event is generated in the
windows log:
Application: Omnibox Server.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
at Grapevine.Server.Router.Route(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Both exception log and windows log in the event viewer have the same timestamp.
From the OP:
I fixed the issue by moving the line context.Response.SendResponse(HttpStatusCode.Ok); below the try/catch. I think what happened was that sometimes TCP pipe breaks and payload is corrupt/incomplete, therefore an exception is thrown when trying to get it, and because I didn't SendResponse(OK) another exception is thrown outside the try/catch, breaking my server.
I have an executable that is written in C# which runs fine on one computer but crashes without providing an error on another computer.
Is there a class that I can add to my code that will dump all the information relating to the crash no matter where the error occurs within the code?
I have seen this post but I was hoping to create a "catch all" error handling class that would exist in my code.
Try the AppDomain exception handler:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
Code sample:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
var thr = new Thread(() =>
{
Thread.Sleep(1000);
throw new Exception("Custom exception from thread");
});
thr.Start();
thr.Join();
Console.WriteLine("Done");
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//Log information from e.ExceptionObject here
}
}
In this example a custom global exception handler is registered, and then a thread is started which throws an exception after 1 second. The global exception handler is then invoked, with the custom exception that has been thrown.
I have a ErrorRecorder App, which prints the error report out and asks if the user wants to send that report to me.
Then, I have the main app. If an error occurs, It writes the error report to a file and asks ErrorRecorder to open that file to show user the error report.
So I am catching most of my errors using Try/Catch.
However, what if an error occurs that was completely unexpected and it shuts down my program.
Is there like an Global/Override method or something of that kind, that tells the program "Before shutting down if an unexpected error occurs, call the "ErrorRecorderView()" Method"
i think this is what you're after - you can handle exceptions at the appdomain level - i.e. across the whole program.
http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx
using System;
using System.Security.Permissions;
public class Test
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Example()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try
{
throw new Exception("1");
}
catch (Exception e)
{
Console.WriteLine("Catch clause caught : " + e.Message);
}
throw new Exception("2");
// Output:
// Catch clause caught : 1
// MyHandler caught : 2
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
public static void Main()
{
Example();
}
}