c# force debug mode programmatically - c#

Nevermind why one might want to do this, I'm just curious to know if it can be done.
Here's my code that doesn't work:
if (!Debugger.IsAttached)
{
try
{
Debugger.Launch();
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
}
catch (System.Security.SecurityException e)
{
Console.WriteLine("exception " + e.Message);
}
}
Basically I was curious to know how to use the Debugger.Launch() method.

Debugger.Launch will launch a debugger or will do nothing is one is already attached. I believe It's not a breakpoint. Debugger.Break() will actually break.
Calling Debugger.Launch() may do different things depending on the machine, for example if Visual Studio is installed or not, etc.
See also a related tech article: How to: Launch the Debugger Automatically

It will launch and attaches a debugger to the process.
For sure do not use it in production . I think that possible use
can be in local machine when error occured and you want automatically run debug.

I think you're misunderstanding what Debugger.Launch() does. It functions like a hard-coded breakpoint.
When your program hits Debugger.Launch(), the Just-In-Time-Debugging window will show (assuming you have Visual Studio installed on the machine. At that point, your program is stopped - it doesn't keep running.
If you choose an instance of VS, it will be launched, and will be stopped on the line with Debugger.Launch(), as if you hit a breakpoint there.
So there is really no reason for the while() loop. You could just call Debugger.Launch() whenever you want to stop the program to look at something.
But the utility of Debugger.Launch() is questionable. You can much more easily use breakpoints, and with breakpoints there is no danger of accidentally leaving it in the finished product.

Related

Visual Studio 2017 Breaks on System.InvalidOperationException Even Though It Is Both Handled AND Unchecked In Exception Settings [duplicate]

Visual Studio 2017 is (kind of suddenly) breaking on all exceptions. That means, if I deactivate them in the exceptions settings (pressing CTRL + ALT + E while debugging), the debugger still breaks on them. I don't know wether this is just a bug of VS I can't change and therefore have to live with, or wether there is a simple solution for it.
This is the exception settings window:
and this the exception VS breaks on:
By the way, I also tried that beautiful minus (nothing happens if I press it) or adding a impossible condition (VS still broke on the exception).
I also tested other exceptions (by simply throwing them), which I deactivated before, and they get thrown as well and I tested the same issue in other projects, where it appeared as well:
I actually even put the whole stuff into a try catch statement but VS still breaks:
InitializeComponent ();
try
{
var t = new Thread (() =>
{
while (!IsHandleCreated) {} //It breaks here (similiar to the screenshots)
while (true)
Invoke (new Action (() => Size = new Size ()));
});
while (true)
{
t.Start ();
Thread.Sleep (100);
t.Abort ();
}
}
catch (ThreadAbortException) { }
It doesn't appear in other IDEs (like Rider) on my PC and doesn't occurr on other PCs in VS. It didn't always occurr on my PC, it just started recently and only in debugging mode. And if I continue the execution (with F5) it just continues normally.
EDIT As I put the try catch inside the thread it behaved a little bit different (I'm sorry for putting pictures in here, but I think they're more expressive in that case):
Can anybody explain this behaviour?
EDIT It seems to be normal for ThreadAbortExceptions to break again at the end of a catch statement. However, VS still shouldn't break on this exception at all.
I was having a similar problem.
I fixed it by unchecking "Break when exceptions cross AppDomain or managed/native boundaries" in Tools > Options > Debugging > General
I fixed it by unchecking Enable Just My Code in Tools > Options > Debugging > General
I can't confirm whether this happens with other project types, but it happens to me consistently with (Visual Studio Tools for Python) VSTP.
Although it is less than satisfactory, it can at least silence the exceptions and allow you to continue working in peace until a better solution surfaces. In my case, it was nearly impossible to debug my code, since StopIteration breaks during every iteration.
Select Debug > Windows > Exception Settings or press Ctrl-Alt-E. Y
Right click anywhere on the Window and select Show Columns > Additional Actions. You will have an "Additional Actions" column appear if it doesn't already.
Right click on a specific exception you want to silence or click the top level checkbox to select an entire category of exceptions, i.e. Python Exceptions. Click Continue When Unhandled in User Code.
Repeat for each additional exception or category of exceptions.
I know it's a little late for this, but ThreadAbortException is different from all other exceptions, and requires some special handling, otherwise it is automatically re-thrown at the end of all catch blocks if you don't actually handle it the way it's supposed to be handled.

Debugging when my code is started by external program with Process.Start()

Suppose I have a C# WinForms application and it is started by external program simply by using Process.Start(MyModule.exe).
I've tried to debug my code by using My project properties->Debug->Start Action->Start external program (with setting proper Working directory of course).
My enother attempt was Debug->Attach to process
UPDATE: Both my module and external program use one resource. So external program releases it, then calls Process.Start(), waits for my process to exit ans then capture the resource again. So I can't attach when your program is already running.
Both of them failed - breakpoint in Program.cs was never hit.
So, how can I debug my code in such circumstances?
There are two ways I know of to easily solve this problem. The first way is have your program request a debugger attach to it as the first thing it does in Main via Debugger.Launch()
public static void Main(string[] args)
{
Debugger.Launch();
//Rest of your code here
}
This will make a dialog like the following show up
This will allow you to attach to your running visual studio or start a new instance.
The other way to solve this when you can't use the previous method (for example I don't think it works inside services) is put a loop at the start of your code that will loop forever until a debugger is attached, this gives you enough time to do the "Attach to process" method you tried earlier without letting the program progress.
public static void Main(string[] args)
{
while(!Debugger.IsAttached)
{
Thread.Sleep(1000); //Sleep 1 second and then check again.
}
//Rest of your code here
}
There are two different methods you can use System.Diagnostics.Debugger.Launch() or System.Diagnostics.Debugger.Break() The first will attach a debugger (letting you choose which) and then do nothing. In the case where one is already attached nothing will happen.
The latter will do exactly as Launch in the case no debugger is attached and will serve as a break point if one is attached.
So simply write System.Diagnostics.Debugger.Break(); where you want your break point to be.
That will result in a dialog asking you how you wish to debug the program (which of course also means your should remove the line when your done debugging)
In the dialog choose the appropriate instance of VS (or create a new) and the simply continue debugging as usual

