How to stop Visual Studio debugging so sql database changes not commit? - c#

I work with several code pages and Stored Procedures during day. I look for an easy way to stop visual studio while debugging, so database changes rollback. Since I work with several pages, i don't want to add code for this in my pages or for every SP I use. Is there a shortcut or a command i can use in immediate window?(I am open to other solutions - these are the ones came into my mind) If I can manually throw an exception(not written in code, in immediate window may be, it may work.)

I think the best thing is to use TransactionScope class for this.
Just wrap your db calls inside
using (TransactionScope scope = new TransactionScope())
{
// Invoke your database calls
scope.Complete(); // Put a break point here and stop the program when the break point is hit.
}

I usually kill the w3wp.exe process using Process Explorer. Alternatively, you can drag and drop the "yellow mark" in the debugger to a point after the commit so that the commit is skipped. I also sometimes set a variable to null and induce a crash that way.

If you want to throw an exception, you can do it using Immediate Window, after hitting breakpoint.
The problem is, you can not use in Immediate Window something like:
throw new ApplicationException("Forced exception");
But you can create the method, and then launch it from Immediate Window
public static void ForceAnException()
{
throw new ApplicationException("Forced exception");
}
In immediate window:
ForceAnException();
EDIT:
So maybe try this:
var throwEx = false;
if(throwEx) ForceAnException();
And change in immediate window throwEx to true, before condition is checked...it should work...

Related

breakpoints not hit once evaluation timed out

I quite often stumble about code that takes too much time for the debugger to evaluate yielding to the following annoying error:
Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
Usually we can ignore this by just stepping further, making the debugger-thread snyc to our process and then re-evaluate our statement.
However when I attach my source-code to a running, managed process, I´m unable to step any further. As soon as I get the mentioned error, no breakpoints are hit at all nor will "Break all" let me break the execution and see the currently executing statement.
The yellow line produces the error mentioned above. However no breakpoint is hit after continuing, neither by using F10 ("Step over") nor F5 ("Continue"). After this I´m completely unable to debug anything in my entire codebase.
Also when I try to break debugging to see what the process is currently doing no source-code is available nor any dissambly-information, as seen here:
I have a few methods that run one by one in a loop. To show the entire progress after every such method my BackGroundWorker is notified:
void RunTests()
{
foreach(var m in methods)
{
m.Invoke(...);
backgroundWorker1.ReportProgress(1);
}
}
private void InitializeComponent()
{
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.RunTests);
}
The behaviour occurs inside the currently invoked method. I suppose it´s because of the other thread which the BackGroundWorker uses in order to notify the progress to the UI (in my case a progressbar), but that´s just a guess.
Has anyone an explanation or even better a solution which doesn´t need to re-start the process (which as I noticed yields to the exact same behaviour btw.).
This is because the exception is un-handled and Visual Studio cannot move past that line without it being handled in some manner. It is by design.
Continuing in the Visual Studio debugger after an exception occurs

Windows Form Won't Display in Debug Mode

