Failed to initialize the PowerShell host while installing packages

While trying to install the NEST Nuget package, I got the following error when the JSON.NET post-install powershell script was executed:

Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

I then tried to update the execution policy by executing the following in a PowerShell opened as Administrator:

start-job { Set-ExecutionPolicy Unrestricted } -RunAs32 | wait-job | Receive-Job

Unfortunately, this failed with the following error message:

Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a
more specific scope. Due to the override, your shell will retain its current effective execution policy of
RemoteSigned. Type “Get-ExecutionPolicy -List” to view your execution policy settings. For more information please see
“Get-Help Set-ExecutionPolicy”.
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

I then tried to set it to RemoteSigned instead of Unrestricted:

start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Jobb

This didn’t cause any error but even after restarting Visual Studio I was not able to install JSON.NET.

The only thing that worked was reinstalling the NuGet Package Manager for Visual Studio:

  1. In Tools -> Extensions and Updates, uninstall NuGet Package Manager for Visual Studio
  2. Restart Visual Studio
  3. In Tools -> Extensions and Updates, install NuGet Package Manager for Visual Studio
  4. Restart Visual Studio

And after I could install NEST including JSON.NET!


Analyze your code using NDepend – Part 1

Whether you have to get on-board on an existing .NET project or you want to get an overview of your own project and use a more holistic approach to code improvement, you will quickly reach the limit of the tools provided by default in Visual Studio. Fortunately, Visual Studio (like most major development environment) does provide a good way to extend it and over time quite a few third-party tool vendors have started providing additional functionality for your favorite IDE.

One such tool is NDepend. The goal of NDepend is to first provide you with means to browse and understand your code using better a better visualization than what’s available by default in Visual Studio. But NDepend allows you to go further than that. Let’s have a look at how you can improve your code and manage code improvement using this tool.

Disclaimer: I was asked by the creator of NDepend whether I’d be interested in test driving it and sharing my experience on my blog. But the reason why I accepted writing this article is that NDepend has helped me improve the code quality in one of my project and I feel this is a tool with a lot of potential. I do not work for NDepend neither do I get any financial compensation from them (except for a free license for the tool).

Download and Installation

You can download a trial version of NDepend on their web site. The installation process is pretty straightforward. You download a ZIP file; extract it to some directory and start the installation executable. If you have a license for it, you just need to save the license file to the same directory where you’ve extracted the ZIP file.

During the installation process, the installer will identify which Visual Studio versions (it supports VS 2008 till VS2013) are installed and allow you to install NDepend as an add-in. One thing I really like was that I was able to install it and activate it (over the menu Tools | Add-in manager) with needing to restart Visual Studio.

Once you’ve activated NDepend, a new menu item will be available in your menu bar. A good place to start is the Dashboard.


The Dashboard shows you an overview of all relevant metrics related to your project as well as their evolution over time:

NDepend Dashboard

It shows some general project metrics like:

  • Number of lines of code
  • Number of types
  • Percentage of lines of comment
  • Max and average Method Complexity
  • Code Coverage
  • Usage of assemblies

But also some metrics related to coding rules. These code rules violations are clustered in critical and non-critical rules. All these metrics are available either as a view of the current status or as a graph showing you the evolution over time. Very often, especially when using NDepend on a project, which has already been around for some time, it is not possible to fix all violations at once and it’s important to be able to see whether we’re slowly reducing the number of violations or whether we have a negative dynamic and the number of violations are actually increasing.

All diagrams can be exported to HTML. This makes it easy to incorporate it in external reports about your project. If like me you’re stuck with an older version of Internet Explorer, you might get an almost empty display when looking at the exported web page. You then just have to open it in another browser. It’d be nice if it also worked in IE8 but let’s face it, web technologies keep evolving at a high pace and you can’t really expect anything to work in a browser, which is already more than 5 years old…

Code Rules

