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!
Related
Our Application is moving some files it requires to run during startup.
The application takes care (on shutdown) to properly stop every process using this files.
However, if the application crashes / or you just hit "stop" in VS on Debugging - some executables might still be running.
So, if you quickly restart the application, it might happen, that the copy-attempt is failing, due to the file is still in use.
For such a case, we just ignore the failed copy attempt - or more exactly: the failed deletion attempt which should make sure, that the latest version is available:
foreach(String entry in contents)
{
if (System.IO.File.Exists(entry))
{
try
{
System.IO.File.Delete(entry);
}catch (Exception e)
{
//ignore during this startup.
}
}
}
Now, this works perfectly fine, as there is a version of the file available for usage and the production version just ignores the exception.
The annoying Problem is, that the Debugger "breaks" everytime, this error happens.
We don't want to generally "ignore" any System.IO.IOException thrown while debugging.
We tried to annotate the method in Question with [System.Diagnostics.DebuggerStepThrough()] which works, but causes the exception to be catched at the callers position.
So, is there a way to ignore "some" exceptions raised at a certain line of code, even if general "breaking" for that kind is enabled?
Some #if (DEBUG)-Directives which will avoid the exception to be catched at this particular line of code?
Something like:
foreach(String entry in contents)
{
if (System.IO.File.Exists(entry))
{
try
{
#if (DEBUG:NoThrow)
System.IO.File.Delete(entry);
#endif
}catch (Exception e)
{
//ignore during this startup.
}
}
}
I'm still interested in an answer, cause it has "many" usecases.
For the time beeing, we used the following "workaround": Check, if the file has been accessed withing 3 minutes - then don't attempt to delete it.
(For DEBUG-Mode!)
Remember, the actual issue is only about the "debugger", not production, where Exceptions can be caught (and ignored) easily for a certain line of code.
We just want to avoid "Debugger-Breaks" kicking in if the exception can savely be ignored AT THIS line of code.
foreach (String entry in contents)
{
if (System.IO.File.Exists(entry))
{
try {
#if (DEBUG)
FileInfo fi = new FileInfo(entry);
if (fi.LastAccessTime < DateTime.Now.AddMinutes(-3))
{
#endif
System.IO.File.Delete(entry);
#if (DEBUG)
}
#endif
}
catch (Exception e)
{
//ignore
}
}
}
This is NOT a solution, it's a workaround, reducing the Debugger-Breaks at this line of code by about 99%, in case you just "Stop" Debuggin within Visual Studio!
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
I'm developing C# application for windows phone 8.1 (Silverlight). Lately I've came across the problem connected to application falling asleep and storyboards.
The construction goes as follows:
class X : DependencyObject
{
public static readonly DependencyProperty vProperty =
DependencyProperty.Register("v", typeof(double), typeof(X), new PropertyMetadata(0.0));
public double v
{
get
{
return (double)GetValue(vProperty);
}
set
{
SetValue(vProperty, value);
}
}
private Storyboard _storyboard;
void Prepare()
{
_storyboard = new Storyboard();
var animation= new DoubleAnimation
{
From = 0,
To = 1,
BeginTime = 0,
Duration = 0,
};
_storyboard.Children.Add(animation);
Storyboard.SetTarget(animation, this);
Storyboard.SetTargetProperty(animation, vProperty);
}
void Go()
{
_storyboard.Begin();
}
}
There is a NullReferenceException thrown from inside of _storyboard.Begin() if application is placed in background between "Prepare" and "Go" (about 10% reproduction rate). Of course it ends up with crash.
I was not able to determine problem source and as I need quickfix for that I've decided to just catch this NullRefereneceException in this rare scenario. This is where real question starts. I've changed "Go" implementation to:
public void Go()
{
Debug.WriteLine("BreakPoint 1");
try
{
_storyboard.Begin();
}
catch (NullReferenceException)
{
Debug.WriteLine("BreakPoint 2");
}
}
Afterwards the crash is not reproducible at all, but the problem is that "BreakPoint 2" is never hit (no printout in Output either). "BreakPoint 1" is normally hit and printed as well. Changing NullReferenceException to other Exception type (not parent type ofc) causes crash to reappear.
So... What's going on here? Is this crash cached or not? What kind of weird behavior is that? Is it safe to assume that it will work as expected?
Additional question: Maybe you know why the original code crashes in the first place?
EDIT:
End of stack trace of internalException of TargetInvocationExceptions looks as follows:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.Storyboard_Begin(Storyboard storyboard)
at System.Windows.Media.Animation.Storyboard.Begin()
at X.Go()
I know that you've said that you've tried to use parent types for NullReferenceException, but please try the following without running in the debugger:
public void Go()
{
Debug.WriteLine("BreakPoint 1");
try
{
_storyboard.Begin();
}
catch (Exception)
{
Debug.WriteLine("BreakPoint 2");
System.Diagnostics.Debugger.Break();
}
}
My suspicion is that the catch is not firing because you are running from within the debugger. Also try System.Diagnostics.Debugger.Launch(); in the catch if .Break(); does not work. And finally also try throw; in the catch if .Launch(); does not work.
If the debugger attempts to launch in either case, then you have another clue.
UPDATE:
I can't give you all of the reasons why this might happen as it may not be possible to determine precisely what is causing it in your situation.
I've seen behavior like this due to use of multithreading. Multithreading can behave differently when running with a debugger attached then without. Timing issues and race conditions can prevent exceptions from being thrown while in the debugger that otherwise may occur frequently when there is no debugger attached.
I've also encountered instances where System.Diagnostics.Debugger.IsAttached was used in third party code and even my team's code which caused the application to behave differently based on if statements using this check.
And lastly, I've had times where I could not come up with a specific reason why the behavior was occurring. I've learned to use the System.Diagnostics.Debugger.Break() method whenever I see behavior exhibited differently depending on whether a debugger is attached or not. Sometimes it really is just a gut feeling.
I'm currently learning after a book about how to convert xaml code into objects during runtime.
I have the following code:
try
{
ctrl = XamlReader.Load(xaml) as UserControl;
}
catch (Exception exc)
{
OnXamlResult(new XamlCruncherEventArgs(exc.Message)); return;
}
The code is not mine, I took it from the book.
The problem is that try-catch does not work properly, or at least as I know till now.
During debugging the program stops when it reaches the line :
ctrl = XamlReader.Load(xaml) as UserControl;
without catching the exception.
What am I doing wrong or how can I solve this problem?
"xaml" is a string. It is taken from a textbox and if the xaml is correctly typed by the user the program should convert the xaml code into object otherwise it should display the corresponding error.
About how the program reacts, i can say that debug stops(it returns me to visual studio pointing the error) and it is not behaving like going into a infinite cycle.
It's probably the debugger breaking as the exception occurs. Stick a breakpoint inside the catch and F5 to continue, it should carry on and hit your breakpoint.
And by "breaking", I don't mean it fails, I mean it pauses execution of the app on the offending line of the exception, so it's a Good Thing in this instance.
If you are using Visual Studio, you can enable/disable this "break on exception" behaviour:
Debug -> Exceptions... (Ctrl + Alt + E)
Common Language Runtime Exceptions, check the boxes to the right as needed.
As for the exception itself, unless it's there specifically to show exceptions, it is likely having trouble loading the provided XAML string.
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.