Runar Ovesen Hjerpbakk

Science-based software development

Visual Studio

Scriptcs IntelliSense in Visual Studio Code

We’ve lately rewritten our build systems at work using scriptcs. Scripts with C# as the language with full access to the rest of .Net. Aka PowerShell as it should have been. This rewrite has been awesome for several reasons:

  • Ease of use: Since we’re a C# shop, writing the build system in scriptcs is both convenient and time saving. I still remember TFS 2012 XAML based builds with dread.
  • Flexibility: The build system is build server agnostic, the same script can be used on Team City, TFS, locally or on any other server
  • Ownership: The build system is now so trivial that every team can easily understand and extend the system when needed. The build system becomes part of the product, not something the other guys do.
  • Server or local? Same, same: The same scripts are used locally and on the server. The previous XAML based builds were an opaque mess.

Read More

XAML Tools in Visual Studio 2015

Blend is recreated in new glory together in Visual Studio 2015. As is the XAML language service. Fast and fluid is the mantra. Roslyn saves the world. Roslyn saves the world.

The XAML designer can now be disabled completely, though it is also more useful, so it’s a tradeoff.

Code Peek is present in the XAML editor as XAML Peek. You can quickly edit your C# while in your XAML editor, complete with Intellisense, refactorings and code actions! Awesome! Thanks Roslyn. Who needs a designer view? Who needs a designer view?

Regions are supported in the XAML editor. It’s maybe more useful there, but I doubt it. If you need regions, you are doing something wrong. Structure your code differently and remember Uncle Bob. Clean! Short! And in your face if it isn’t. Regions are the root of all evil. Regions are the root of all evil.

Right click on any XAML file and you can open it in Blend. Blend is recreated in Visual Studio, but with an additional designer friendly theme. Projects and source control integrations are shared between Blend and Visual Studio. Blend lives! Blend lives! And it's dark! And it's dark!

The visual debugger is a very welcome addition. A UI debugger is now a requirement for modern UI frameworks IMO. The Live Property Editor supports setting arbitrary properties on any visual element, even properties that doesn’t have a value set yet. Blue lines are the defaults, yellow are the margins. Blue lines are the defaults, yellow are the margins.

Killer feature: databinding debugging! In the Live Property Explorer you can search for DataContex and browse the current context. This makes it easy to check if the right context is set or find misspelled properties.

Also awesome is the timeline profiling tools which I covered yesterday in Debugging Performance Issues Using Visual Studio 2015 and XAML Performance: Techniques for Maximizing Universal Windows App Experiences Built with XAML.

XAML views can share the same code behind, making code sharing possible also outside MVVM. But you do use MVVM, right? InitializeComponent can now take a URI to a XAML file as an argument. Adaptive like HTML :) Adaptive like HTML :)

Read More

What’s New in C# 6 and Visual Basic 14

Everybody loves Mads and Dustin. The line was forming even 30 minutes before the session. The first session of the day.

A big year. Began talking publicly about C# 6, released and open sourced Roslyn, released .Net Core libraries and runtime as OSS on GitHub. OSS all the things!

Visual Studio 2015

The C# stack in Visual Studio 2015 has been completely rebuilt. Everything is a little bit better. And shinier. The IDE has stolen most of ReSharper best features and made them available out of the box. This is a good thing and I’m writing these words wearing a ReSharper t-shirt.

Code actions will show previews before you complete them. An improvement over ReSharper’s implementation. Potential conflicts that would come as result of the actions are visualized. Modal dialogues are also used less. Refactoring preview in action. Refactoring preview in action.

Anyone can build code analyzers, and they can even be shipped together with the code the should analyze. For instance, ship analyzers for ImmutableArrays together with Immutable Collections nuget packages.

Language features

Static usings simplify access to static members. Console WriteLine can be called as WriteLine with using static System.Console.

Immutable types are awesome. Auto properties can now be readonly, same as with normal member variables. Only declare getters and you’re set. They can even be initialized directly.

