Visual Studio IDE0059 C# Unnecessary assignment of a value bug? - c#

I have the following C# Code (I reduced it to the bare minimum to simplify it). Visual Studio 2019, .NET Framework 4.7.2.
public void Demo()
{
ReportStart();
var success = false;
try
{
int no = 1;
switch (no)
{
case 1:
default:
break;
}
DoSomething();
success = true;
}
finally
{
ReportEnd(success);
}
}
From my understanding, there is nothing wrong about it. The function may fail (I don't want to catch it) but before leaving, it will report successful execution to another method. When debugging, it does exactly what it should.
Interestingly, Visual Studio 2019 will report the following:
When I follow the suggestion by choosing "Remove redundant assignment", it will remove the line success = true;, effectively changing the outcome!
Now what is the switch/case for, you'd ask? When removing it, the recommendation disappears:
Is there any reason for that, or is it a bug in Visual Studio?

It seems to be a known issue with Roslyn and Visual Studio 2019 16.4, please refer to the GitHub issues #39755 and #39344.
The milestone is set to the version 16.5 Preview 2, so it was already fixed and you can try the preview 2 of 16.5 version or wait for stable one (personally, I'm not using a Preview versions)

Related

Visual Studio 2019 IntelliSense changed (how to get prior behavior?)

Since I switched to VS 2019 (from 2017) I am pretty sure I got a degraded IntelliSense experience. I looked for settings under Tools -> Options... but did not find anything helpful.
The matter is this: suppose I have a variable kvp that has a property Key, I could type "key.", scroll to the "Key" property (if this is not already selected) and then type ";" to complete the statement.
But this does not work anymore. Instead it now ignores what I selected and I get
key.;
The only way to get the selected property is to explicitly hit enter. Same when I type the first character(s) to select the desired option: when pressing ; it just leaves what I already typed and adds the ; immediately behind it, ignoring what I selected in the popup menu.
What happened and how do I get the proper behavior back?
I am using the Preview version but I already had a couple of updates and it does not improve so I guess it is by design or default behavior now.
Here's some of my code for Perry. It is just an example though, the problem (or what I regard to be a problem) occurs with any object variable.
private static void AddBlockNodes(TreeNode node, IDictionary<string, Block> blocks)
{
foreach (KeyValuePair<string, Block> kvp in blocks)
{
string name = kvp.Key;
Block block = kvp.Value;
TreeNode childNode = new TreeNode(name);
childNode.Tag = block;
node.Nodes.Add(childNode);
AddBlockNodes(childNode, block.Subblocks);
}
}
it just leaves what I already typed and adds the ; immediately behind
it, ignoring what I selected in the popup menu.What happened and how
do I get the proper behavior back?
It is quite an abnormal behavior and l have installed Visual Studio 16.6.0 Preview 2.1 and test your code in my side and it works well.
Type variable kvp. and then select property Key and it types as expected. I did not face missing property Key during the process.
You can try these steps to troubleshoot your issue:
Suggestion
1) reset all settings by Tools-->Import and Export Settings-->Reset all settings
2) close VS Instance, enter the project path and delete .vs hidden folder which stores some Intellisense settings, bin, obj folder and then restart your project again. I wonder if you migrate an old project into VS2019 preview version, I think you should complete this step.
3) disable any third party extensions if you have under Extensions-->Manage Extensions in case they cause this behavior.
4) delete all component caches under C:\Users\xxx\AppData\Local\Microsoft\VisualStudio\16.0_xxx(16.0 is VS2019)\ComponentModelCache
5) try to create a new project in VS2019 Preview version and test whether this issue persists in the new platform and if it works, I think it is an issue of your project itself. Or you can try to migrate your project into the new project.
Hope it could help you.

VBScript GetObject() not working if called from C# WPF application