One of the most valuable features in NDepend is that all code rules are based on queries on a model. This means that you can adapt them, as you need i.e. in order to change a threshold or consider additional criteria. So you can adapt existing rules (the ones provided with NDepend) but also add your own rule groups and queries. Of course, that’s something you will only be able to use once you’ve invested enough time in learning how NDepends works. But modifying an existing rule is very easy.

Just as an example: There is a rule called “Methods too big”. It basically scans for methods with more than 30 lines of code. Let’s say, you define that in your project, it’s fine having methods of up to 40 lines of code. You can just click on one of the links in the “Code Rules” widget of the Dashboard:

NDepend Dashboard Code Rules

It will open the Queries and Rules Explorer. On the left hand side, you’ll see all rule groups:

NDepend Dashboard Code Rules Groups

There you can also create some groups or delete them. You also immediately see whether any of the rules in a group returned a warning or not. When you click on one of the groups, you’ll see all related queries on the right hand side:

NDepend Dashboard Code Rules queries

Queries can be activated and deactivated. And you can open the queries and rule editor by clicking on one of the queries.

The editor is a split pane, with the query on the top e.g. in the case of “Methods too big” you will see the following code:

// <Name>Methods too big</Name>
warnif count > 0 from m in JustMyCode.Methods where 
   m.NbLinesOfCode > 30
   // We've commented # IL Instructions, because with LINQ syntax, a few lines of code can compile to hundreds of IL instructions.
   // || m.NbILInstructions > 200
   orderby m.NbLinesOfCode descending,
           m.NbILInstructions descending
select new { m, m.NbLinesOfCode, m.NbILInstructions }

// Methods where NbLinesOfCode > 30 or NbILInstructions > 200
// are extremely complex and should be split in smaller methods.
// See the definition of the NbLinesOfCode metric here 

And below you will see where a match was found. You will notice that when the violation occurs in an auto-property setter or getter, it is not possible to jump to this line of code by clicking on the link. When asked, the NDepend support answered that the problem is that the PDB file doesn’t provide this info and hence NDepend doesn’t know about the location. So though I do hope that they find a solution for this in the future, you can work around it by clicking on the type name and navigating to the appropriate location. Since none of us should have types with thousands of lines of code, it is no big deal, right? 😉

All queries I’ve looked into seemed to be very well commented. This made it easy to understand what the rule is about and how to modify it to comply with one’s coding rules.

So in our example, in order to change the threshold for the “Methods too big” query, all you need to do is replace 30 by e.g. 40 and save. Additionally, you can press the “Critical” button to mark this rule as a deal breaker i.e. when called during a build, it will return an error code so that you can refuse to build the software if some critical violations are detected (of course I doubt you’ll use it with a “Method too big” violation).

The NDepend online documentation provides a lot of useful information about the query language. Since it’s based on the C# LINQ syntax, you’ll need to be comfortable with LINQ in order to start working with custom rules. But I guess most developers and architects working with C# are familiar with LINQ anyway…

Trend charts and Baselines

Except for the ability to customize and extend the NDepend rule set, another thing I found very useful is the ability to create and work with trend charts. The ability to create baselines for comparison is also a nice feature related to this topic.

Whenever you start working with static code analysis on a project which has already been around for quite some time, you end up getting a huge list of findings. It’s rarely the case that you can fix them all in the short term. What’s really important is to fix the critical violations and make sure that you first do not introduce more violations as your code evolves and also with every new version try and reduce the number of violations (starting with the most important ones).

Trend Charts

In order to create a trend chart, click on the “Create Trend Chart” button at the top of the Dashboard. The following dialog will appear:

NDepend Create Trend Chart

You can give your new trend chart a name choose which series will be defined and how they should look like. Once you save your new trend chart will be displayed in the dashboard.

A few useful trend charts are already displayed by default in the Dashboard:

  • Lines of Code
  • Rules Violated
  • Rules Violations
  • Percentage Coverage by Tests
  • Maximum complexity, lines of code, number of methods for a type, nesting depth…
  • Average complexity, lines of code, number of methods for a type, nesting depth…
  • Third-Party Usage