Expression bodied members can skip the return statement and curly brackets, using the lambda arrow instead. Makes for more readable code when dealing with small methods. Thanks for the inspiration F#! Simplify all the things! Simplify all the things!

String.Format can be converted to an interpolated string. Prefix the string with an $ and write your format string. Expressions can be used, not just values.

nameof(whatever) gives you the name of the variable. Useful when creating argument exceptions or in databinding.

Null conditional checks can be written with ?., an inline null check. It even supports indexers. No more foo == null boilerplate!

Object initializers can now initialize to an index, not only members. Focus on the important bits, less cruft. Focus on the important bits, less cruft.

The team became smarter with time, an await can now be used inside catch and finally blocks. It just works!

Exception filtering is supported using the when keyword. Less logic in the catch block.

Debugging experience

Edit and continue is back and works even if you use new language features. You can code freely while stopped at a breakpoint, even create new types. Visual Studio 2015 still gives you Intellisense and the code actions and refactorings works!

Lambdas and LINQ can be used in the watch and immediate windows. Impressive, the language is even useful during debugging.

The C# Essentials is a useful extension, helping you use the new languate features.

Future stuff

A playground without equipment. A playground without equipment.

C# interactive window will be back with full Intellisense. Xamarin and Swift, you’re not alone! Not as feature rich as the Playgrounds of other languages, yet at least. Roadmap is available on GitHub. Though a REPL is still useful without visualizations.

The design notes of C# 7 is on Github. They’re issues tagged as Design Notes. Modern languages have greater potential to help the programmers being more productive and less error prone, such as nullability tracking or tuple types. I love the new open Microsoft. I love the new open Microsoft.

Read More

Using Git in Visual Studio

GitHub is fully intergrated with Visual Studio 2015.

Git is the preferred source control system for modular code bases, but TFS also lives on with both server and local workspaces. Git is the natural evolution of SCMs. Git is the natural evolution of SCMs.

View History is improved in Visual Studio 2015 with a new graphical view. That's nice for people with command line phobia, such as myself. That's nice for people with command line phobia, such as myself.

Sync does a pull, merge and push, all in once.

Commits are immutable, but you can create a new history. This can be restricted in TFS using permissions.

Be mindful of your line endings, use a git attribute file. Default gitattribute and gitignore files are available from github.com.

The average number of commits per push is not surprisingly one.

If you don’t need branches, it’s because merging is too painful in older SCMs. Branches in git are just a pointer to a commit and remains in place in the file system. Thus, feature or personal branches is the way to go. Even if you work alone on a project. There is no magic, only Git. There is no magic, only Git.

Posh-git is a good CLI for git on Windows.

Tags is also a pointer to a commit, but stays in place. Perfect for tagging releases. They can now be created from the History view in Visual Studio 2015.

Phil thinks rebase should be called graphing. Creating a linear history instead of the messy, branched real world. And you can rebase directly from Visual Studio 2015.

Visual Studio 2015 supports graphical merge, even in git. The conflict window only shows the conflicts, not the changes that worked.

Use pull request for merging into master and get a code review at the same time. This is best practice within Microsoft.

Microsoft and GitHub both enforces two factor authentication.

Read More

.Net Compiler Platform (“Roslyn”): Analyzers and the Rise of Code-Aware Libraries

A code-aware library is a library that provides guidance on correct use through embedded tooling and operates on the user’s code in real time.

This is the spiritual successor to FXCop. The most useful rules are already available on nuget. The future is here. The future is here.

The analyzers are also run inside the preview window. Real preview! Real preview!

By installing the C# essentials extension, an analyzer with a code fix project template is available. The boiler plate is a type name checker which checks that all types start with upper case letters. It also supplies an action to camel case the names. Such a project can be debugged, starting a new session of Visual Studio 2015.

Your first decision is what languages the analyzer should support. I recommend C#, off course.