I have the following VBScript code in MyScript.vbs:
Dim myApp
Set myApp = GetObject(,"ViewDraw.Application")
I call it from a PowerShell command line, like so:
cscript MyScript.vbs //I
This works as expected; myApp is set to the process I'm looking for and I'm able to interact with it.
Here's some C# code that attempts to do the same thing:
var script = new Process();
script.StartInfo.FileName = "cscript";
script.StartInfo.Arguments = #"<MyWorkingFolder>\MyScript.vbs //I";
script.StartInfo.CreateNoWindow = true;
script.StartInfo.RedirectStandardOutput = true;
script.StartInfo.UseShellExecute = false;
script.Start();
//Read anything sent out by program
string output = script.StandardOutput.ReadToEnd();
script.WaitForExit();
VBScriptResult result = new VBScriptResult();
result.returnCode = script.ExitCode;
result.stdOut = output;
return result;
When I execute the C# code, the VBScript fails on the GetObject() call. There have been similar SO questions, and I've tried their suggestions. One suggestion was to explicitly call either the 32bit or 64bit version of cscript. Neither worked, however.
This hasn't always been an issue. The code is a couple of years old now and has worked in the past. It's possible that an update to Visual Studio 2017 somehow caused this problem. I'm currently running version 15.3.5.
I've been stuck on this issue for a week now, so any help is greatly appreciated!
The problem is with Visual Studio 2017, probably a result of taking update 15.3 or later. The same code works fine in VS 2015 Update 3.

Nunit malfunction for tests in C#