Using these trend charts, it’s dead easy to get an overview whether you’re going in the right direction or keep making your software more complex and error-

More about how I use NDepend to analyze and improve my code will come in a follow-up article…


The c# project is targeting “.NET Framework,Version=v4.0”, which is not installed on this machine.

Since I needed some space on my hard disk to install some software I went through the list of installed software and saw that Visual Studio 2010 was installed but I actually only use Visual Studio 2012 (or Visual Studio 2005 for some very old stuff which hasn’t been ported yet). So I thought it makes sense to uninstall Visual Studio 2010. And ended up wasting alot of time…

After uninstalling VS 2010, I started getting the following message in VS2012 whenever I opened a project targeted at the .NET framework v4.0:

The C# project xxx is targeting ‘.NETFramework,Version=v4.0″, which is not installed on this machine. to proceed, you must select an option below.

1.Change the target to .NET Framework 4.5…..

2.Download the targeting pack for “.NET Framework, Version = v4.0″…

3.Do not load the project

When you choose option 2 you are redirected to a web page where you actually cannot download the v4.0 .NET framework. Checking in the registry, I saw that the .NET framework was gone. I also found the installation package for the .NET framework v4.0. Unfortunately, it refuses to install since the v4.5 framework is already installed.

So my next great idea was to uninstall the v4.5 framework. Then I could install the v4.0 version. Of course, after that VS 2012 wouldn’t start anymore. So I installed the v4.5 framework again. During the installation, it told me that it’s an in-place update for the v4.0 framework. I immediately thought that it might cause trouble but didn’t have a choice anyway. After installing the v4.5 framework VS2012 worked again but as expected, I still got the same error message when opening projects targeting the v4.0 framework.

Running out of other options, I finally reinstalled VS2010. It took forever but in the end I was able to open all projects in VS2012.

So this is kind of a waste of space but if you cannot have your project target the v4.5 framework but need to target the v4.0 framework, you will need to have VS2010 installed additionally to VS2012 (even though you actually do not need VS2010).

If anybody has found a solution not requiring VS2010 to stay installed, please leave a comment. My hard disk space is running low and I’d love to be able to get rid of VS2010.

Visual Studio: Upgrading solutions and projects from the command line

I wanted to build some projects created with Visual Studio 2005 on a machine with Visual Studio 2010. While compiling from the command line, I got the following error message:

Solution file 'xxx.sln' is from a previous version of this application and must be converted in order to build in this version of the application. To convert the solution, open the solution in this version of the application.NMAKE : fatal error U1077: 'if' : return code '0x1'

Of course Visual Studio will convert the solution/project when you open it. But I had about 60 projects and didn’t really feel like opening them all. So I looked for a command line solution. There are basically two ways to do it:

  1. Using devenv /upgrade
  2. Using vcupgrade

Here the syntax for devenv /upgrade:

devenv /upgrade xxx.sln

or if you want to convert a project:

devenv /upgrade xxx.vcproj

The problem with devenv /upgrade is that if it finds a .vcxproj file, it will display a popup dialog asking whether it should be overwritten. And there is unfortunately no command line argument to say that you always want to overwrite. So when calling it 60 times in a row, you could end up having to answer this question 60 times in a row.

There is a checkbox in the dialog in order not to be asked again in this session but since a session is a call of devenv /upgrade, it only makes sure that you do not get a message per project in the solution but it doesn’t prevent getting a message per solution.

The solution is to use vcupgrade which does provide such an option:

vcupgrade /overwrite xxx.vcproj

The problem with vcupgrade is that it only works with project files and not solutions.

So if you just want to upgrade projects, you can use vcupgrade. But if you want to upgrade solutions, you are stuck with devenv /upgrade.
Of course you can just delete the .vcxproj if there are any in order not to get the dialog.