Exception before the program starts c#

I have a project that runs fine, everything loads, runs and completes, this is only when i set visual studio in Debug mode, when i switch to Release, all hell breaks loose.
The program does not even enter the main method, becouse when i put a console.Readline in there, the program still crashes. also i have put my whole program in a try catch block but becouse it doesnt even enter the main it will not catch anything. i have tried to seach for it on the internet but could find nothing usefull. What is going on here?
This pops up right after i press F5:
http://i.stack.imgur.com/Vb3Xu.png
http://i.stack.imgur.com/msCCI.png
The exception window you see is somthing that is thrown inside my program, but is does not even get there?
Right click on the soltuion and select properties.
Click on Configuration Properties and then Configuration manager
In the Release section, make sure your projects are set to build (ticked) (sorry about the ugly picture)

Program works on dev machine, but won't start on test machine

I've been writing this program for a while now, and I'm finally ready to start testing it. It works 100% on my dev machine, but I wanted to try it on a machine it's never run on. So, I get my program over to a test computer. When I double-click the exe, nothing happened. I opened up task manager, and tried again. I saw the process start, but after about 5 seconds, it disappeared. No errors, no exceptions, no nothing. How would I go about trying to figure out what is going wrong? I'm still fairly new, and I've never had this happen. Thanks for any and all help!
EDIT
Sorry for not mentioning before. This is a winforms application.
EDIT 2
So, turned out what was going on is that I was trying to a dll meant for 64-bit OS into a 32-bit OS. In Windows XP, this threw a BadImageFormatException. However, in Windows 7, as I stated, it threw no exception at all.
This is a pickle, no doubt about it. I've had to debug this type of thing before.
The first bit of useful information is that no exception is being thrown out. This tells me that somewhere in your actual code is the key to solving the problem. You are either trapping an exception and closing silently, or your code is hitting what it considers to be a "normal" exit condition and is closing in what it would consider the normal way.
To figure out where and why it's exiting, I would add debug logging at key points in your application, and attach a listener to the Debug/Trace listener collection that writes out to a file. "Key points" are places where the application is supposed to exit (or the main form of the window is supposed to close), and within any "catch" block or error event handler. Run this new version on the test computer and see what it gives you. That should tell you the basic flow of the program behind the scenes, and through what mechanism it's shutting down.
If you're running a console application, it is possible that it runs and then closes itself.
Trying opening a command prompt, and then executing the application from there.
If your program has output, then you would see it in that command window.
Have you checked the application event log?
Do you have the necessary version(s) of .Net installed?
Perhaps you should put more exception handling with calls to MessageBox.Show("I failed here") through out your application.

Process.WaitForExit not triggering with __debugbreak

I'm trying to write a program to test student code against a good implementation. I have a C++ console app that will run one test at a time determined by the command line args and a C# .net forms app that calls the c++ app once for each test. The goal is to be able to detect not just pass/fail for each test, but also "infinite" (>5secs) loop and exceptions (their code dying for whatever reason).
The problem is that not all errors kill the C++ app. If they corrupt the heap the system calls __debugbreak which pops up a window saying Debug Error! HEAP CORRUPTION DETECTED... My C# app is using Process.WaitForExit(5000) to wait, but this error doesn't count as an exit, so I see a timeout.
So my question is, how can I either get the C# app to detect that this is an error OR how can I get the C++ app to die when this error occurs rather than giving a dialog box and asking if I want to debug?
Edit:
Here's the error that pops up: Debug Error
Here's the normal application failed dialog that pops up if I press retry in the previous dialog: Windows Error. The debug option goes away if you turn off the JIT debugger.
You should turn of JIT debugging, this page has instructions for how to turn it on or off.
Edit You can also use the _CrtSetReportMode and _CrtSetReportFile functions inside the C++ program to change the behaviour of the debug asserts (in particular, you can use _CRTDBG_MODE_FILE to write the contents of the message to a file instead of popping up a dialog.
If you're compiling the program as part of your tests, then you can just add your own .cpp file which includes a global class that does the work in it's constructor. Something like this:
// AssertModify.cpp
class AssertModify
{
public:
AssertModify()
{
::_CrtSetReportMode(...);
::_CrtSetReportFile(...);
}
};
AssertModify am;
This'll cause the code to run before main() is entered which should catch all possible cases (unless the student overrides your value themselves, but you can add a check for any calls to _CrtSetReportMode in their submitted code before you compile it)
I think you need to compile the C++ app in "release" mode. You're probably running "debug" builds which include asserts. Those asserts pop up MessageBoxes which is what you're seeing.
Since you want to catch the assertion failures, you can either modify the code when compiling it (as codeka suggests) or run the programs under a debugger. It's not that hard to make a C# app into a debugger using Mike Stall's wrapper, but it isn't exactly the easiest solution.

Categories

Resources