visual studio 2010 debugger - steps into an "if" statement despite condition false - visual-studio-2010

I'm using VS 2010 Professional (On Windows 7 Professional 64), writing with WCF 4.0.
I have the following code:
if (responseMessage.StatusCode == HttpStatusCode.NotFound)
{
throw new ContentNotFoundException(contentId, SSPErrorCode.PartnerRestGetStream404);
}
When attaching the debugger to the process, having set a breakpoint at the "if" statement or before that, while the condition is false (responseMessage.StatusCode is 'OK'), the debugger steps into the "if" statement. It then steps over the "throw" statement without doing anything, then continuing on with the code.
I've tried:
Restarting VS, logging out my Windows user, rebooting, cleaning the solution, building it again, rebuilding it, recycling the application pool, resarting IIS, adding more code inside the "if" statement and inside the condition - nothing worked so far.
There must be a cache somewhere which I can clean to get rid of it, but what, and where?
Googling this I only found http:--social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/d4b70fd7-b74a-42ce-a538-7185df3d3254/, so I tried manually setting the breakpoint, and it didn't break in this class, although the same did break in other classes.
I would love to fix this without reinstalling VS. Thank you in advance!
Update:
Since I put this up and could not find an answer, I moved on with my project.
I stumbled upon this issue, reported by John MacIntyre on this post, which ends up with a simplified example:
using System;
namespace IEnumerableBug2
{
class Program
{
static void Main(string[] args)
{
if (new object() == null)
throw new Exception();
try { } catch { }
}
}
}
Update #2:
Note that my Method also has a try-catch statement in it, a few lines after the 'if' statement.
I've just tried reproducing this bug again, and failed. I'm going to leave the question on stackoverflow for others who might need it, but, as I wrote, I am no longer able to reproduce the behaviour.

I am experiencing this problem too, but slightly different.
Here's my code:
string lockCode = Guid.NewGuid().ToString();
bool alreadyLocked = string.IsNullOrWhiteSpace(lockCode);
if (alreadyLocked) {
throw new Exception("already running");
}
try {
PerformTask(task);
}
finally {
UnlockTask(task, lockCode);
}
As you can see, the lockCode string is always assigned with a Guid value. The debugger steps into the 'if' scope, although it shouldn't. The exception isn't thrown.
I am running Visual Studio 2010 SP1 on Windows 7 64-bit with ReSharper 6.0.
Microsoft Visual Studio 2010
Version 10.0.40219.1 SP1Rel
Microsoft .NET Framework
Version 4.0.30319 SP1Rel
Installed Version: Premium
This happens to me with an ASP.NET application on framework 4.0.
I tried running the repro code posted here on a different project on my machine but could not reproduce the issue.
Also, I have deleted the Shadow Copy Cache for the .NET Framework on this path:
C:\Users\username\AppData\Local\assembly
I deleted the VS2010 symbols cache directory, and the Temporary ASP.NET Files.
I restarted my computer, cleaned the whole solution and rebuilt everything.
No clue why this happens.
Workaround: If I remove the 'try-finally' part from the method, or extract the throw statement to a different method, the debugger steps over the 'if' scope correctly.
Sorry for not posting a real solution to this, I hope this helps either isolate the problem or work around it.

Today I also experienced this issue. The following code solves the problem, with the advantage of not compiling the workaround on release builds:
using System;
namespace IEnumerableBug2
{
class Program
{
static void Main(string[] args)
{
if (new object() == null)
throw new Exception();
#if DEBUG
bool workaround = true; // dummy instruction
#endif
try { } catch { }
}
}
}

While stranger things have in fact happened, I highly doubt that this is a bug in the debugger or bad bad VS installation.
I think something must be happening that you're not interperting correctly. Did you put the expression "responseMessage.StatusCode == HttpStatusCode.NotFound" into the Debug Watch window? What does it return? Is it possible StatusCode is returning a different value each time? Did you try evaluating it several times to make sure it is consistent?
The only way I could imagine this happening is if the code was changed, and when prompted whether or not you want to debug the source file even though its version does not match, you answered Yes. This would explain why you can skip over the "throw" line without it doing anything - you're not debugging the actual code you're seeing, but an older version of it. To fix this, rebuild everything, and never say yes when prompted if you want to debug even though there is a version mismatch - it is way too confusing!