The AnalysisContext contains the state of the analyzer, will be huge. You can write your code at debug time to better understand the content. Thanks edit and continue. “It now actually works”. It's just code :) It's just code :)

For code fixes, a CodeFixContent context is provided. Using async operations to prevent blocking the UI thread.

Roslyn syntax tree visualizer will help with the code generation in the fixes. The Roslyn syntax APIs are immutable.

If your action do not appear in Visual Studio 2015, delete the ComponentModelCache (MEF cache) to force a refresh.

Read More

Debugging Performance Issues Using Visual Studio 2015

Bad performance leads to poor user experience. Continuously evaluate performance during debugging using PerfTips, Memory Tool and CPU graph. Debugging is now useful. Debugging is now useful.

PerfTips shows you the time used between steps. Overhead from debugging is removed from the number. Utilize edit and continue and moving of the instruction pointer to test different implementations without recompiling. This works anywhere you can debug, even remote debugging and while debugging unit tests.

While looking at the CPU graph, look for spikes. It could be one core at 100%.

Memory snapshots are useful while debugging memory problems. It only shows object on the managed heap. After two or more snapshots, these will be compared with each other. The deltas can be visualized, making it easy to find the offending objects. Cycles in the reference graph is automatically detected. Remember to clear your event handlers. Snapshots can also be taken while the application is running, but the object instances can only be inspected if you’re stopped at a breakpoint. Intelligent filtering. Intelligent filtering.

The native debugger can also be enabled, thus showing you native objects in your snapshots.

A garbage collections is simulated before showing the objects in the snapshot.

The timeline tool supports both WPF and Universal Applications. A ListView.GroupStyle disables virtualization in WPF. The Timeline tool is going to be wicked useful. The Timeline tool is going to be wicked useful.

Delay loading of images and other large assets during scrolling, load only when scrolling has stopped.

CPU profiling can be xcopied and used in production in Windows 8 and later.

The Performance Wizard contains more specialized profiling tools.

Read More

Debugger Tips and Tricks for .Net Developers with Microsoft Visual Studio 2015

Debugging is hard, time consuming less fun than writing the program correctly the first time. Thus, I’ve never tried debugging myself. For my readers:

You can start debugging a process directly by using “Step Into” before a process has started. Useful if you don’t know where a programs entry point is.

Return values of methods are now visible in the Locals window. No more local variables created just for debugging purposes.

When you have multiple method calls on a line, you can “Step Into Specific” to choose which method to step into. A timesaver if there ever was one.

Using the Call Stack, you can select a point in the program and “Run to Cursors” to step into that point.

WPF now has its own debugger visualizer. It’s easy writing your own visualizers for your own data structures.

Use the DebuggeDisplay attribute to change your class’ visualization in the debugger. No more unneeded ToString declarations.

Pinning values during debugging also makes them available after debugging has finished. The debugger helps even when it’s not running.

Visual Studio 2015’s debugger now supports lambda expressions, both in the watch windows and in edit and continue. Hello LINQ!

Breakpoints with configured Actions are powerful and can now be created without opening a modal dialog. Progress. Automatic continuation enables advanced logging without littering your code with temporary logging statements.

Break when thrown now has a search box, making it easier to break at the source of exceptions without breaking the F5 key.

Other goodies: Profiling is awesome Profiling is awesome Timings are awesome Timings are awesome My favourite feature of the future My favourite feature of the future Who would want this? Who would want this?

Read More

Maximize Your Coding Productivity for Apps, Devices, and Services with Visual Studio 2015

New SKUs: Community (Free), Professional (everyone else) and Enterprise (supersedes Premium and Ultimate). This is really good news. Ultimate had many useful features which now gets into the hands of more users. I’m looking at you Code Lens.

Xamarin support is now available out of the box. Updates are smaller and more regular.

Signing in to Visual Studio I snow more useful, and you can sync your settings to multiple accounts at the same time. For instance, both your work and personal accounts can share your settings.

