I'm getting some extremely weird behavior. An object appears to be null and not null at the same time, and a statement is getting skipped. I'm probably being an idiot, but if it's my fault I don't see it. I'm building using Visual Studio 2008 on a Windows 7 SP1 OS.
public void ReadTrendData(OpcDriver opcDriver)
{
if (opcDriver != null)
{
int a = 1;
}
if (opcDriver == null)
{
Exception ex = new Exception("Null OPC driver received by ReadTrendData()");
throw ex;
}
The opcDriver object is successfully created and passed in to this method. When I step through, the "int a = 1" statement is executed. Then, in the next if block, execution gets to the "throw ex" statement without executing the line above that creates the ex object. So, ex is null and throwing null gives me an access violation exception.
Do you have any idea what could be happening here?
A couple of members of the OpcDriver class are instances of classes from a 15-year-old ungauranteed, unsupported sample library that uses COM to interface with an OPC (OLE for Process Control) program. The only thing I can think of is that somewhere in the bowels of that library something grotesque is happening, but I can't think how this can be possible.
Thank you.
You should try on newer visual studio build. I got almost the same problem on 2008 and 2012 versions. It's a visual studio compile time bug. You should check your build option, if you selected "release" mode you should check back to debug and try again.
To sum up, it probably the problem's root is wrong operator overloading (== and/or !=). The test
if (Object.ReferenceEquals(opcDriver, null))
works as expected.
Related
I am working on a VSTO Word Add-in project. I was initially using Visual Studio Community 2017 version. I then upgraded to the 2019 version and migrated my Word VSTO Add-in project accordingly. Then I started noticing a strange occurrence suddenly while executing codes.
Some codes that have been surrounded with a try-catch block so that expected exceptions can be purposely ignored suddenly begins to throw exception and break the code even with the try block in place. This has never happened with the 2017 version. The catch portion of the code that is meant to catch the exception doesn't get executed!
The code is statement that tries to get a returned string from an object after the object calls a particular method. The calling objects can sometimes be inevitably null and all that the design will want to do when such is encountered is to ignore and move to the next step which perform actions that depends on whether a string was gotten from the try-catch block or not. I need someone to help me explain this please.
The code is as shown below:
string style = null;
try
{
style = ((Style)paragraphs[i].Range.get_Style()).NameLocal;
}
catch (Exception ex) {}
if(style != null)
{
//do something
}
else
{
//do something
}
Given this gem of code:
class Program
{
private static bool IsAdmin = true;
static void Main(string[] args)
{
if (!IsAdmin)
{
throw new Exception();
}
try
{
var x = 2342342;
var y = 123132;
}
catch (Exception)
{
throw;
}
}
}
Given the this.IsAdmin yields true - I would expect the debugger to not enter that if statement. In reality it does - and it steps over the throw but does not actually throw!
Now this only happens when you have an exception inside an if statement followed by a try/catch block, on Visual Studio 2013, targeting .NET Framework 4, 64 bit, "Prefer 32 bit" unchecked.
I have confirmed this oddity with colleagues on different machines. Step though the following code and the debugger will seem to step into the if branch, but no exception is thrown:
I am in debug mode, I have tried compiling and cleaning the project multiple times.
Can anyone explain why this is happening?
This is a known problem caused by the x64 jitter, it occasionally generates bad debug line number info. It can fumble when a statement causes extra NOPs instructions to be generated, intended to align code. The first NOP becomes the line number, instead of the instruction after the NOPs. This bytes in a few places, like a throw statement after a simple if() test and usage of the ?? operator with simple scalar operands. These alignment NOPs are also the reason why it is so dangerous to abort threads, described in this post.
Simplest workaround is Project + Properties, Build tab, tick the "Prefer 32-bit" option if available, set the Platform target to x86 otherwise. Note how nothing actually goes wrong, while the debugger suggests that the throw statement is going to be executed your program doesn't actually throw an exception.
It is being worked on, the x64 jitter was drastically rewritten, a project named RyuJIT. It will ship in VS2015, currently in Preview.
Check out this link. It's a known bug in some versions of visual studio and the .NET framework version. It's completely harmless and something you will just have to live with.
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.
This application has a WCF web service that is called by a WinForms app. The WinForms app has a class WCFCache to manage data from the service. There is a section like this in that class to manage an optional custom configuration section that a subset of the machines have:
private bool? m_HasCustomConfiguration = null;
public bool HasCustomConfiguration
{
get
{
if (m_HasCustomConfiguration == null)
m_HasCustomConfiguration = (CustomConfiguration != null);
return (bool)m_HasCustomConfiguration;
}
}
private WCFService.CustomConfiguration m_CustomConfiguration = null;
public WCFService.CustomConfiguration CustomConfiguration
{
get
{
if (m_CustomConfiguration == null)
{
if (m_HasCustomConfiguration.HasValue
&& !m_HasCustomConfiguration.Value)
return null;
try
{
using (WCFService.WCFServiceClient wcf = new WCFService.WCFServiceClient())
{
m_CustomConfiguration =
wcf.GetCustomConfiguration(Machine.ProcessID);
// Above method returns null if no record exists.
m_HasCustomConfiguration = (m_CustomConfiguration != null);
}
} catch (Exception e) {
// Error logging & re-throw
}
}
return m_CustomConfiguration;
}
}
When I step through the debugger in code that calls either of the above properties like this:
if (!Program.WCFCache.HasCustomConfiguration)
return new List<CustomComponents>();
...it throws the following exception:
System.AccessViolationException was unhandled
Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Source="System.Windows.Forms"
...
When I step onto the line containing the reference, there is a long pause, followed by a VS popup with the exception.
The exception doesn't appear when I just put a breakpoint after the above code has executed. It doesn't even appear when I put a breakpoint inside the accessors of the properties. It only occurs when I step onto a line with one of those properties from the outside. (So there is a workaround, but it can be a pain.)
Why is this happening? Can I stop it?
Edit: The whole application was written in the last year in 3.5 C#/.NET with WCF communicating between components; meaning, we don't have legacy unmanaged DLLs. Just two unmanaged calls: one to advapi32.dll when the WinForms app is loading, in the username detection procedure. The issue I'm having happens only in this one place in the code, in a place that is about as unrelated to the login section as you can get. The other is to kernel32.dll, in a GC force-flush long after anything is done with the results from calls like the one above.
Are you using any P/Invoke or other such native code? Odds are, that's where you should start looking.
This exception is a symptom of a larger problem, namely memory corruption (that what the exception says, after all). If this was a native application, you'd get a crash.
So, look at any native calls, make sure they're operating correctly, maybe run them under a debugger to try and trap the error closer to home.
Sorry, can't really give better advice given the circumstances.
I eventually found that others have encountered this situation and that it is likely a Visual Studio bug. I was using VS 2008 when the problem occurred.
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!