Related

ShimNotImplementedException after upgrading Visual Studio 2013 and Microsoft Fakes v12

We are utilizing Microsoft Fakes with Visual Studio 2013. After updating to Visual Studio 2013 Update-4 or Update-5, we are getting ShimNotImplementedException's in our tests.
We have followed instructions found in other SOF questions and turned off the SpecificVersion of our Microsoft.QualityTools.Testing.Fakes references. This allows a compile but the tests still fail when run.
The hint we needed to solve this was found in MSDN forums.
The underlying issue is that the legacy tests did not define specific methods
on the ShimXXX object that the code based is using. Under version 11
all is well; version 12 is a different matter.
The stack trace for the ShimNotImplementedException gave the needed information on the missing property/method:
Microsoft.QualityTools.Testing.Fakes.Shims.ShimNotImplementedException
at $Func`2NotImplementedf5b9281e-32b0-4bf3-9079-6a54470670de.Invoke(SiteContext arg1)
at Sitecore.Sites.SiteContext.get_Database() //THIS IS THE PROBLEM PROPERTY
at Sitecore.Ecommerce.ShopContext..ctor(SiteContext innerSite)
at ActiveCommerce.UnitTest.ProductStockManagerTests.get_MockShopContext()
at ActiveCommerce.UnitTest.ProductStockManagerTests.GetAvailability_AlwaysInStock()
Adding the missing property to our shim construction solved the issue:
return new Sitecore.Ecommerce.ShopContext(new ShimSiteContext
{
PropertiesGet = () => new NameValueCollection(),
DatabaseGet = () => null //ADDING THIS SOLVED THE ISSUE
});
I ran in to a similar problem after upgrading several of our projects from .NET 4 to .NET 4.5.2 using Visual Studio 2015. All the sudden several previously passing tests started failing. The common denominator was that all of the tests were using Shims to mock registry access.
What appears to have happened is that something changed in the handling of the Dispose method. Originally I had not implemented a Dispose method on the RegistryKey shims. That didn't seem to cause any trouble running under .NET 4. However after the switch to 4.5.2, it is implicitly being called all the time.
The solution was simple: I just added a stub for Dispose.
Microsoft.Win32.Fakes.ShimRegistryKey.AllInstances.Dispose = (key) => { };
The tests now pass again.
Note that setting it to NULL did not solve it for it. There has to be a method.

TypeScript 1.3 protected error

Recently installed new TS version into VS2013 and tried to use protected modifier.
However TS validator shows me an error (and underlines protected word with a red line.
I get an error like
Use of future reserver word.
; expected
looks like it's looking into old TS definitions.
Checked the project file and there is 1.1 version of TypeScript.
also running tsc -v produces 1.3.0.
Does somebody of you guys experience that?
What i'm missing and what to do to fix that.
Thank you a lot for any help.
export class SomeClass {
protected metadata: Metadata;
protected subItems: SomeClass[];
constructor() {
}
}
thank you all guys. for your answers!
the reason was (oh, what's the shame =) ) the ReSharper.
It's validation was showing that error, suspending it i'm getting no errors now.
Looks like JetBrains guys should update their definitions like Web Essentials did.
As they aren't compatible with new TS version, 1.3. And no updates pending as for now.
Hope, it'll be useful for somebody else.
The answer to your question then is ReSharper 9.0 EAP.
It supports TypeScript 1.3 features: 'protected' modifier and tuples.
You're welcome to try it. Though, yes, it's a pre-release version, so overall stability is not strictly guaranteed.
Are you building from within Visual Studio, or from the command-line? What with different versions of the SDK being installed, as well as potentially the NPM package globally (if you've ever installed that), it can get quite messy as to which version gets picked up. For example, if I run 'where tsc' from the command prompt, I get the below hits (and this is without the 1.1 SDK on the path, though I am in the bin folder for testing the latest bits)
S:\src\TypeScript\bin>where tsc
S:\src\TypeScript\bin\tsc
S:\src\TypeScript\bin\tsc.js
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\tsc.exe
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\tsc.js
C:\Users\billti\AppData\Roaming\npm\tsc
C:\Users\billti\AppData\Roaming\npm\tsc.cmd
Can you verify via "where tsc" the locations and order you PATH is resolving the 'tsc' command?
That said, if you're building from within a VS project, it should locate the latest SDK via the build target. Does this also occur with a new TypeScript project (where the latest version and targets file should be referenced)?
Failing that, and I hate to say it... ready... did you try rebooting? :-) Sometimes updates to the PATH etc.. after an install don't get picked up until processes restart, and things like MSBuild can actually linger waiting for the next build as a perf optimization, rather than exit once the build is done (and thus may not pick up environment changes immediately).
It didn't work for me too. What I did to fix it was installing VS2013 Update 4 and after that, I executed the TypeScript 1.3 setup again and did a repair.
Also, you should make sure you don't have <TypeScriptToolsVersion>1.0</TypeScriptToolsVersion> in your csproject defined. Set it to 1.1 (not 1.3) or remove it entirely (then it will use the latest one). Hope that helps!
You can determine whether the issue is related to Visual Studio pointing at the wrong TypeScript version by following these steps.
Place this example code in C:\Temp\app.ts
interface Metadata {
something: string;
}
export class SomeClass {
protected metadata: Metadata;
protected subItems: SomeClass[];
constructor() {
}
}
export class OtherClass extends SomeClass {
constructor() {
super();
this.metadata = null;
}
}
var x = new SomeClass();
// Not allowed
// x.metadata = null;
Run the command:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.1>tsc --module amd c:\Temp\app.ts
Taking care to ensure you are pointing at the 1.1 folder in the TypeScript SDK folder.
The output should be:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.1>
i.e. nothing, except you now have an app.js file.
You can also re-run the test after uncommenting the x.metadata = null; line - at which point you should get the error:
c:/Temp/app.ts(22,1): error TS2445: Property 'metadata' is protected and only accessible within class 'SomeClass' and its subclasses.
Next Steps...
If the above fails, please supply details of the problem.
The only real answer we could give though it remove it and check the 1.1 folder is gone before re-installing it by fetching the installer fresh from the Microsoft website (perhaps you have a bad installer or there was some problem during installation?) You may also want to check that you are on Visual Studio Update 4, as I am testing it on Update 4.
If the above worked as expected, your Visual Studio is not pointing at the correct version.
This could be because of the project file as Dick van den Brink has correctly mentioned. Check that you have <TypeScriptToolsVersion>1.1</TypeScriptToolsVersion> and that it is the only element with this name.
It can also be down to any Visual Studio extensions that may be messing with your TypeScript (for example, if you had a really old version of Web Essentials - in which case, update it - if it is some other extension, try disabling it).

Visual Studio Debugging Issue with Resharper/Nunit

I am having a very frustrating problem in Visual Studio. I am using Resharper, and writing tests in Nunit.
If I set a breakpoint, it does get hit, however Step In/Over and Continue do not work, and the test never finishes. Even if I set two break points, continuing won't hit the second. If I debug a test without a breakpoint, it finishes fine.
Also, often and intermittently, when I try to debug a test by setting a break point, I can't evaluate the contents of variables, but instead see this message:
Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation.
I am using Visual Studio 2010.
Please let me know if you have any ideas of what to look at... I have scoured the web, but without any luck.
Happy to provide further information if needed.
EDIT - Example of method
Test:
[Test]
public void OneRowAddedToSourceData() {
//Factory just returns System.Data.DataTable with correct columns.
var sourceData = new DataTableContainerFactory().GetTargetTableContainer(DataTypeNames.EventSharedEnd);
//GetRow just returns a populated row.
var row = GetRow(sourceData, 123456, 123,60, 31);
sourceData.DataTable.Rows.Add(row);
Assert.AreEqual(1, sourceData.DataTable.Rows.Count);
}
When I set a break point on the Assert statement, and try to evaluate the data table I get this problem.
UPDATE 2!
So, I have narrowed this problem down to Resharper Debugging. I changed a test class to MSTest rather than NUnit, but still got both the above problems when debugging with Resharper. However, when I ran the tests with the built in VS MSTest test runner, ALL the problems had gone!
Now I much prefer using NUnit and Resharper, so I would be very happy if someone could point me at a setting that will allow Resharper to debug properly!
I have a possible solution, albeit with a caveat. Did some searching and ran across this blog item. It suggests turning off Enable property evaluation and other implicit function calls from Tools->Options->Debugging->General. I turned it off and I can now go into items that previously caused this problem.
The caveat is that all the properties you're used to seeing automatically evaluated are now not being shown. Instead it states Implicit function evaluation is turned off by user. All you need to do is hit the Refresh button on a property and you can see the value, but I haven't decided whether this is a trade-off I'm willing to make.
I've found de way to solve this problem!
Check the option DEBUG->OPTIONS AND SETTINGS->GENERAL->ENABLE PROPERTY EVALUATION AND OTHER IMPLICIT FUNCTION CALLS and uncheck the option Call string-conversion function on objects in variable windows
This worked to me!

MSBuild doesn't find async required references

We have Visual Studio 2010 SP1 and Async CTP (SP1 refresh) installed.
A solution with projects that use async/await keywords builds OK when build from VS IDE.
Also when built with devenv /build "Debug" solution.sln everything is OK.
However msbuild #commands.rsp solution.sln reports:
File.xaml.cs(123): error CS1993: Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
commands.rsp looks like this:
/nologo
/p:Configuration=Debug
/m:3
/fileLogger
Any clues?
Please, refer to the discussion here: http://social.msdn.microsoft.com/Forums/uk-UA/async/thread/3d491cb0-a19f-4faf-80a6-5fd05e4e06db
There are 2 points to be clarified in order to understand better your problem:
Environment: did you install VS11 side-by-side with VS 2010+Async CTP?
Your project: do you have XAML with user controls and "clr-namespace" in your project?
I will cite the preliminary conclusion by SERware from the discussion on the MS forum:
I think it has to do with the order in which the XAML projects
compile assemblies when referring to classes of the library itself. In
this case, the XAML Loader try to compile this classes before having
reference to the Async CTP library. So, the keyword "async" is not
recognized.
Personally I am going to see whether it is possible to split the assembly in order to resolve the order of the compilation of the dependencies in XAML
Added after further investigation:
As I have found out, the explanation is even more disappointing: the .NET 4.5 (Beta) replaces the .NET 4.0. Besides, the signatures of the async/wait related types have been internally changed. Therefore there is no way so far to use simultaneously VS 2010+AsyncATP and VS11 Beta. – Yuri S. 2 mins ago
I was hit by this myself and for various reasons I can't upgrade the projects to .NET 4.5 so I had to develop a workaround.
Since this is only a problem for XAML projects that has a xmlns declaration pointing to itself I'm able to use async on all the other projects that are referenced. This means my architecture is still utilizing async/await and is prepared for the move to .NET 4.5 later.
But in the affected XAML projects, I just manually implement (poorly) the await things otherwise done by the compiler.
So code that was this clean before:
try
{
var foo = GetFoo();
foo.DoStuff();
var data = await foo.GetDataAsync();
bar.WorkOnData(data);
}
catch (Exception ex)
{
// Logging, throw up a popup, whatever...
HandleError("Failed to get data", ex);
}
Now becomes this:
var foo = GetFoo();
foo.DoStuff();
var getDataTask = foo.GetDataAsync();
getDataTask.ContinueWith(t =>
{
if (t.IsFaulted)
{
// Logging, throw up a popup, whatever...
HandleError("Failed to get data", t.Exception);
return;
}
if (t.Status == TaskStatus.RanToCompletion)
{
bar.WorkOnData(t.Result);
}
});
Not ideal of course, and this is the exact thing that async/await was created to solve. But it does work as a short-term workaround at least for simple uses of await.

Debugging Nunit Tests inside VS2010 Express

I have written a bunch of unit tests inside VS2010 Express and tests being tests they sometimes fail. Since the express editions of VS don't allow plugins to run I can't simply spin up TestDriven.Net or an equivalent and debug the tests. To try and work around this I've converted my test assembly into a console app and made the main method look like this:
class CrappyHackToDebugUnitTestInVSExpress
{
public static void Main()
{
AppDomain.CurrentDomain.ExecuteAssemblyByName(
#"C:\Program Files\NUnit 2.5.5\bin\net-2.0\nunit-console.exe",
new [] { Assembly.GetExecutingAssembly().Location, "/framework:4.0" });
}
}
In theory I should be able to run this up, set break points in my test. If it worked it would be an acceptable work around, but I keep getting the following:
FileLoadException
Could not load file or assembly 'C:\\Program Files\\NUnit 2.5.5\\bin\\net-2.0\\nunit-console.exe'
or one of its dependencies. The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
Now the file exists and when run manually nunit-console runs fine. What might be my problem?
Basically you need to convert your assembly to Windows Forms app, add reference to the nunit-gui-runner.dll assembly and change your Main method to look like this:
[STAThread]
static void Main()
{
NUnit.Gui.AppEntry.Main(new string[] { Assembly.GetExecutingAssembly().Location });
}
here is another example:
...
using NUnit.Gui;
namespace __libs
{
class Program
{
[STAThread]
static void Main(string[] args)
{
NUnit.Gui.AppEntry.Main(new string[] { #"C:\test\bin\Debug\test.exe" });
}
}
}
This will allow you to step into certain tests but is not very good for a red green cycle, so you will want to use this only when debugging and not in other circumstances.
I played with your concept and it appears the issue isn't directly from loading the file, but from dependencies.
I used the following modified code:
And the error was actually a failure to locate nunit.core.dll, which is in the /lib directory.
try
{
String NUnitPath = #"C:\Program Files\NUnit 2.5.7\bin\net-2.0\nunit-console.exe";
AssemblyName asmName = System.Reflection.AssemblyName.GetAssemblyName(NUnitPath);
AppDomain.CurrentDomain.ExecuteAssemblyByName(asmName, new[] { Assembly.GetExecutingAssembly().Location, "/framework:4.0" });
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
Trace.WriteLine(ex.StackTrace);
}
(I like getting System.Reflection.AssemblyName because you can inspect and see that everything's in order verses the raw file path.)
A quick bulk copy (xcopy nunit.*.dll) into my test projects' debug directory and it ran just fine. (It should be trivial to discover the minimal dependencies required)
Tested in VC# 2010 Express with NUnit 2.5.7 (breakpoints work, but I didn't really play with any other options.) Although I'm sure you could make a passable build option from it.
Cheers!
PS - First post here so I'm a bit untested as to getting the 'code' blocks formatted. Sorry in advance..
I had a similar problem trying to debug unit tests in VS C# express. Had a hard time getting it to work properly but then I found out about this project template. Works perfectly in C# Express!
http://visualstudiogallery.msdn.microsoft.com/b8a7a8fa-9f5a-4b9b-8e8b-8839a4364f26?SRC=VSIDE
C# Project Template
Integrated tests with Visual Studio, including Visual C# Express
version
Self contained NUnit console runner. Allow to write test fixtures and
test, running from Visual Studio simply by pressing F5 (support test
debugging), or Ctrl-F5 free run with results in console window. In
case of test failure indicate by beep sound.
Contains essential NUnit modules to start test project. No external
dependencies. Simply create new project, using NUnit Test Application
template.

Resources