While debugging, debugger skips intermediate return statement and/or executes both branches of an if statement, etc - c#

Using:
Microsoft Visual Studio Community 2022 (64-bit) - Current
Version 17.4.5
When stepping through the code below, after hitting and continueing from the line 'return exists', the debugger will not jump to the end of the function, but instead step to the line 'return true' after which the function will return true, regardless of the value of 'exists'. Ofcourse, it should not execute the line 'return true' in the first place...
List<files> filesWithTheSameHash = GetFilesByMD5Hash(md5Hash);
if (filesWithTheSameHash.Count == 0)
{
return false;
}
if (contents != null)
{
Boolean exists = filesWithTheSameHash.Where(f => f.contents == contents).Any();
return exists;
}
return true;
What I tried was to run the code in both Visual Studio, as well as JetBrains Rider and there is no difference in behaviour.
I checked whether the project was compiling as a release build. It is not. It is a debug build. The configuration is to "Active (Debug)".
I checked whether compiler optimizations were enabled. For this, I went to the 'Build' tab of the project's properties and found 'Optimize code' to be unchecked.
I updated visual studio. No change.
I stepped through one other function in the same class and it also displayed similar behaviour.
I enabled 'Suppress JIT optimization on module load'. No change.
--- UPDATE 1 ---
There is an error in the code.
f.contents == contents
needs to be:
f.contents.SequenceEqual(contents)
--- UPDATE 2 ---
I wrote "regardless of the value of 'exists'." That is incorrect, what is returned is the value of the boolean 'exists', eventhough the debugger hits 'return false'. At this point the question has changed. The code is working fine, but how can I stop the debugger from hitting two return-statements in the same function (which is confusing) ?

Set breakpoints on all lines of this code and see where and how and why it goes

Related

Simple conditional breakpoint throws error in Visual Studio 2017 [duplicate]

Is it possible to use Linq within a conditional breakpoint?
I'm attempting to break when the following condition is true:
parentElement.ChildElements.Any(c => c.Id == 1)
When ever the debugger is hit the following error message is displayed
The debugger is unable to evaluate this expression.
I have tried the following condition in case the issue was related to using .Any()
parentElement.ChildElements.Where(c => c.Id == 1).Count() > 0
This resulted in the same error as above being displayed.
I know a work around would be the following code
#if DEBUG
if(parentElement.ChildElements.Any(c => c.Id == 1))
{
System.Diagnostics.Debugger.Break();
}
#endif
However, I would ideally not like to make code changes to place a debugger.
This issue was caused by the Use Managed Compatibility Mode option not being enabled within Visual Studio.
Once this option was checked the breakpoint performed as expected.
See this answer for how to enable this option within Visual Studio.

Visual Studio C# if statement not working in Debug

So I have a weird situation, where I get to an if statement while debugging, and I'm finding that even though EM=="M", my if statement if(EM=="E") is being entered anyway... I'm also noticing that some of my code seems to be just getting skipped over when I'm stepping though the code(F11).
I'm using C# in VS2015 and VS2017, it's having the issue in both versions. I was using Framework 4.5, I had switched it to 4.6.1 to build a compatible version for a different program. But switching that back didn't change anything...
public static string EM = "";
Database db = doc.Database;
//db.measureunits is 0 or 1
if (db.measureunits == 1) // english
{
EM = "E";
}
else // metric
{
EM = "M";
}
try
{
if (EM == "E") //If english
{ <-- Breakpoint STOPS Here EM is equal to "M" at this point, which shouldn't allow the break point to be hit, since EM("M")!="E"
topText.TextString = rad + "\" minimum bend radius";
}
if (EM == "M") //Metric
{ <-- Breakpoint never stops Here
topText.TextString = Convert.ToString(Math.Round((Convert.ToDouble(rad)) * 0.3048, 2)) + "\" minimum bend radius";
}
}
catch (IOException e)
{
// Extract some information from this exception, and then
// throw it to the parent method.
if (e.Source != null)
System.Windows.Forms.MessageBox.Show($"IOException source: {0}", e.Source);
throw;
}
If anyone else is aware of this issue or know's what I may be doing wrong, help would be appreciated.
The following workaround might be helpful
Delete bin and obj folder then re-build.
Restart Visual Studio OR PC
A few ideas.
There occures an exception so that it jumps over the code which is coming after. Press Ctrl + Alt + E and check "Common Language Runtime Exceptions". Now it should stop at the moment an exception occures and show it to you.
Your code was optimized during build. Try to build in debug mode or uncheck "optimize code" in the project properties under "Build".
Delete the obj and bin folders. You already tried this.
There is something fishy with the PDB file. The PDB file contains information for the debugger. Project properties -> build -> advanced => set "Debug Info:" to "full" (if you use debug configuration this should already be the case) and rebuild the whole solution.

