Emgu.CV , CvBlob.BoundingBox throw System.AccessViolationException - c#

Im using Emgu.CV (OpenCV), to find delta in image, but sometimes I get Access violation exception that cause my app to crash.
After digging in the debug I find that (blobs.Values):
List<CvBlob> listOfBlobs = blobs.Values.ToList();
return 1733 items, and when I do the following:
But when run through the list I get EXCEPTION:
if (resultedRectangles[j].Contains(listOfBlobs[i].BoundingBox))
I check and find the exception occurred at: i = 418 :
+BoundingBox '(new System.Collections.Generic.Mscorlib_CollectionDebugView(listOfBlobs)).Items[418].BoundingBox'
threw an exception of type
'System.AccessViolationException' System.Drawing.Rectangle
{System.AccessViolationException}
As I see the last valid value in the list is in 417.
I have 2 questions:
1. Why blobs.Values.ToList(); return such corrupt data?
2. How I can check the value before access it to prevent System.AccessViolationException ?

Are you having multiple threads in your Process? If there are multiple threads trying to initialize the List, then the list may get corrupted.
This exception is more specific to Memory related issues and you will be in a hard time to debug this, unless the all the code is in your control. The following link may help.
http://msdn.microsoft.com/en-us/library/system.accessviolationexception(v=vs.110).aspx
Me too got trapped in the same error.

Related

How to fix random FileSystemEnumerableIterator.MoveNext Error. The handle is invalid