Retina-support is here! All icons reworked. Finally! It's hard to create beautiful apps using ugly tools. Finally! It's hard to create beautiful apps using ugly tools.

You can also save and load your window layouts, easily switching between them when moving from a multiple monitor setting to a laptop. Also, pinch to zoom now works as expected.

Peek Definition lets you see definitions in place while reading code. You can also navigate down through the rabbit hole without losing your place in the code. This works with XAML-styles too! See details without losing your place in the code. See details without losing your place in the code.

Code Lens works with all files now, showing source control history for the file. And is available in the Professional edition.

ReSharper light bulb fixes are now properly stolen and multiple fixes are available. Redundant code is dimmed, and fixes can be previewed before you apply them. JetBrains should be proud. These are created using Roslyn analyzers, and both the detection and fixes can be created by third party developers. Such as me!

Code Analysis can now be viewed in the Error List. This is more natural place for such messages, and they can naturally be filtered from regular errors or warnings. All error codes can be clicked, taken you to relevant documentation for that error. Or automagic Bing searches for the error if no documentation exist.

Bing is integrated in the IDE and you can search for code samples based on keywords. Cargo Cult programming has never been so easy.

Read More

Keyboard disabled in Visual Studio 2013

ReSharper 8

Although Visual Studio 2013 is a great IDE, it's even better together with ReSharper.

But not this day.

Eager to get some coding done, I opened my solution ready to work on the worlds best app. I tried typing my ifs, whiles and gotos (not really), but nothing happened. Within this particular solution, Visual Studio stopped responding to keyboard input. Completely. Kind of defeating the purpose of being an IDE.

Turns out Visual Studio was innocent and ReSharper was the culprit. Closing Visual Studio and clearing the ReSharper solution caches solved the problem.

The caches can be found at

C:\Users{User Name}\AppData\Local\JetBrains\ReSharper\v8.2\SolutionCaches\

if you want to delete them manually, or you can use ReSharper's Clear Caches button in ReSharper Options under Environment -> General, section "Caches (effective on solution open/close)".

Read More

No content in Solution Explorer using Visual Studio 2013

After opening Visual Studio 2013 (VS) today, I was greeted with an empty Solution Explorer window. This was strange because I'd opened VS by double clicking my solution-file. My Team Explorer window could not help me either, it just showed:

Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found.

In my previous VS session I had both connected to my Team Foundation 2013 Server (TFS) and worked on this specific solution. What's going on here?

The first law of tech support or troubleshooting is to turn the thing off and on again. VS didn't even manage to close properly and teased me with this friendly message: No exports were found that match the constraint: ContractName Microsoft.Internal.VisualStudio.PlatformUI.ISolutionAttachedCollectionService RequiredTypeIdentity Microsoft.Internal.VisualStudio.PlatformUI.ISolutionAttachedCollectionService  

No exports were found that match the constraint: ContractName Microsoft.Internal.VisualStudio.PlatformUI.ISolutionAttachedCollectionService RequiredTypeIdentity Microsoft.Internal.VisualStudio.PlatformUI.ISolutionAttachedCollectionService  

Googling this message produced a Microsoft Connect report with the following suggestion:

This issue is because of a MEF cache corruption. Installing the feedback extension (or installing any extension) will invalidate the cache causing VS to rebuild it.

That tip actually worked! I uninstalled one of the extensions I never use, restarted VS and my solution opened as i should. I even managed to connect to TFS! I don't understand what really caused this issue, but I suspect the error messages could be more helpful if they tried...

Read More

Debugger.Launch() in Services on Windows 8

I tried debugging (sorry Uncle Bob) a regular Windows service on Windows 8.1 the other day. As so many times before, I started with adding Debugger.Launch() in the beginning of the service, compiled it under Debug, copied the DLLs and started the service.

In Windows 7, the JIT debugger selection popup would then appear, and the correct instance of Visual Studio could be selected to perform the debugging session. This time though, nothing.

As always when nothing happens in Windows, I checked the event viewer.