Refrences break console app from running on other machines

I've made a console application which inserts data into a MySql backend, and reads the serial number from a hard disk
To do this i had to add References to MySql.Data and to System.Managment.
The way im running it is by copying the Debug directory from visual studio (i think this is the problem) and running the .exe file on the other machine.
When i run the application on another machine the stack trace error is:
PhDD >C:\Users\User\File\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object: reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 49
Updated HDD Stats at28/03/2012 18:46:57
Am i correct in thinking this problem is because of the referencing ?
I've checked the methods by recompiling the same code on the other machine and it works, when the references are added through VS.
Can anyone guide me on how to resolve this issue ?
Cheers for reading.
P.S. i tried adding reference paths (by right clicking on the project, selecting options and then choosing Reference Paths and adding the two dll files)
Line 49
bool conversion = int.TryParse(smartData[1].ToString(), out temp);
After adding a fake int value just to make sure conversion isnt the error the new stack trace error is:
PhDD >C:\Users\bborisov\Dropbox\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 53
Updated HDD Stats at28/03/2012 19:00:24
line 53:
DBHandler.insertData(smartData[0].Trim(),
3, smartData[2], file.getKey());
Put code in to check validity of error situations which may be happening on the client pc but not the development one. You can handle the errors by either throwing an exception or handling it gracefully in a better way.
Here is the code which checks for error situations
if (smartData == null)
throw new Exception("Smart data is null; aborting");
if (smartData.Any() == false)
throw new Exception("Smart data instance is valid but has no elements; aborting");
bool conversion = int.TryParse(smartData[1].ToString(), out temp);

os.access returning useless value for mode os.F_OK in IronPython