I just started randomly getting the error on a program that has been running for years. all this program does is look at a set of directories and delete files based on their last write time.
Here is the error and stack trace.
Error: The handle is invalid.
Stack Trace: at System.IO.__Error.WinIOError(Int32 errorCode, String
maybeFullPath) at System.IO.FileSystemEnumerableIterator`1.MoveNext()
at DirectoryCleaner.Program.GetNewFiles()
Here is the code
DirectoryInfo di = new DirectoryInfo(sourcePath);
foreach (FileSystemInfo file in di.EnumerateFileSystemInfos(variablePattern == true ? "*" : SearchPattern, searchSubDirectories == true ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
{
creates queue of records to delete. I removed the logic as it is rather long...
}
I have spent several hours searching. I found
System.IO.IOException: The handle is invalid, when using Directory.EnumerateDirectories but it does not have an answer.
The stack trace shows that it is in the MoveNext method which I do not directly call. I assume the foreach loop calls it. How can I correct what is causing this?
This error occurs because the various file/directory EnumerateX methods are effectively wrappers around the native Win32 FindFirstFile function, and as per its documentation:
If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.
If we look at the relevant portion of the Framework Reference Source, we see that any error not handled explicitly is surfaced as an IOException. This would include INVALID_HANDLE_VALUE.
In other words, this is an expected potential exception while calling an EnumerateX method and your code should handle it correctly by catching the generic IOException. The docs for the various EnumerateX methods fail to call this out, which IMO is an omission, and as such I've opened an issue to get that fixed.

'System.Reflection.TargetInvocationException' when calling Activator.CreateInstance()

I am receiving this error:
A first chance exception of type 'System.Reflection.TargetInvocationException'
occurred in mscorlib.dll
and also:
Exception has been thrown by the target of an invocation.
when running this method, and the error is occurring on the CreateInstance(Type.GetType(instantiationString), parameters) call:
public static Report instantiateReport(ReportInfo reportInfo)
{
string instantiationString;
Report reportToReturn;
ReportInfo[] parameters = new ReportInfo[1];
parameters[0] = reportInfo;
instantiationString = reportInfo.Report.InstantiationPath;
reportToReturn = (Report)Activator.CreateInstance(Type.GetType(instantiationString), parameters);
return reportToReturn;
}
ReportInfo is just a custom class that contains variables that help me build the report that I am trying to instantiate and when I investigate it, everything is completely fine. The instantiationString just helps me understand which report is trying to be created at the call and that way I can use the Type.GetType() method. I really have no idea what kind of error this is or what could be going wrong. I researched it a bit but didn't receive any helpful answer so any help is appreciated.
EDIT After looking at the inner exception I am getting Object reference not set to an instance of an object. message. This is strange because neither the ReportInfo or the GetType() methods have a null reference. Say one of the variables within ReportInfo was null, could that cause an issue? It shouldn't right?
FIXED After delving into the stack trace of the inner exception I found that there was some conflicting code causing issues elsewhere. Problem solved.

Unhandled Exception in C# Console Application causing AppCrash

I have a Windows Console application built in Visual Studio 2010 and it keeps crashing but the error is not caught by the visual studio debugging tool nor by try/catch statements in my code.
I have managed to locate the WER file on my system and would like to be able to understand the contents of the file so I can pinpoint exactally what is causing the unhandled exception.
I would be greatful if anyone can offer some idea on how I can use the following information to locate the process causing me this problem and also what the exception may be...
The information from the WER file is:
Version=1
EventType=APPCRASH
EventTime=129973086237604286
ReportType=2
Consent=1
ReportIdentifier=91331e8b-2dc8-11e2-977b-080027f7e5bb
IntegratorReportIdentifier=91331e8a-2dc8-11e2-977b-080027f7e5bb
WOW64=1
Response.type=4
Sig[0].Name=Application Name
Sig[0].Value=SAGE_TESTING.vshost.exe
Sig[1].Name=Application Version
Sig[1].Value=10.0.30319.1
Sig[2].Name=Application Timestamp
Sig[2].Value=4ba2084b
Sig[3].Name=Fault Module Name
Sig[3].Value=ntdll.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=6.1.7600.16385
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=4a5bdb3b
Sig[6].Name=Exception Code
Sig[6].Value=c015000f
Sig[7].Name=Exception Offset
Sig[7].Value=000845bb
DynamicSig[1].Name=OS Version
DynamicSig[1].Value=6.1.7600.2.0.0.272.7
DynamicSig[2].Name=Locale ID
DynamicSig[2].Value=2057
DynamicSig[22].Name=Additional Information 1
DynamicSig[22].Value=0a9e
DynamicSig[23].Name=Additional Information 2
DynamicSig[23].Value=0a9e372d3b4ad19135b953a78882e789
DynamicSig[24].Name=Additional Information 3
DynamicSig[24].Value=0a9e
DynamicSig[25].Name=Additional Information 4
DynamicSig[25].Value=0a9e372d3b4ad19135b953a78882e789
Here is the section of code I believe to be causing the exception to be thrown:
//Data from the project linked to the split data
if (oSplitData.Project != null)
{
oProject = oSplitData.Project as SageDataObject190.Project;
oBasicDetail.ProjectID = oProject.ProjectID;
oBasicDetail.ProjectReference = oProject.Reference.ToString();
}
else
{
oBasicDetail.ProjectID = -1;
oBasicDetail.ProjectReference = "NO_PROJECT";
}
To add to all the above I seem to have found that there is a general exception that is being thrown but it doesn't help me out much - if anyone can put some light on this it would be great:
Unhandled exception at 0x78bc7361 in SAGE_TESTING.exe: 0xC0000005: Access violation reading location 0xfeeefeee.
If your program is multi-threaded and the exception is thrown in one of the spawned threads, the Exception may not be caught depending on how you do exception handling in your program.
You can add a catch-all exception handler like this:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
// Your code here
}
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
Environment.Exit(1);
}
}
UPDATE
Based on the code you posted, here are some things to look at
Put a try/catch block around the code you posted.
Are you sure that oSplitData is not null?
In the following line, oProject will be null if oSplitData.Project is not of type SageDataObject190.Project. Test for null.
oProject = oSplitData.Project as SageDataObject190.Project;
You are probably dealing with so-called corrupted state exceptions. These exceptions corrupt the process in a way so it is usually more safe to kill the process since it is very difficult to impossible to recover from such an error, even if it would be only for running a short catch-clause. Examples are StackOverflowExceptions, OutOfMemoryExceptions or AccessViolationExceptions.
There is an extensive and generally interesting explanation on corrupted state exceptions in this article.
What is helpful on getting a hand on such exceptions is to use DebugDiag. With this tool from Microsoft (download on this page) you can define a crash rule which generates a crashdump for your failed process. You can easily open these dump files in Visual Studio, where you may find the source of the exception that lead to the failure. This is not guaranteed but it often helped me in the past to nail down some nasty errors.
Are you invoking non-managed C++ or other code?
I'd try something like
static void Main()
{
try
{
DoSomethingUseful() ;
}
catch ( Exception e )
{
// managed exceptions caught here
}
catch
{
// non-managed C++ or other code can throw non-exception objects
// they are caught here.
}
return ;
}
See Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?
Also C++ try, catch and throw statements at msdn: http://msdn.microsoft.com/en-us/library/6dekhbbc(v=vs.100).aspx
And MSIL opcode throw (0x7A) allows the throwing any object reference. C#, however, does not allow it.
But it looks like they improved things with .Net 2.0 and started wrapping oddball stuff in an RuntimeWrappedException.

What exception to throw to indicate child process freezed

Question 1 - practical
I run child process in my C# application using System.Diagnostics.Process. Like the following:
Process process = new Process();
// ... StartInfo initialization here
int timelimit_ms = 30000;
process.Start();
if (!process.WaitForExit(timelimit_ms))
{
// What exception to throw here?
throw new Excpetion(
"An executing method exceeded the time limit of " + timelimit_ms.ToString() + "ms");
}
I'm currently throwing System.ComponentModel.Win32Exception. But I don't sure it is the best choice. The child process is a simple command line utility. So the first question, what exception to throw in this situation?
Question 2 - thoretical
This is not the first time I ask myself about what exception to throw. And I don't know of a simple guidelines on how to pick a certain one. There are so much exceptions in C#, deeply inherited from one namespace to another. The second question, how to decide what exception to throw in a specific situation?
Practically, I'd throw a TimeoutException as it describes what is happening
Theoretically, if a quick google / read of the docs doesn't throw up an exception that already describes what is happening then you can just extend Exception to generate a WeirdThingThatHappensSometimesInMyApplication Exception.
But it depends who or what is going to "read" your exception. If your exception isn't exceptional then maybe you should do things differently :-)
how about a timeout exception?
I would think about throwing InvalidOperationException from the code.
As states MSDN, this exception is:
The exception that is thrown when a method call is invalid for the
object's current state.
So the caller of the function or consumer of the object that runs and waits for the process will be notified about the fact that execution of the function failed.
If you want to be detailed about declaration of the failure reason, you can express it
or in detailed message (if it's enough)
or create yuor own custom exception derived from InvalidOperationException and populate it with additional data you may need outside from the caller.

Problem with Environment.StackTrace

On a thread that is processing new data in the system, if the data is invalid I write a message in the event log, containing the Environment.StackTrace information.
Writing in the event log throws an exception with no text message
Message:
CallStack - at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at <my method that writes in the event log>
Any ideas why this happens?
EDIT: I am interested in what can cause the Environment.StackTrace to throw exception in general, so that i can understand what is happening in my case
#anchandra I don't know if you have figured this out since, as this is now 4 years old.
However I would like to add as I just stumbled upon this myself.
So, why does Environment.StackTrace throws an exception?
First the most uninteresting answer:
As you can see in the MSDN reference to the property, it can throw an ArgumentOutOfRangeException if "The requested stack trace information is out of range.", note also that the executing context must have System.Security.Permissions.EnvironmentPermission.
Now what stumped me for a second:
It does NOT throw an exception! Yes, that is what was happening to me, it actually returned me a Stack Trace that started listing the call to Environment.StackTrace like "at System.Environment.get_StackTrace()" then it showed all the other calling methods.
Because I was logging this into an audit log, if you look at it you assume there is an exception occurring at the last frame of the stack, but that's not true, I was just happening to request a Stack Trace at that point and stick it in my error log, very dumb once I realized this.
You need to capture the stacktrace before moving onto a separate thread.
Stacktrace will only show you the frames up to the root of the thread.

Categories

Resources