Category Archives: Visual Studio

Asynchronous Debugging

Everyone who has spent time debugging errors in code that has multiple threads knows the pain of pressing F10 and seeing the cursor jump to a completely different part of the system (that is, everyone who has ever tried to).

There are a few tools in VS2017 that make this process slightly easier; and this post attempts to provide a brief summary. Obviously the examples in this post are massively contrived.

Errors

Let’s start with an error occurring inside a parallel loop. Here’s some code that will cause the error:

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
 
    Parallel.For(1, 10, (i) => RunProcess(i));
 
    Console.ReadLine();
}
 
static void RunProcess(int i)
{
    Task.Delay(500).GetAwaiter().GetResult();
 
    Console.WriteLine($"Running {i}");
 
    if (i == 3) throw new Exception("error");
}

For some reason, I get an error when a few of these threads have started. I need a tool that tells me some details about the local variables in the threads specifically. Enter the Parallel Watch Window:

Launch Parallel Watch Window

Figure 1 – Launch Parallel Watch Window

This gives me a familiar interface, and tells me which thread I’m currently on:

Parallel Watch Window

Figure 2 – Parallel Watch Window

However, what I really want to see is the data local to the thread; what if I put “i” in the “Add Watch” cell:

Add a watch

Figure 3 – Add a watch

As you can see, I have a horizontal list of watch expressions, so I can monitor variables in multiple threads at a time.

Flagging a thread

We know there’s an issue with one of these threads, so one possibility is to flag that thread:

Flagging a thread

Figure 4 – Flagging a thread

Then you can select to show only flagged threads:

Filter flagged threads

Figure 5 – Filter flagged threads

Freezing non-relevant threads

The flags help to only trace the threads that you care about, but if you want to only run the threads that you care about, you can freeze the other threads:

Freeze Thread

Figure 6 – Freeze Thread

Once you’ve frozen a thread, a small pause icon appears, and that thread will stop:

Frozen Thread

Figure 7 – Frozen Thread

In order to freeze other threads, simply highlight all the relevant threads (Ctrl-A) and select Freeze.

It’s worth remembering that you can’t freeze a thread that doesn’t exist yet (so your breakpoint in a Parallel.For loop might only show half the threads).

Manual thread hopping

By using freeze, you can stop the debug message from jumping between threads. You can then manually control this process by simply selecting a thread and “Switch To Frame”:

Figure 8 – Switch to Frame

You can switch to a frozen frame, but as soon as you try to progress, you’ll flip back to the first non-frozen frame (unless you thaw it). The consequence of this is that, it is possible to switch to a frozen frame, freeze all other frames and then press F10 – you’re program will then stop dead.

Stack Trace

In a single threaded application (and in a multi-threaded application), you can always view the stack trace of a given line of executing code. There is also a Parallel Stack trace:

Parallel Stacks

Figure 9 – Parallel Stacks

Selecting any given method will give us the active threads, and allow switching:

Active Threads

Figure 10 – Active Threads

Parallel Stack Trace – Task View