I recently upgraded to VS 2012. I have a set of coded UI tests that I've coded in VS 2010 and I'm trying to spin them up in VS 2012. I have a windows form that I'm displaying at the beginning of the test run by using the AssemblyInitialize attribute. I use this form to allow users to select from sets of values and those values are used to data feed the tests. Here's a copy of my code that displays the form:
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
ProcessUtility.TerminateAll();
if (!File.Exists(Directory.GetCurrentDirectory() + #"\RunInfo.ser"))
{
InitializeForm initForm = new InitializeForm();
initForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
initForm.ShowDialog();
}
}
So, here's my headache: the form displays just fine in Run mode. However, if I try to spin it up in Debug mode, it never displays. I've stepped through the code. It's loading all of the controls for the form with no errors. I make it to the 'initForm.ShowDialog()' line of code. It runs that line of code but then nothing happens. I don't receive any errors and the status in the lower left of the IDE is 'Ready'. It's almost as if the IDE thinks the form is displayed but it's not. I've double-checked the Task Manager and it's just not there. I've verified the build configuration is set to Debug. I've tried cleaning the solution and re-building. This code continues to work in VS 2010. Please tell me someone out there has ran into a similar problem because I'm out of ideas. I'm new to stackoverflow so let me know if there is anything else I can provide to better explain the issue. Thank you in advance for taking a look at it.
Not sure why this solution works, but I was able to solve this issue in VS2013 by setting the visible property on the form I was trying to display to true and then false before calling ShowDialog.
VB.Net example code
Dim form as Form = new Form
form.Visible = True
form.Visible = False
form.ShowDialog
I was able to get the form to display using the following code instead of ShowDialog. I still have no idea why ShowDialog wasn't working but this does the trick:
InitializeForm initForm = new InitializeForm();
initForm.Visible = true;
initForm.Focus();
Application.Run(initForm);
Most likely a exception is happening during the initialization, Go in to the Debug->Exceptions dropdown menu and be sure the checkbox thrown for Common Language Runtime Exceptions is checked, this will let your code break on the exception that is happening.
If you are still not catching the exception go to Debug->Option and Settings then uncheck the box for Enable Just My Code and check the box for Break when exceptions cross AppDomain or managed/native boundries
This may give you some "read herring" exceptions, as some .NET processes use exceptions for control of flow logic. So just be aware that the first exception you see may not be the cause of your problem.
I was experiencing the same thing while debugging an old code and resolved the situation by adding [STAThread] attribute on top of container method which contains form.ShowDialog();
For example:
[STAThread]
public void MessageBoxShow(string errorMessage)
{
using (frmError errorForm = new frmError(errorMessage))
{
errorForm.ShowDialog();
}
}
This has solved any hanging occured while hitting-continuing debug point.
Platform Windows 7 x64 enterprise edition and VS2008 (both has latest updates as of today).
Hope this helps.
Update 1: Please ignore using statement in example since I am using a custom form which inherits IDisposable in addition to Windows.Form and has custom disposition routines. Sorry if it has created any confusion.

Debugging Nunit tests in Visual Studio C# Express 2010

I've followed this advice to get debugging working for NUnit tests.
http://www.blackwasp.co.uk/NUnitCSharpExpress.aspx
However, i have several tests that do Assert.Throws<...>, which causes the debugger to break when the exception i'm testing for occurs, when really i want it to break if an exception occurs outside of those calls.
How can i get the debugger to ignore exceptions caused from within these kinds of methods?
EDIT: I've event tried the below, which doesn't work!
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
try
{
Assert.Throws<ArgumentNullException>(() => new CachedStreamingEnumerable<int>(null));
// This still throws and stops be being able to debug tests called after this one
}
catch
{
}
}
Here is what worked for me (although in Visual Studio Professional, not Express, but I guess that should not matter).
Bring up the "Exceptions" Dialog as suggested by Ninjapig.
Click on the Add... Button, to open the "New Exception" dialog.
Select "Common Language Runtime Exceptions" in the drop down box
In the Edit box enter "NUnit.Framework.AssertionException".
Click OK to close the "New Exception" dialog.
Back in the "Exceptions" dialog make sure that both checkboxes (Thrown and User-unhandled) are unchecked.
Now, the debugger should completely ignore a NUnit assertion failure (i.e. a thrown, caught or not, NUnit.Framework.AssertionException).
UPDATE: This will only prevent from breaking into the debugger, it cannot ignore the exception itself; i.e. it will not alter the actual program flow. Appart from changing or replacing or encapsulating the Assert-calls in try-catch blocks, I don't think there is anything that can achieve that (at least not automatically).
I'm uncertain if VS2010 Express has this option, but you can choose the exceptions to break on .
Go to the 'Debug' menu, then select 'Exceptions'
and from here you can select what exceptions to break on
I've ended up referencing nunit-gui-runner.dll and invoking it like
NUnit.Gui.AppEntry.Main(new string[] { Dll });
This brings up the NUnit gui. I can then run the specific test i'm interested in.
I had the same problem. Although your original approach (without the need for a try...catch block) works for most exception types, ArgumentNullException doesn't work. I fixed it like this:
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
bool isArgumentNullExceptionThrown = false;
try
{
new CachedStreamingEnumerable<int>(null);
}
catch (ArgumentNullException)
{
isArgumentNullExceptionThrown = true;
}
Assert.That(isArgumentNullExceptionThrown);
}
It's not as elegant, but it does seem to work.

"The debugger cannot continue running the process."