An unhandled Microsoft .NET Framework exception occurred in WindowsService.Server.exe [6652]. Just-In-Time debugging this exception failed with the following error: The operation attempted is not supported.

Check the documentation index for 'Just-in-time debugging, errors' for more information.

So I did.

The Solution

You need to change a registry key to enable debugging of a Session 0 process (like a windows service) on Windows 8. The Visual Studio JIT Debugger has its AppIDFlags set to APPIDREGFLAGS_IUSERVER_ACTIVATE_IN_CLIENT_SESSION_ONLY (0x20) and APPIDREGFLAGS_IUSERVER_UNMODIFIED_LOGON_TOKEN (0x8), thus preventing debugging.

Change the key to 0x8 by running the following command:

reg add "HKCR\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 8 /f

When your code works and you never want to debug again, restore the default value 0x28 by running:

reg add "HKCR\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 40 /f

Read More

Debugging XSLT in Visual Studio

tl;dr: Check that your XSDs listed under XML -> Schemas... actually exists at their specified locations.

I sometimes dabble in the magical realms of XSLT using Visual Studio to debug and step through the transformation process. I was looking forward to a fun morning of XSLT debugging when the following message appeared in the status bar:

Waiting for parse to complete

And wait I did.

A lot.

The XSLT I was trying to debug had a couple of namespace declarations, and some of them had blue squiggles below. Maybe Visual Studio was trying to tell me something.

I looked under XML -> Schemas... and found the namespaces specified in the XSLT.

XML Schemas

The schemas with warnings in the editor had file locations where no XSD could be found. After removing the offending XSDs and adding them back from their correct locations, the waiting part in Waiting for parse to complete shortened considerably.

Not the most informative message, but the blue squiggles helped me look in the right direction. Still, when the message shows in the status bar, the parser already knows what it is waiting for...

Read More

Value was either too large or too small for a UInt32

While trying to check-in some code to TFS using Visual Studio 2012, I got the following message:

Value was either too large or too small for a UInt32.

The check-in did not continue and this message was all I was left with. In the history of poor error messages, this must rank pretty high.

Value was either too large or too small for a UInt32

As it turns out, the solution was very mundane. For some reason Visual Studio had decided not to save one of my newly edited files, thereby confusing the check-in dialog enough to make it throw this error.

After saving all my open files, the check-in completed successfully.

Developers should remember that error messages are useless if they:

  1. Do not give the user useful insight to what has gone wrong
  2. Do not suggest possible solutions

Sometimes software sucks.

Read More

Message: The agent process was stopped while the test was running.

In the series of fancy behavior from Visual Studio 2012, we turn today to the MSTest test runner.

While trying to run some tests using Test Explorer, some of them started to fail with the following message:

Message: The agent process was stopped while the test was running.

It turns out that this message appears if the test runner itself has stopped working during the test's execution.

Running the test again in debug mode, revealed the culprit:

StackOverflowException

The code under test had thrown a StackOverflowException, but the error message from the test runner wasn't exactly comprehensive. After fixing the cause of the exception, the tests ran smoothly again.

Read More

Enable "Profile Test" in Visual Studio 2012's Test Explorer

If you have Visual Studio (VS) 2012 Enterprise or Ultimate edition, you can right click on any test in the Test Explorer window and start a profiling session for the selected test. However, for me the option to "Profile Test" was greyed out and disabled.

In order to get this feature to work, I needed to delete VS' ComponentModelCache-folder:

%localappdata%\Microsoft\VisualStudio\11.0\ComponentModelCache

After a restart of VS the option was finally enabled:

Intuitive.

Read More

"User-Unhandled" Column Is Missing In Visual Studio's Debug Exceptions Window

Symptom

The Exceptions window under Visual Studio's Debug menu is missing the column User-unhandled. Only the column Thrown is shown.

Debug Exceptions Window

Solution

Go to Debug -> Options And Settings… and check the checkbox named Enable Just My Code.

Debug Options And Settings

