What happens before Main()? - c#

The question arrived when I began having some strange symptoms on my computer.
Here's what's happening: I have a WinForms application written in C# (.Net 2.0). If I run it from Visual Studio 2005 (either Debug or Release), everything is just fine. If I try to run it from Windows (run the exact same executable generated by the debug process in VS 2005) I get a
"System.TypeInitializationException" on the Program class.
I have added debug log messages ( File.AppentAllText() ) in a static constructor and in Main(). The log messages in the static constructor get written, but the ones in Main() don't. So, clearly, something happens after the static constructor has finished and before the call to Main() is issued.
Any suggestions on where to look next? What happens before the Main() method is called?
Thanks everybody.
EDIT: I think that I should point out that the application runs just fine on other computers. :)

Check out your code in static constructors. TypeInitializationException usually happens when there is an exception in static constructor, so type cannot be initialized. Code can work fine in IDE because it was started from different user with different security privileges.
As a side note - I would avoid using of static constructors when it is possible.

Based on the exception it sounds like either a static constructor or the initialization of a static field is throwing an unhanded exception here. Given that the Main method is apparently not executing it's likely happening for a type which is referenced in the Main method and hence trying to be initialized by the CLR.
There are a couple of ways to track down what is causing this. None of them are pretty
Inspect the Main method of the program and analyze every Type in play and then analyze their static constructors to see which could be throwing
Systematically comment out lines in the Main method to discover which one is causing the exception
Or alternatively when you run the program it should popup an error dialog. At that point attach to the process and dig into the exception to see which type is causing the problem.

You will also get a System.TypeInitializationException when you have a error in a *.config file. Check the innerException for the LineNumber in that case.

Related

My Application crashes if there is an unhandled exception in my Class Library?

What I am doing is basicly creating a .DLL. I have a lots of stuff going inside these DLL-s, and it happens that I miss a scenario and something unexpected happens. I am working on it on unit tests, but I want to be hundred percent sure, that my WinForms app will never crash.
What I have:
One Solution with two projects:
ProjectDLL (Class Library)
ProjectWinForms (Windows Forms Application [.NET Framework])
What I did:
In ProjectWinForms I added this to ApplicationEvents.vb
Private Sub MyApplication_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs) Handles Me.UnhandledException
Bugsplat_Lander.ExeptionToShow = e.Exception
Bugsplat_Lander.Show()
Bugsplat_Lander.BringToFront()
e.ExitApplication = False
End Sub
This works fine as long as the exception occurs in my ProjectWinForms project. However, if I build a Release version, move it to another computer, and create an exception; my application will simply close, and write the error in Windows Events.
What I want to achive:
Basicly the nicest thing would be to open up this form even if the exception happens in my ProjectDLL code, without quiting the application.
I am a sure that I am the one doing something wrong, I just can't figure out what.
At first the golden rule is: If your code creates an exception, it has to be handled otherwise your application runs in a dirty state.
For your problem take a look to Application.SetUnhandledExceptionMode Method. Maybe this could help you

Visual studio, debugging randomly throws SEHException unhandled exception in mscorlib.dll with no stackTrace

I've got a C# Windows Forms application that (outside of debug mode) works perfectly. When I run it in debug mode, each action I take has a random chance of crashing the application (like clicking a button, or closing the main form). There is a lot of async code running in the background, but the app crashes even when no tasks seem to be running (the _formClosing method is an entirely Synchronous method). Notably, the first thing most button clicks in my app do is change the visibile and enabled properties of some buttons, and then will start writing messages to the log - the app crashes before any logs get written (using NLog)
The error being thrown is:
System.Runtime.InteropServices.SEHException
HResult=0x80004005
Message=External component has thrown an exception.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
With output
An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in mscorlib.dll
and trying to resume the application just ends the debugging session.
The fact that it's not any one specific section of code or event that's triggering the crash, and that the code never crashes outside of debug mode leads me to believe this might be a Visual Studio issue. Are there any settings I can configure within Visual studio to make this crash less prone to occurring? or if not, is there any way to get more information than 'cannot Evaluate the stackTrace'?
Other Information that may or may not be relevant, the memory and CPU usage are both very low at the time of crashing (40MB or so and about 5% CPU utilisation). I'm running the latest Visual Studio Community 2019. The app runs on .Net Framework 4.8. My OS is a local VM running windows 10 enterprise. I also don't think I'm running any Trusteer applications.
My code is also all heavily Try Catched, especially around the button clicks.
Thanks for any help, let me know if I'm missing any relevant information
Edit: I've discovered the line that's causing the issue, commenting out this line causes the app to run fine, completely error free
var ignore = currentJob.jobConfig.ToObject(t); //jobConfig is a JObject
The cast works fine, but by doing the cast, somehow the exception mentioned above and shown below is triggered
Edit #2: Repairing, updating and reinstalling visual studios has not changed the issue, the app still seems to work fine 10-40% of the time, and crash the rest of the time
I found a solution to my problem, by adding 'return;' statements everywhere and removing them one by one (removing large sections of my code). I eventually found the line that was causing problems. It turns out, if you serialise and then deserialise a CancellationToken, visual studio's debug session becomes prone to randomly crashing when, presumably, it tries to do a certain operation on the object you have deserialised to. The solution was just to make the cancellation token either private, or add [JsonIgnore]
Code to reproduce the problem: (run the void method, and then try closing the window)
private void BreakVS()
{
ClassWithCancellationToken someClass = new ClassWithCancellationToken();
someClass.ts = new CancellationToken();
var json = JsonConvert.SerializeObject(someClass);
JObject jObject = JObject.Parse(json);
var test = jObject.ToObject(typeof(ClassWithCancellationToken));
}
public class ClassWithCancellationToken
{
public CancellationToken ts; //change to private to
}
The answer to my original question then, is to start with Jeroan's solution to try debugging on a different device, if the code still breaks on said device then try what worked for me (hack and slash your code until you find what's breaking it) - or a more sophisticated approach to debugging your code more thoroughly. If your code works on another device, then try Micheal's approach to update/repair/reinstall your Visual studios install
Of course, the one thing I still don't know how to do, is to locate the faulty code without spending an hour removing sections of my code until I find the cause.