I've been messing with VS 2010 debugging settings, trying to get stepping into the .NET Framework working. Well, I can't get it to work. I've also tried the Reflector VS plugin and that was working at one point.
Then I randomly started getting this error:
This only happens when I have a breakpoint on a line that calls IEnumerable<T>.ToList(). If I try to step-over or step-into on that line where my breakpoint is set, I get this error dialog and my debugging session ends.
If I move the breakpoint to the line below, the debugger makes it past the ToList() call!
I've tried the following to no avail:
Removing the Reflector plugin.
Undoing my changes in the Tools > Options > Debugging window (unchecked the option to step into the .NET Framework; unchecked the source server option; checked the just my code option).
Unchecked Microsoft Source Server in the Tools > Options > Debugging > Symbols window.
Cleared the symbol cache.
What is going on?
Because this was the first place I came to when I searched for an answer, I'll add what I found out.
In my case, I had the debugger set up in the solution to start multiple projects. For some reason this setting was changed by Visual Studio so that no project was starting. Correcting the setting in the solution immediately solved the problem.
The problem was not difficult to solve, but the error message was more than a bit irritating.
I've just found this answer useful. All I did was change my start-up project to another, and back to normal.
My project probably lost this setting somewhere, and resetting it made it available again.
It was a ToString() override that make the debugger crash ! (After the evaluation the debugger will show you the result with the ToString() method). And if you get an exception in the ToString(), you will never catch an exception because you cannot code them on the debugger behaviour.
I've got this answer from msdn
I suffered from same problem....
I found one solution which heard uncommon....
The debugger cannot continue running the process.Process was terminated
While debugging your code step by step , you will find the line , from where error redirecting.
If you are using " ToString() " anywhere in that file ,please remove that .
Instead of the ,you can use Value / Text .
It works fine.
............
If you were not used ToString() any where in program , then reload project copy by removing completely.
I had the same problem. I traced it down to a class(step-by-step debugging) and finally to a property(commenting all the code, then step-by-step uncommenting).
this property returned a typed dataSet from a table.Dataset
private typedDataSet myDataSet
{
return this.DataSet as typedDataSet;
}
this was in a DataTable partial class.
After I removed this property everything went OK.
I ran into this issue with a code bug from copy/paste. Instead of get/setting the private member variable, I did a get/set on itself. When I referenced the property in other code the debugger terminated (2010):
public bool ProdToDeve
{
get { return ProdToDeve; } // <= missing underbar
set { ProdToDeve = value; }
}
private bool _ProdToDeve = false;
This message will also show up when you're trying to debug a Xamarin solution but you have a class library selected as the startup project instead of your application porject.
It occurred to me when I was doing the following:
throw new Exception(timeout.TotalSeconds + " second(s)");
That's because timeout.TotalSeconds.ToString() which indeed is an override method for an object of type double, was throwing a Parameter not valid exception.
Finally, for safety I ended up doing the following:
throw new Exception(System.Convert.ToString(timeout.TotalSeconds));
Well, typically, this is also the kind of error message you can get in a multi-threads context. In brief, it involves concurrency : make sure that your resource accesses are always secured.
In my case, I got this error message when I forgot to secure resource accesses at some places within my code. To solve this issue, I just had to decorate the critical sections with a lock instruction (on the concerned resource). I hope this will help those who are in this context.

Breakpoint not hit and code not executed?

I'm facing an issue which I can't seem to wrap my head around.
private void IndexEntityType(Type targetType, bool onlyNew)
{
Logger.Debug("generating index for {0}", targetType);
using (var wrapper = SessionWrapper.For(targetType, true))
{
var session = wrapper.Session;
session.FlushMode = FlushMode.Never;
session.CacheMode = CacheMode.Ignore;
var entities = GetEntities(targetType, onlyNew, session);
Logger.Debug("Indexing {0} entities", entities.Count);
// Create a Full Text session.
using (var fullTextSession = Search.CreateFullTextSession(session))
using (var transaction = fullTextSession.BeginTransaction())
{
fullTextSession.CacheMode = CacheMode.Ignore;
foreach (var entity in entities)
{
fullTextSession.Index(entity);
}
try
{
transaction.Commit();
}
catch (Exception ex)
{
Logger.Error("could not commit fulltext session transaction", ex);
}
}
Logger.Debug("generated index for {0}", targetType);
}
ReQueueTimers(onlyNew);
}
I'm trying to debug this and have set breakpoints at the first row (Logger.Debug) and the last row (ReQueueTimers).
However, when stepping through the code, the last call (ReQueueTimers(onlyNew)) is never invoked, nor hitting the breakpoint. How can that be? Does the compiler "remove it when optimizing" somehow?
Does anyone have any hint on what might trigger this behavior?
EDIT: This is run in multiple threads if that might have anything to do with it.
It could be that your code is throwing an exception - if anything other than the transaction.Commit() throws an exception, the ReQueueTimers call won't be made. You could prove this by getting Visual Studio to break on all CLR exceptions - in the Debug menu, select "Exceptions", and check the "Thrown" box on the "Common Language Runtime Exceptions" row. Then start debugging again.
On the other hand, I have sometimes had Visual Studio just give up stepping through code halfway through debugging a method. Maybe this is the cause - it might have something to do with multiple threads. If you remove the first breakpoint and leave the one on the ReQueueTimers call, does this make any difference?
As a little addition to what Graham said:
If you run on multiple threads and an exception is thrown on that thread and is not caught, the thread is aborted.
I had the very same issue from 2 days and banged my head dead until... I found this somewhere on the net:
Make sure that your target code actually builds when you build your solution/project. To do that, go to Build->Configuration Manager and make sure the corresponding project is checked (In the rightmost column).
Mind you, for some misterious reason that only Gates knows, the box was unchecked!

Categories

Resources