I have a pile of python scripts that I am trying to use within IronPython (I need C# functionality), and I am having some issues with the os.access method.
When using the os.access method with the mode set to os.F_OK (see whether a path can be accessed), I am getting False returned every time, even when the python interpreter returns True for that directory. The strange thing about this though, is that the os.access method called with the os.R_OK, os.W_OK and os.X_OK modes returns True.
Here is a code sample I knocked up to demonstrate the issue:
import os
d = ["C:\\", ".\\", "./", ".", "C:\\BOGUS_DIR"]
for path in d:
print path
try:
print "access: %s"%os.access(path, os.F_OK)
print "read: %s"%os.access(path, os.R_OK)
print "write: %s"%os.access(path, os.W_OK)
print "execute: %s"%os.access(path, os.X_OK)
print "-------------------------"
except Exception, e:
print e
print "finished"
raw_input("")
The results:
C:\
access: False
read: True
write: True
execute: True
-------------------------
.\
access: False
read: True
write: True
execute: True
-------------------------
./
access: False
read: True
write: True
execute: True
-------------------------
.
access: False
read: True
write: True
execute: True
-------------------------
C:\BOGUS_DIR
access: False
[Errno 2] Could not find file 'C:\BOGUS_DIR'.
finished
For good measure, I added a bogus directory to the list (a directory that doesn't exist). The os.access with mode os.F_OK returned False (as always), but the call to check os.R_OK throws an exception (as expected).
Also, I tested the os.access method in the python interpreter, which worked fine.
I can't seem to find anybody else with this issue, which is why my first assumption is that I've done something silly (or missed something obvious). I am running the IronPython code through Visual Studio 2010, perhaps there is something interfering there.
Any help would be greatly appreciated. Thanks
For one, os.access can be misleading - it's better to just open the file and catch any exceptions that occur.
IronPython uses os.F_OK to mean "does this file exist", and boils it down to a call to File.Exists() - which returns false for a directory.
This is a bug, and should be fixed in 2.7.1.

Uninstalling my Office 2010 plugin leaves a null pointer exception

I've been trying to track down why my Office2010 plugin leaves a null pointer exception during uninstall and the 2007 version does not. (Edit: 2007 is at same state as 2010 - FAIL)
To narrow it down I have put in a couple of eventlog traps, meaning if code reaches this point - I should get something in the Eventlog. No such luck. Now either I written the eventlog trap wrong or code doesn't reach that point.
In the CustomSetupActions - ClickOnceInstaller.cs
public void Uninstall(System.Collections.IDictionary savedState)
{
// write something to eventlog
// This is not being fired, the exception doesn't reach here or writing to eventlog fails.
if (!EventLog.SourceExists("OfficePlugin"))
{
EventLog.CreateEventSource("OfficePlugin", "Application");
}
EventLog.WriteEntry
("OfficePlugin"
, string.Format("Uninstalling: (bug hunting)"), EventLogEntryType.Information);
string deploymentLocation = (string)savedState["deploymentLocation"];
if (deploymentLocation != null)
{
string arguments = String.Format(
"/S /U \"{0}\"", deploymentLocation);
ExecuteVSTOInstaller(arguments);
}
}
As for the ExecuteVSTOInstaller(string arguments)
2007 refers to: string subPath = #"Microsoft Shared\VSTO\9.0\VSTOInstaller.exe";
2010 refers to: string subPath = #"Microsoft Shared\VSTO\10.0\VSTOInstaller.exe";
If the first trap had fired, this is where I would have placed the trap afterwards.
--
I have another method that handles the registration db
RegisterOffice2010AddIn.cs
public void UnRegisterAddIn(string applicationName, string addInName)
{
Next line is precisely the same eventlog trap as I just used/shown.
Difference between the two (2007 vs 2010).
private const string UserSettingsLocation =
#"Software\Microsoft\Office\12.0\User Settings";
vs
private const string UserSettingsLocation =
#"Software\Microsoft\Office\14.0\User Settings";
I can't think of any other place that might be interesting to place the trap. I have a CustomInstaller which doesn't do anything besides Dispose(bool disposing) and InitializeComponent()
Development:
Action start 14:21:00: PublishFeatures.
Action ended 14:21:00: PublishFeatures. Return value 1.
Action start 14:21:00: PublishProduct.
Action ended 14:21:00: PublishProduct. Return value 1.
Action start 14:21:00: InstallExecute.
MSI (c) (B8:BC) [14:21:01:013]: Font created. Charset: Req=0, Ret=0, Font: Req=MS Shell Dlg, Ret=MS Shell Dlg
Error 1001. Error 1001. An exception occurred while uninstalling. This exception will be ignored and the uninstall will continue. However, the application might not be fully uninstalled after the uninstall is complete. --> Object reference not set to an instance of an object.
DEBUG: Error 2769: Custom Action _EE8A0D36_BE55_421F_9A55_95470C001D87.uninstall did not close 1 MSIHANDLEs.
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2769. The arguments are: _EE8A0D36_BE55_421F_9A55_95470C001D87.uninstall, 1,
Action ended 14:21:05: InstallExecute. Return value 3.
Action ended 14:21:06: INSTALL. Return value 3.
Googling the Error 2769 - gives an answer of "[TARGETDIR]\" , but I dont reference TargetDir, I reference deploymentLocation. And Yes I have tried adding the "\" to places I could think of. Including the setup - Registry - HKLM\Software\MS\Office\12.0\ ...etc... \Addins\Excel/Word/Outlook and the Manifest keyvalue. Gave no feedback, good or bad, errors or otherwise. I'm at a loss what else to try to hunt this one down.
I have a guess it is referencing to this, in the VDPROJ:
{
"Name" = "8:UnregisterOutlookAddIn"
"Condition" = "8:"
"Object" = "8:_73E71A44EB72485AB7367745F7D57F49"
"FileType" = "3:1"
"InstallAction" = "3:4"
"Arguments" = "8:"
"EntryPoint" = "8:"
"Sequence" = "3:3"
"Identifier" = "8:_EE8A0D36_BE55_421F_9A55_95470C001D87"
"InstallerClass" = "11:TRUE"
"CustomActionData" = "8:/addinName=\"OUR.Outlook.Outlook2010AddIn\" /application=\"Outlook\""
}
I found it throws two exception - the secondary under CustomSetupActions and UnregisterAddIn and the primary under ClickOnceInstaller and Uninstall. Howcome I mention them as 2ndary and primary. Well it will do the exception in CustomAction and then the killing one in ClickOnce. I've eliminated the one in CustomActions and I now only have to worry about the ClickOnce. From what I can gather the ClickOnce implements the interface specified in the Setup Project (Install, Rollback, Commit, Uninstall). I only have to figure out how it can run amiss the Uninstall method.
Disclaimer: Unless ofcourse I'm mistaken and is barking up the wrong tree.
Change to WiX. It became a workaround as the original is still true.

Categories

Resources