Catching an Unhandled Exception Raised by an Unmanaged Sub-Process

Using C#'s System.Diagnostics.Process object, I start an unmanaged exe, that later starts yet another unmanaged exe.
The 2nd exe is causing an unhandled-exception that I'd like my application to ignore, but can't seem to.
I'm using a try/catch statement when I start the first process, but it doesn't seem to catch the exception raised by the 2nd process. When the exception occurs, the just-in-time debugger notifies me and halts my application until I manually click "yes" I want to debug or "no". Then my application proceeds.
The JIT debugger doesn't have source code for the 2ndprocess.exe that is throwing the exception. So, it doesn't tell me what the exception is. I don't really care what the exception is, I just want to know how to catch it and ignore it so my application doesn't get halted by it. By the time the exception occurs, the work is done anyway.
Can anyone offer some insight?
You should be properly handling the exception in the second executable. Your main program won't catch the exception because it isn't throwing one, it is executing something that is.
Edit:
Do you have access to the source of the second process (the one throwing the exception)? Your application shouldn't ever just crash. If the exceptional case gets handled correctly in the second process, you won't have this problem in your primary application.
Edit2:
Since you have access to the source (open source) I recommend you fix the bug. This will help you in two ways:
1) Your program will finally work.
2) You can say you contributed to an open source project.
And, as a special bonus, you get to help out a project you use frequently. Win/Win
Since you are using process.start to actually launch the application, the application creates a separate application domain. Capturing the exception from that application is not something that I believe will be possible, since more than likely the JIT dialog is coming up due to that failed process.
Although not a solution you could stop the dialog if needed, but that has issues of its own.

C# memory error on program exit

I have a rather simple C# program (no UI, just command line) that uses a 3rd party library (Abbyy's Finereader 8.1) to do some work and then exits.
Simple enough and works quite well. Recently however we've started getting the following error from the program:
Application Error : The instruction at
"0x2c0de46b" referenced memory at
"0x0732aa84".
A little digging shows that this is happening at the end of the C# code. Basically the last two lines are:
Console.WriteLine(message);
return statusCode;
The final console message is written and the output from the program is fine. Indeed, if it wasn't for the fact that this error keeps the program from fully terminating I could work around it.
We're running two scripts that invoke this program each on two machines. This happens at random (as far as I can tell) but usually at least one of (the 4 scripts) hits this each day. I thought that perhaps some kind of weirdness was happening for concurrent runs, but testing eliminated that.
Any thoughts on possible causes would be most welcome as I've run out of ideas.
Also if anyone knows of a way to have the program terminate when this happens, that would be useful.
"Application Error : The instruction at "0x2c0de46b" referenced memory at "0x0732aa84"."
This error implies memory corruption somewhere in your code, without the full code i cannot say more than this.
The place where the exception is risen is not important in this case of error. Try to take a look at your code, especially the code that calls the library.
Well... Troubleshooting dictates that I ask what changed, but I reckon you thought about that yourself. What version of the .NET framework are you using? What OS(es) does this problem occur on?
I belief that this exception is coming from some cleanup that the 3rd party library does. Did you contact their support? Can you try to explicitly unload the library and see if the error still occurs then?
Or... did you try adding an handler for unhandled exceptions? Might be worth a try...
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(
OnUnhandledException);
//some code here....
}
/// <summary>
/// Occurs when you have an unhandled exception
/// </summary>
public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//here's how you get the exception
Exception exception = (Exception)e.ExceptionObject;
//bail out in a tidy way and perform your logging
}
(example code by DoctaJonez)
Just throwing some things out there, since there doesn't seem to be a definite answer (yet).

Running C++ code through NUnit

I have tried to use NUnit to test C# code the is already connected to C++ code (without the NUnit the application work perfectly).
In my test I run the main function through AppDomain.CurrentDomain.ExecuteAssembly(..), However when the C# code tries to "communicate" with the C++ it throws an exception and the test crashes. The exception is System.Reflection.TargetInvocationException if anyone has and idea why its happen it will be very very helpful... Thanks, Naama
Your suspicions are correct it is being through during the constructor, the constructor in c# is trying to create an object (it is already wrapped and work perfect when the application is running normally) that is written in c++ and in c++ in the constructor of the object the exception is thrown.
However the application is very complex but if it necessary for clarification I will write a demo application that symbol the real one.
It is likely that an exception is being thrown in your C++ code, in the constructor of the class. Check to make sure you're handling exceptions properly and that you're giving the proper information to the constructor so exceptions aren't thrown.

Categories