The missing column will return.

Debug Exceptions Window Fixed

Cause

Enable Just My Code was enabled by someone, probably you 😉

Read More

Visual Studio 2012 tweaks

Yesterday I installed Visual Studio 2012 (VS 2012). It's an improvement over the 2010 version IMO, especially the performance when running unit tests. I haven't explored all the new stuff by now, but here's a couple of tips so far.

Install Spell Checker

The normal Spell Checker extension available from the online gallery uses the same language as the locale of the current Windows user. This is problematic when you're Norwegian and you still want all your comments and documentation to be in English. Bernhard Richter has forked the extension and updated it for VS 2012. This version uses English (EN-US) as the spell checker language, regardless of locale.

Download English Spell Checker

Extension and Updates

Hide Menu Bar

Even if you ignore the ALL CAPS MENU, the menu bar still takes up space all the time. By installing the Hide Main Menu extension from TOOLS -> Extensions and Updates... the menu bar will remain hidden until you press Alt. This saves space while making the menu bar available when you need it.

Hide Status Bar

I like that VS 2012 finally contains a dark skin out of the box. As nice as it is, it makes the blue status bar stand out even more than it already does in the light theme. I've never found a use for the status bar anyway, so I always disable it using TOOLS -> Options -> Environment -> General.

Extension and Updates

Read More

Exception has been thrown by the target of an invocation

Exception has been thrown by the target of an invocation

This was the message that greeted me when I tried running my tests from Visual Studio 2010 this morning. Changing solution to run other tests did not help, neither did restarting Visual Studio. Next, I tried to run the tests manually using mstest from the command line. The tests ran successfully. How to get the tests running from Visual Studio again?

After a little googling, the Internet presented me with a few suggestions for solving the problem. No one seemed sure of the cause, and I not sure what caused my problem. However, I will present the “solutions” in the order of which I tried them, plus some suggestions that were not necessary in my situation.

1. The number one cause around the web was that Team Explorer was not connected to the Team Foundation Server. In my case, Team Explorer was already connected when the problem first appeared, but I tried to reconnect nevertheless. No luck.

2. Next, I tried to reinstall Team Explorer. This is a quick reinstallation, but it did not solve the problem.

3. My third try was to reset all Visual Studio settings back to defaults. Remember to export your existing settings before you try this. The command is

devenv /resetuserdata

and it will reset Visual Studio back to its original self. This solved the problem and the error message did not reappear when I tried running my tests. The exact cause might never be known, but after a few minutes of customization, I had a fully functional IDE again.

4. The fourth and untried suggestion was to reinstall Visual Studio 2010 SP1…

5. … and finally: reinstall Visual Studio.

Read More

Disable StyleCop Upgrade Dialog

After upgrading StyleCop to version 4.5, an upgrade dialog appears after starting Visual Studio if a newer version of StyleCop is available. This can be annoying if you do not wish to upgrade right then and there, and StyleCop does not appear to give you a choice in this matter. It will continue to bug you every time Visual Studio is opened.

StyleCop new version pop-up

One of the new features of StyleCop 4.5 is that the StyleCop for ReSharper plugin is installed together with StyleCop proper. Thus, it also has its own options tab in the ReSharper options dialog. The check box for disabling the StyleCop upgrade dialog is hiding in almost plane sight.

StyleCop Settings

Untick the check box and you can upgrade StyleCop at your leisure, without a nag-screen.

EDIT: The discussion on CodePlex reveals how we can disable the dialog without ReSharper.
Open regedit and navigate to

HKEY_CURRENT_USER\Software\CodePlex\StyleCop

Here you'll find (at least) three dwords related to the update process:

AutomaticallyCheckForUpdates"=dword:00000001"
AlwaysCheckForUpdatesWhenVisualStudioStarts"=dword:00000001"
DaysBetweenUpdateChecks"=dword:00000002

Setting the value AutomaticallyCheckForUpdates to 0 should disable the update dialog.

Read More