The above view gives you a view of the created threads for your program; but most of the time, you won’t care what threads are created; only the tasks that you’ve spawned (they are not necessarily a 1 – 1 relationship. You can simply switch the view in this window to view Tasks instead:

Task View

Figure 11 – Task View

Tasks & Threads Windows

There is a tool that allows you to view all active, blocked and scheduled tasks:

Tasks Window

Figure 12 – Tasks Window

This allows you to freeze an entire task, switch to a given task, and Freeze All But This:

Freeze All But This

Figure 13 – Freeze All But This

There is an equivalent window for Threads. It is broadly the same idea; however, it does have one feature that the Tasks window does not, and that it the ability to rename a thread:

Rename a Thread

Figure 14 – Rename a Thread

Flags

The other killer feature both of these windows have is the flag feature. Simply flag a thread, switch to it, and then select “Show Only Flagged Threads” (little flag icon). If you now remove the breakpoints, you can step through only your thread or task!

Breakpoints

So, what to do where you have a breakpoint that you might only wish to fire for a single thread? Helpfully, the breakpoints window has a filter feature:

Filter breakpoints on thread Id

Figure 15 – Filter Breakpoints

References

https://msdn.microsoft.com/en-us/library/dd554943.aspx

https://stackoverflow.com/questions/5304752/how-to-debug-a-single-thread-in-visual-studio

Live Testing in Visual Studio 2017

While working on this project, I decided that I would see how useful the new feature of “Live Testing” is for TDD.

Once you’ve created your suite of tests, turning live testing on gives you some interesting information:

As you can see, there are some slight contradictions here in what it’s telling me. The first test is failing, the test for Count has a line (which indicates not covered). However, code lens is telling me there are two covering tests.

My suspicion here is that live testing is being too clever for its own good; for example, looking at the tests themselves, shows that only the first Enqueue statement is covered:

My thoughts are that the engine works out where the test fails, and so, in the case above, it’s telling me that the tests are not running the line of code that tests the Count functionality. What I’m guessing is that this is because the tests are failing before that.

I can prove this by creating a further unit test:

And, indeed, this now shows coverage:

As I start to add the functionality, I can quickly see that the tests are now passing:

Changing the way code is written

The interesting thing here is that is promotes two things:
1. Defined tests – if a test covers more than one thing, it will show as uncovered initially
2. Tests first – obviously, there need to be tests to show test coverage

Caveats

1. Annoyingly, by default, you continually have to opt in for live unit testing. It only starts when you select to “Start” live unit testing, and this must be done each time you launch VS. This is configurable, and can be switched on by default in options:

2. If the build fails, it shows nothing.

3. Live testing is only available in Visual Studio Enterprise.

NUnit

One thing that only occurred to me as notable while I was writing this is that the tests that I’ve written are in NUnit. So the Live Testing clearly works with none MSTests, and probably works with anything that’ll show up in Test Explorer / Code Lens.

References

https://blogs.msdn.microsoft.com/visualstudio/2017/03/09/live-unit-testing-in-visual-studio-2017-enterprise/

Convert a standard C# project into a Unit Test project

I recently (accidentally) created a Unit Test project as a standard C# class library. Although you don’t need to change this to a test library (it basically just gives you the test icon instead of the class icon), I felt that, if I wanted to do this, it shouldn’t require that I delete and recreate the project.

To change the project type

If you open the csproj for a class library, it looks like this (or some of it does):

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{93F28F24-AD9B-4839-8697-6DA48BAB2048}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>MyProject.UnitTests</RootNamespace>
    <AssemblyName>MyProject.UnitTests</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>

All you need to do is add the correct ProjectTypeGuids:

<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

References

https://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs

http://stackoverflow.com/questions/2911565/what-is-the-significance-of-projecttypeguids-tag-in-the-visual-studio-project-fi

Start Two Project Simultaneously

In Investigating message queues with RabbitMQ and ActiveMQ, I came across a problem that I’ve never considered before. Starting two projects at the same time.

The well-known (at least to me) way of doing this was to start the start-up project, and then right-click the second project, and select Start New Instance:

2proj

However, this is laborious when you’re constantly starting both projects. So, the alternative is to right click the solution, and select Set StartUp Projects… :

2proj2

Then you can select to start multiple projects:

2proj3

A small thing, but saves a lot of time.

Now using Visual Studio 14 CTP

I was previously using VS2013, but after running 14 just once, I saw no reason to go back. I thought I’d jot down some notes on my experience of this update. A quick caveat though: VS14 is a CTP, so if you’re thinking about using it to maintain the code for your nuclear reactor, then probably don’t.

Faster

Okay, so this is my perception. I’m working on a personal project on the train to and from work. VS14 loads almost a station before VS2013 did. Now, if that’s not a fair and accurate benchmark, I don’t know what is!

Debugging

One particularly cool feature is that you can see the CPU execution time for previous statement during debugging. Typically, this is a meaninglessly low figure of x milliseconds; but occasionally it shows an unexpectedly high figure.

This can be dangerous, because if you saw a statement that took 30ms, which executed once when the user presses a button in your app, you might think nothing of it… unless all the other statements take 2ms. At this point, you might spend 1/2 hour trying to work out what the bottleneck is. You might even find it: and speed up your app by 28ms.

Refactor

Shift-Alt-F10 on a non-existent method now gives you a preview of what it’s about to do. Possibly not the most useful feature in the world to be honest, but if you want a field and it tries to create a property then you know (obviously, if you’d just read the description of what it will create, that would also tell you). The Using statement tells you where it will create the statement:

preview

However, I can’t find any way you can affect the preview – which would have been a nice feature; for example, say you wanted to create a public field rather than internal; or, you wanted to define a constant and give it a constant value.

Light bulbs now appear next to potential refactoring. One example was an unnecessary using statement I had. It had turned grey; I didn’t understand this until I noticed that a light bulb had appeared next to it, which helpfully informed me that I didn’t need the statement.

Also, code analysis seems to be an opt-in thing now – rather than the previous version which seemed to constantly kidnap whichever tab it was on.

It is still a CTP

Line numbers were turned on in VS2013 and were off in 14.

Add a settings file from another project (VB.NET)

I recently asked this question on Stack Overflow and, although the answer I got was correct, I thought I would write it up so that a clearer explanation was available for when I forget that I asked in the first place.

Here’s the link to the SO question (as I certainly wouldn’t want to claim credit for the solution): http://stackoverflow.com/questions/20427328/sharing-settings-file-between-projects-in-vs2013

I believe that the process for C# is different, and will try to cover that in a future post.

Disclaimer

If you do read the question, you’ll see that it was suggested to create the settings file in a single library and then expose that through a public method. I do agree that this would be the best way to do things. I’m not even saying that the way here is a good way to do things. However, I was in a position where it was the only feasible way to do things, given time constraints and project architecture. I intend, in the future, the refactor, and to have just such a library of settings. If you have time do do this now, or if you haven’t yet created your settings file then I would strongly suggest you go down this route and NOT read on.

Otherwise, read on

Okay, if you’re still reading then you’re either in the same position I was, or you didn’t read the disclaimer.

Adding a Settings file as a link

In the project that you wish to add the settings file, first, delete any existing settings files from inside (or outside) the “My Project” folder. Note that by default, “Show All Files” is turned off, and this can hide the “My Project Folder”, so make sure it’s on:

ShowAllFiles

MySettings

Now that’s deleted, selected the project and select “Add Existing Item”, and in the dialog that appears, find your settings file; then, and this is the important part, select “Ass as Link”:

AddAsLink

Okay, now you have a settings file from another project. Now you need to set the namespace and the custom tool. They should look like this:

SettingsSettings

Finally, you need to manually tell the settings file to generate itself by right-clicking, and selecting “Run Custom Tool”.

Conclusion and Caveat

One of the reasons that this is a bad idea is the last step. Although you are linking to the settings file, you need to manually generate each time.

So, it’s not a good way to do things, but if you need it, it does work.