I have transitioned my test project from Visual Studio 2010 to 2015.
Execution of the tests in earlier version was fine since it was Mbunit. In the new version is used Nunit 3.4.1. I do not see any problem in my code. Whenever I want to run test I receive Message: No arguments were provided.
Here is the code of test that have worked fine with MbUnit
[Test]
[TestCaseId(456123)]
[Priority(PriorityLevel.Critical)]
public void ExpiredJobViewPageUi(string channel, SeleniumWebDriverDeviceType seleniumWebDriverDeviceType,string widgetType) {
TestRunner.RunTest(MethodBase.GetCurrentMethod(), channel, seleniumWebDriverDeviceType, webDriver => {
//Test body
ReportLog.WriteLine("Step 1 - Create new flow.");
var flow = new StandardFlowModel<JobModel>(channel, webDriver, ReportLog.WriteLine);
ReportLog.WriteLine("Step 2 - Go to .");
var expPage = flow.GoToExpirationPage(123);
expPage.WaitPageIsLoaded(10);
....
When I click on Run Selected Test in the Text Explorer in Visual Studio 2015 I got the message No arguments were provided.
Can anybody help me what is wrong? Even though there is no chance to set break point to figure out what is going on.
the problem was that I missed some input parameters in [] brackets. When I dig into TestRunner and debugged it I found that I need to specify [Combination("parm", SeleniumWebDriverDeviceType.Desktop, "Popular Articles")]
Thank you for your hints!

Visual Studio 2015 has problems communicating using VISA Libraries

I'm having problems with the VISA-Com Libraries to communicate with a Keysight (N6700B) power supply.
I have some C# code I am compiling in Visual Studio 2015, and it does not work. However, if I compile the same code in Visual Studio 2012, then it works.
Basically I am just doing simple communication with the device:
using Ivi.Visa.Interop;
//...
string address = "USB0::2391::2311::MY54002380::0::INSTR";
ResourceManager rm = new ResourceManager();
FormattedIO488 myDmm = (IMessage)rm.Open(address , AccessMode.NO_LOCK, 2000, "");
myDmm.WriteString("*RST"); // reset the device
myDmm.WriteString("*IDN?"); // request the IDN string;
string IDN = myDmm.ReadString(); // This is where it fails, returning: "VI_ERROR_TMO: A timeout occurred"
Also, the power supply has an error state of: "Error -420, Query UNTERMINATED"
The code does not work with VS2015, but it DOES work with VS2012.
(In VS2012 I get no errors at all.)
I have tried downloading the latest drivers from KeySight, and it still does not work (www.keysight.com/find/iosuitedownload).
Does anyone have any idea why it would be breaking with VS2015 but work with VS2012?
I've looked up "Quere Unterminated" and some say that it could be a missing Termination character "\n". I've tried adding the "\n" to both writeStrings, and it still fails.
EDIT: I have also now tried using (in various places):
myDmm.IO.TerminationCharacterEnabled = true; // and = false
myDmm.FlushWrite(); // also tried passing in "true" (default is 'false')
I also tried adding the:
myDmm.IO.TerminationCharacter
to the WriteStrings.
http://download.ni.com/support/softlib//visa/NI-VISA/15.0/Windows/readme.html
Microsoft Visual Studio Support
The following table lists the programming languages and Microsoft Visual Studio versions supported by this version of NI-VISA.
Earlier versions of NI-VISA support other application software and language versions. For more information on Visual Studio compatibility with earlier versions of VISA, refer to ni.com/info and enter the info code NETlegacydrivers. To find and download an earlier version of a driver, refer to ni.com/downloads.
Visual Studio Versions Support by NI-VISA:
Visual C++ MFC1 -------------- 2008
Framework 3.5 Languages (Visual C# and Visual Basic .NET) -- 2008
.NET Framework 4.0 Languages (Visual C# and Visual Basic .NET)-- 2010
.NET Framework 4.5 Languages (Visual C# and Visual Basic .NET)-- 2012
So apparently the drivers don't work with VS2015... (not sure how a newer version doesn't work.. but okay)
EDIT, FOUND ANSWER
Someone from NI-VISTA told me to just add "true" as a second parameter:
myDmm.WriteString("*RST",true); // reset the device
myDmm.WriteString("*IDN?",true); // request the IDN string;
string IDN = myDmm.ReadString(); // now it works.
I'm not sure why "true" wasn't needed in 2012, and why it is needed in 2015... oh well.
I confirm: the method WriteString() (but not only this) needs the bool parameter flushAndEND = true (default value = false) in order to complete the command. Without it, the instrument can't parse the instruction. If you send multiple commands, the instrument can't separate and identify them.
I suggest you to use the Keysight IO monitor for sniffing the communication between your instruments and you controller (PC?) . It's an utility of the IO Libraries Suite (v17.1).
For details, see the attached IFormattedIO488 interface definition, belonging to the reference Ivi.Visa.Interop.
using System.Runtime.InteropServices;
namespace Ivi.Visa.Interop
{
[...]
public interface IFormattedIO488
{
[DispId(1610678274)]
bool InstrumentBigEndian { get; set; }
[DispId(1610678272)]
IMessage IO { get; set; }
void FlushRead();
void FlushWrite(bool sendEND = false);
dynamic ReadIEEEBlock(IEEEBinaryType type, bool seekToBlock = false, bool flushToEND = false);
dynamic ReadList(IEEEASCIIType type = IEEEASCIIType.ASCIIType_Any, string listSeperator = ",;");
dynamic ReadNumber(IEEEASCIIType type = IEEEASCIIType.ASCIIType_Any, bool flushToEND = false);
string ReadString();
void SetBufferSize(BufferMask mask, int size);
void WriteIEEEBlock(string Command, object data, bool flushAndEND = false);
void WriteList(ref object data, IEEEASCIIType type = IEEEASCIIType.ASCIIType_Any, string listSeperator = ",", bool flushAndEND = false);
void WriteNumber(object data, IEEEASCIIType type = IEEEASCIIType.ASCIIType_Any, bool flushAndEND = false);
void WriteString(string data, bool flushAndEND = false);
}
}
Have you tried the ReadBytes method? This method reads a fixed amount of bytes from the device. The error you've encountered most probably occurs because the the visa driver tries to read data until a termination character, which you never explicitly set, is received.
Try setting the TerminationCharacter Property to either \n or \r (depending on the instrument) and it should work. Furthermore, you might want to add it to the commands you send as well so the instrument won't bother you with this error (-420) anymore.

Why isn't this code executing correctly (video)?

I'm using Unity (3.4) Monodevelop (2.4.2) and it's not executing the code properly when I step through it in the debugger. Here's a link to the video that shows it, please run it at 720p and fullscreen it...
http://www.youtube.com/watch?v=LGN7kxMUqjA
Also, here are some screenshots showing the debugger displaying really strange values when I mouseover a variable. Here's what it looks like when it correctly shows the value of the xSectionPixel in the first if block...
And here's what it looks like when it incorrectly shows the value of the xSectionPixel in the second if block...
This is also the line of code where it starts executing code incorrectly.
What would cause this?
I've tried reinstalling the tools, using a fresh copy of the code from the repository, I even set it all up on a different computer with a different OS (Win 7) and it always does the same thing. Doesn't that mean it has to be my code then?
It's also worth noting that I'm using SVN to push/pull the code from a repository and my local copy exists in my Dropbox folder.
Thanks so much in advance for your wisdom! Here's the code as well if you can spot anything that might be breaking things (i.e. the way I'm using floats and ints maybe?)
Vector2 textureCoordToHexGridCoord(int textX, int textY)
{
Vector2 hexGridCoord = new Vector2();
float m = hexH / hexR;
int xsection = (int)(textX / (hexH + hexS));
int ysection = (int)(textY / (2 * hexR));
int xSectionPixel = (int)(textX - xsection * (hexH + hexS));
int ySectionPixel = (int)(textY - ysection * (2 * hexR));
//A Section
if(xsection % 2 == 0)
{
hexGridCoord.x = xsection;
hexGridCoord.y = ysection;
if(xSectionPixel < (hexH - ySectionPixel * m))
{
hexGridCoord.x--;
hexGridCoord.y--;
}
if(xSectionPixel < (-hexH + ySectionPixel * m))
{
hexGridCoord.x--;
}
}
//B Section
else
{
if(xSectionPixel >= hexR)
{
if(ySectionPixel < (2 * hexH - xSectionPixel * m))
{
hexGridCoord.x = xsection - 1;
hexGridCoord.y = ysection - 1;
}
else
{
hexGridCoord.x = xsection;
//hexGridCoord.y = ysection;
hexGridCoord.y = ysection - 1;
}
}
if(xSectionPixel < hexR)
{
if(ySectionPixel < (xSectionPixel * m))
{
hexGridCoord.x = xsection;
//hexGridCoord.y = ysection - 1;
hexGridCoord.y = ysection;
}
else
{
hexGridCoord.x = xsection - 1;
hexGridCoord.y = ysection;
}
}
}
return hexGridCoord;
}
I have no specific experience with the frameworks you use, but I do have a lot of experience with debuggers.
The debugger behavior you see can happen in one of two scenarios (that I can think of...)
The symbol files and executing code are not synchronized with your source code, usually the IDE should detect that, but it some cases it doesn't, the solution is to delete all binaries, recompile and try again.
A bug in the debugger or the debugger extension (used to debug in the specific environment your are in, i.e. unity/monodevelop).
If you are unable to resolve it, I would add logging to your code and use it to really understand what happens.
I saw similar behavior on MonoDevelop with WinForms applications, solved with reinstalling debugger.
Have you tried that or using Visual Studio to verify that the problem is in the code?
Do you have optimizations turned on? If so, does disabling them make stepping any less erratic?
Enabling optimizations is one thing I can think of that no one else has mentioned yet that could potentially cause what you are seeing.
Can you try removing you breakpoints, setting a new one, and stepping through the code?
The reason I ask is there are ways that you can set values using breakpoints. A very similar thing happened to me and was convinced that there was a compiler bug. After stepping through the CLR and number of other things with no answer, we stumbled across a breakpoint that was set earlier for testing, and never removed.
That kind of behavior usually happens to me when I'm debugging a multithreaded part of an application.
What happens is that while you debug several threads at once, the debugger in visual studio keeps switching between them without notifying you by default.
Now since threads are not executing the same lines at the same time, you got unexpected "jumps".
I believe it is widely used in game developpement, so in your case you got two choices:
1) Make only one thread run while you make your debugging.
2) Make unit tests <= That's the "best practice".
You can start by having a look at NUnit
The first issue most likely has something to do with the sequence points in the JITed code. These are the points where the debugger can stop. They're computed by the runtime based on the IL and debug symbols generated by the compiler, therefore this is most likely a runtime or compiler bug. I don't know what version of the Mono runtime and compiler is being used by Unity, but it's quite that this has been fixed in a newer version. If you can reproduce this using a "normal" console app using the latest official MonoDevelop and Mono 2.10.x, please file a bug at http://bugzilla.xamarin.com with a test case. If not, please ask Unity to upgrade their version of Mono.
The second issue looks like an issue in MonoDevelop's expression resolver that's used to resolve the symbol under the mouse. This may have been fixed in a newer version of MonoDevelop - likewise, please try to repro with the official MonoDevelop 2.8.4, and file a bug if it's still an issue.

Categories

Resources