Category Archives: Visual Studio

Creating a Visual Studio debug visualizer

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

A Visualizer is a feature where, if you run an app. and whilst debugging you put the mouse over a variable a little debugger popup appears. You have a drop down to display the value in the variable as XML, HTML etc.

  1. Create class lib project
  2. Add references to Microsoft.VisualStudio.DebuggerVisualizers.dll and System.Windows.Forms
using Microsoft.VisualStudio.DebuggerVisualizers;
using System.Windows.Forms;

[
    assembly: System.Diagnostics.DebuggerVisualizer(
        typeof(MyFirstVisualizer.DebuggerSide),
        typeof(VisualizerObjectSource),
        Target = typeof(System.String),
        Description = "My First Visualizer")
]
namespace MyFirstVisualizer
{
    public class DebuggerSide : DialogDebuggerVisualizer
    {
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            MessageBox.Show(objectProvider.GetObject().ToString());
        }

        public static void TestShowVisualizer(object objectToVisualize)
        {
            var visualizerHost = new VisualizerDevelopmentHost(objectToVisualize, typeof(DebuggerSide));
            visualizerHost.ShowVisualizer();
        }
    }
}

TestShowVisualizer allows us to test from a console app

  1. Create console app
  2. Add reference to Microsoft.VisualStudio.DebuggerVisualizers.dll and our project reference
class TestConsole
{
   static void Main(string[] args)
   {
      var myString = "Hello, World";
      DebuggerSide.TestShowVisualizer(myString);
   }
}

To install, copy to

{visual studio deployment folder};\Common7\Packages\Debugger\Visualizers

i.e. C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers

and

MyDocuments\Visual Studio 2015\Visualizers

Creating a VSIX based project template

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

In this post we’re going to create a Prism Project Template using VSIX (as opposed to the File | Export Template option in Visual Studio). This is a relatively simple project template which will create a simple Prism based WPF application, so will demonstrate creating the project template itself along with adding nuget packages etc. and can be used as a starting point for other, more complex Prism based applications.

  • Create New Project
  • Extensibility | VSIX Project
  • Delete index.html and stylesheet.css – no use for our project
  • Add New Project | Extensibility | C# Project Template
  • Double click source.extension.vsixmanifest
  • Select Assets tab
  • New, Type Microsoft.VisualStudio.ProjectTemplate
  • “Source” set to A project in current solution
  • “Project” set to the added C# project template
  • Remove Class1.cs and remove the following line from the vstemplate in the project
    <ProjectItem ReplaceParameters="true" OpenInEditor="true">Class1.cs</ProjectItem>
    
  • From ProjectTemplate.csproj also remove the line
    <Compile Include="Class1.cs" />
    

Now we have an empty class library template (in every sense).

Creating a very basic WPF Project template

  • In ProjectTemplate.csproj change OutputType from Library to WinExe
  • In ProjectTemplate.csproj in the ItemGroup with Reference elements add
    <Reference Include="System.Xaml">
       <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    
  • To the Project template project add new item WPF | User Control(WPF) name it App.xaml
  • Replace the XAML with
    <Application x:Class="$safeprojectname$.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Application.Resources>
        </Application.Resources>
    </Application>
    
  • Change App.xaml.cs to
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace $safeprojectname$
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            protected override void OnStartup(StartupEventArgs e)
            {
                base.OnStartup(e);
            }
        }
    }
    
  • For both files, show the properties (F4) window and set Build Action to None or the compiler will attempt to compile the code
  • Inthe project’s vstemplate add the following within the project element
    <ProjectItem ReplaceParameters="true" OpenInEditor="true">App.xaml</ProjectItem>
    <ProjectItem ReplaceParameters="true" OpenInEditor="true">App.xaml.cs</ProjectItem>
    
  • In the csproj file add the following to the ItemGroup with the line
    >Compile Include=”Properties\AssemblyInfo.cs” /<

        <Compile Include="App.xaml.cs">
          <DependentUpon>App.xaml</DependentUpon>
          <SubType>Code</SubType>
        </Compile>
    
  • Create a new ItemGroup in the csproject with the following
      <ItemGroup>
        <ApplicationDefinition Include="App.xaml">
          <Generator>MSBuild:Compile</Generator>
          <SubType>Designer</SubType>
        </ApplicationDefinition>
      </ItemGroup>
    

Adding Prism

At this point if you try to run this template it should create a valid project but it will not run as there’s no Main entry point. This was on purpose as we don’t need the StartupUri set in the App.xaml.

We’re going to need to load up nuget packages for prism

  • Add the following after the </TemplateContent>
      <WizardExtension>
        <Assembly>NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
        <FullClassName>NuGet.VisualStudio.TemplateWizard</FullClassName>
      </WizardExtension>
      <WizardData>
        <packages repository="extension" repositoryId="productId">
          <package id="Prism.Core" version="6.3.0" />
          <package id="Prism.Wpf" version="6.3.0" />
          <package id="Prism.Unity" version="6.3.0" />
          <package id="Unity" version="4.0.1" />
          <package id="CommonServiceLocator" version="1.3.0" />
        </packages>
      </WizardData>
    

    Replacing the productId with the Product ID from your vsixmanifest

  • In your vsix add a folder named Packages
  • Goto https://www.nuget.org/packages/Prism.Core/ and press download to grab Prism.Core
  • As above for https://www.nuget.org/packages/Prism.Wpf/, https://www.nuget.org/packages/CommonServiceLocator/ and https://www.nuget.org/packages/Unity/
  • Copy/save the nupkg to your new Packages folder
  • Back in Visual Studio select show all files then right mouse click on the nupkg files and select include in project
  • Set the build action to Content in the Properties (F4) view on each file and Copy to output to Copy Always, also set Include in VSIX to True
  • Add the following to the Assets section in the vsixmanifest
        <Asset Type="prism.core.6.3.0.nupkg" d:Source="File" Path="Packages\prism.core.6.3.0.nupkg" d:VsixSubPath="Packages" />
        <Asset Type="prism.unity.6.3.0.nupkg" d:Source="File" Path="Packages\prism.unity.6.3.0.nupkg" d:VsixSubPath="Packages" />
        <Asset Type="prism.wpf.6.3.0.nupkg" d:Source="File" Path="Packages\prism.wpf.6.3.0.nupkg" d:VsixSubPath="Packages" />
        <Asset Type="unity.4.0.1.nupkg" d:Source="File" Path="Packages\unity.4.0.1.nupkg" d:VsixSubPath="Packages" />
        <Asset Type="commonservicelocator.1.3.0.nupkg" d:Source="File" Path="Packages\commonservicelocator.1.3.0.nupkg" d:VsixSubPath="Packages" />
    

Add the Boostrapper

For Prism to work we need to add the boostrapper so in your project template add a new CS file named ShellBootstrapper.cs and as we’re using Unity here, it should look like this

using Microsoft.Practices.Unity;
using Prism.Unity;
using System.Windows;

namespace $safeprojectname$
{
    class ShellBootstrapper : UnityBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void InitializeShell()
        {
            Application.Current.MainWindow.Show();
        }
    }
}

set the Build Action in the properties (F4) window to None. In the csproj add under the other Compile entry

    <Compile Include="ShellBootstrapper.cs" />

We now need a MainWindow, so add a UsecControl.xaml named MainWindow.xaml, set Build Action to None and changed the XAML from UserControl to Window and the same in the cs file, here’s the code

<Window x:Class="$safeprojectname$.MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:cal="http://www.codeplex.com/prism"
             xmlns:local="clr-namespace:$safeprojectname$"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <ItemsControl cal:RegionManager.RegionName="MainRegion" />
</Window>

and the code is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace $safeprojectname$.App
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

add the following in after the last ProjectItem in the vstemplate

      <ProjectItem ReplaceParameters="true" OpenInEditor="true">MainWindow.xaml</ProjectItem>
      <ProjectItem ReplaceParameters="true" OpenInEditor="true">MainWindow.xaml.cs</ProjectItem>
      <ProjectItem ReplaceParameters="true" OpenInEditor="true">ShellBootstrapper.cs</ProjectItem>

Also add to csproj

<Compile Include="MainWindow.xaml.cs">
   <DependentUpon>MainWindow.xaml</DependentUpon>
</Compile>

within the ItemGroup in the template’s csproj that has the None Include App.xaml place

<Page Include="MainWindow.xaml">
   <Generator>MSBuild:Compile</Generator>
   <SubType>Designer</SubType>
</Page>

In the OnStartup of App.xaml.cs add

var bootstrapper = new ShellBootstrapper();
bootstrapper.Run();

If you now run the VSIX from Visual Studio, it should load up the Visual Studio Experimental instance and you should be able to create a project from the template which will build and run successfully.

Editorconfig

When we’re collaborating with other developers, whether you’re writing JavaScript, C~ or whatever, it’s useful (some may say essential) to create a coding style that all developers adhere to. After all, one of the aims of collaboration is that you shouldn’t really be able to tell who wrote what code just by the code style.

With web development it’s not unusual to enforce code style etc. with eslint & prettier but this is often shown as a warning when things are working against the style or in some cases, these changes are only applied upon committing the source code. It’s be much better if we could have the editor automatically work the same, for things like indent styles (for example).

This is where the .editorconfig comes in. A file you should commit with your source code and is supported by Visual Code, Visual Studio, JetBrains IDE’s etc.

I’ll be honest, the main reason I use the .editorconfig is to configure my editors to use the same indent_size. Here’s a basic .editorconfig file

root=true

[*]
indent_size = 2
end_of_line = lf

Visual Code has an extension available named EditorConfig which can be used to generate a bare bones .editorconfig for you. Visual Studio has a file template, just add a new file to your project using the Add | New Item… context menu and search for editorconfig. Selecting the editorconfig (.NET) will populate the .editorconfig with lots of options set for various .NET languages.

If you have an .editorconfig file in the root of your project it will be applied to all sub-folders unless overridden by another .editorconfig in one or more of these folders.

If you want to override some, but not all options within the root .editorconfig then just put those additions/changes in the file and ensure

root = true

exists in the root level file.

As you’d expect the .editorconfig is read top to bottom, hence if you have a duplicate key later on in the file this will override any previous value.

References

EditorConfig
Create portable, custom editor settings with EditorConfig

Converting old style csproj to new style sdk

This tool’s pretty good for converting the old style csproj files to the new SDK style.

Just install using

dotnet tool install --global Project2015To2017.Migrate2019.Tool

Now navigate to where your solution is (that you want to convert) and from the command prompt run

dotnet migrate-2019 wizard "D:\Path\To\My\TestProject.sln"

You’ll be asked if you want to backup things and whether you want to migrate, answer Y to the migrate question (backing up is up to you). This will then locate all the csproj’s in the solution and convert them.

Lost your Resharper keyboard commands in VS2015?

For some reason I lost CTRL+T which I use a lot to find types using Resharper in Visual Studio. Here’s how to get the shortcuts back.

You may only need to do the following

  • Goto Resharper menu item
  • Select Options | Environment, then Keyboard & Menus
  • Press the Apply Scheme button

Now if this works you may have the key combination working again. If not then go the following route

  • From Tools menu, select Options
  • Now select Environment and Keyboard
  • Press the Reset button on the top right and then OK
  • Now, as per the earlier suggestion, goto Resharper menu item
  • Select Options | Environment, then Keyboard & Menus
  • Press the Apply Scheme button

If you now try CTRL+T and the Resharper keyboard mapping dialog appears, select Use Resharper Command and check the Apply to all Resharper shortcuts.

If all goes well (as it did for me) then CTRL+T should be back.

Xamarin and Visual Studio 2015

I’ve used Xamarin Studio in the past, which is a nice enough environment, but I’ve far more experience with Visual Studio as well as having all my dev tools integrated with it (such as Resharper). Now with Microsoft’s purchase of Xamarin I’ve finally got access to Xamarin’s Visual Studio integrations which also means I can target more platforms in a single solution.

Unfortunately things didn’t “just work” out of the box.

I’m going to go through a few of the issues I found getting started with the Visual Studio integration and hopefully provide solutions and where I can I shall detail how I got everything up and running (assuming I actually do get everything up and running).

What versions am I using?

So I’m going to begin by stating what versions I’m using

  • Visual Studio Professional 2015 (version 14.0.25123.00 Update 2) on Windows 10. This version of Visual Studio includes the Xamarin integration.
  • On the Mac I’m running El Capitan and Xamarin Studio Community edition version 5.10.3 (build 51).

Creating a project

I wanted to jump straight into trying out a Cross-Platform Xamarin.Forms project, so from New Project select Cross-Platform, then Blank App (Xamarin.Forms Portable). I named the project XamarinTest1, obviously name yours whatever you like, but I may refer to this project name within this post.

Visual Studio asks me to choose the target and minimum platform versions for my Universal Windows application – I leave the defaults and press OK.

The project template supplies the following

  • Portable class library – uses for the shared/portable code
  • An Android targeted project
  • An iOS targeted project
  • A UWP/Universal Windows targeted project
  • A Windows 8.1 targeted project
  • A Windows phone 8.1 targeted project

Now my normal inclination is to press the Run button and see what happens…

Getting the Android project up and running

The Android project is selected as the Start-up project, but the first problem occurs.

A message box stating, “There were deployment errors. Continue?” appears. It’s only when I check the Output window that I see a more useful message “Please select a valid device before running the application”. It appears that Visual Studio does not know about the Android virtual devices.

Clicking on the Open Android Emulator Manager button showed I did have emulators set-up (if you hit this problem and no emulators exist, add some).

I found that if I restarted Visual Studio and reloaded the project, it then found the emulators and was able to run correctly.

Getting the iOS project up and running

Select the iOS project and right mouse click on it, then select Set as StartUp project.

To run the iOS application we need to have a Mac running with Xamarin Studio installed. Also we need to set the Sharing System Preferences on the Mac.

Invoke using Cmd-Space and search for Remote Login and then Sharing System Preferences. From here we tick the Remote Login option and set access to specific users.

Now run the iOS application in Visual Studio. If all goes well the iOS emulator will run on the Mac via the Xamarin agent and you can now see what it looks like on your chosen iOS device emulator.

Getting UWP project up and running

Select the UWP project and right mouse click on it, then select Set as StartUp project.

If you now run the UWP application you might get a message box with the following error message: “The project ‘XamarinTest1’ needs to be deployed before it can be started.” etc.

As the message box goes onto say, select the configuration manager and locate the UWP project, check the Build and Deploy options.

If all goes well the application should now run correctly.

Getting Windows 8.1 project up and running

Select the Windows 8.1 project and right mouse click on it, then select Set as StartUp project.

This project should simply work, without any changes required.

Getting Windows Phone 8.1 project up and running

Select the Windows Phone 8.1 project and right mouse click on it, then select Set as StartUp project.

You will need the Windows 8.1 Phone emulator running on your machine (if using Windows 10) and this in turn requires the Hyper V virtualization option on the computer’s BIOS turned on.

Running the application will result in you being asked to download/install the emulator if it’s not on your machine. It’s likely you’ll need to reboot upon completion and/or may be asked if your login user should be part of the Hyper V group – which it should. Once everything is installed correctly then you’ll see a Windows phone emulator appear when you run the application.

Conclusions

It’s unfortunate this stuff doesn’t “just work” immediately out of the box, but with a little tweaking/configuring you can get five different projects running against five different device types and now the world of cross platform C# awaits.

Addendum

Part way through writing this document I foolishly decided to update the Android SDK only to find it failed and left my installation in a non-working state. So here’s what I had to do to get the system working again.

  • Android SDK didn’t appear to be available as a separate download, so I had to install Android Studio and download the NDK seperately
  • Once installed I found the folders of the installations very different from my original install so I needed to option Visual Studio’s Tools | Options
  • Select Xamarin | Android Settings
  • Change the JDK, SDK and NDK paths

So it’s not without its pain points, but eventually I had each of the platform targeted projects running.

Setup Powershell to use the Visual Studio paths etc.

This one’s straight off of How I can use PowerShell with the Visual Studio Command Prompt? and it works a treat.

So I amend the $profile file with the following (updated to include VS 2015)

function Set-VsCmd
{
    param(
        [parameter(Mandatory=$true, HelpMessage="Enter VS version as 2010, 2012, 2013, 2015")]
        [ValidateSet(2010,2012,2013,2015)]
        [int]$version
    )
    $VS_VERSION = @{ 2010 = "10.0"; 2012 = "11.0"; 2013 = "12.0"; 2015 = "14.0" }
    if($version -eq 2015)
    {
        $targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\Common7\Tools"
        $vcvars = "VsMSBuildCmd.bat"
    }
    else
    {
        $targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\VC"
        $vcvars = "vcvarsall.bat"
    }
 
    if (!(Test-Path (Join-Path $targetDir $vcvars))) {
        "Error: Visual Studio $version not installed"
        return
    }
    pushd $targetDir
    cmd /c $vcvars + "&set" |
    foreach {
      if ($_ -match "(.*?)=(.*)") {
        Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
      }
    }
    popd
    write-host "`nVisual Studio $version Command Prompt variables set." -ForegroundColor Yellow
}

The previous version (non-VS 2015) is listed below in case it’s still needed

function Set-VsCmd
{
    param(
        [parameter(Mandatory=$true, HelpMessage="Enter VS version as 2010, 2012, or 2013")]
        [ValidateSet(2010,2012,2013)]
        [int]$version
    )
    $VS_VERSION = @{ 2010 = "10.0"; 2012 = "11.0"; 2013 = "12.0" }
    $targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\VC"
    if (!(Test-Path (Join-Path $targetDir "vcvarsall.bat"))) {
        "Error: Visual Studio $version not installed"
        return
    }
    pushd $targetDir
    cmd /c "vcvarsall.bat&set" |
    foreach {
      if ($_ -match "(.*?)=(.*)") {
        Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
      }
    }
    popd
    write-host "`nVisual Studio $version Command Prompt variables set." -ForegroundColor Yellow
}

Another user on the same question of stackoverlow also put forward the idea of simply changing the shortcut that Visual Studio supply to add the & powershell, like this

%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat" & powershell"

My Visual Studio 2012 C++ 32-bit application is “exe is not a valid Win32 application”

I have a C++ application which I’ve just updated to be built using Visual Studio 2012. The original solution was developed in Visual Studio 2010, so I updated the project properties, Configuration Properties | General | Platform Toolset to Visual Studio 2012.

The application is a 32-bit application, everything was built for 32-bit and all worked well on Windows 7, but on Windows XP (which is still used by some of our users) it failed with the “exe is not a valid Win32 application”.

Checking the configuration manager suggested it was indeed a 32-bit application. Running dumpbin /headers app.exe confirmed it definitely was a 32-bit application but XP said no it wasn’t.

Here’s the thing – I hadn’t noticed when setting the Platform Toolset, there was a second option Visual Studio 2012 – Windows XP (v1100_xp).

Changing to this toolset fixed the problem. So 32-bit does not mean 32-bit on all Windows.

Strange white on black numbers during debug in Visual Studio 2015

When running a Universal Windows application in debug mode within Visual Studio 2015 I noticed some “strange” white numbers on a black background adorning my application window (and in the case of a desktop application displayed on the top right of the screen).

It seems these are enabled via the App.xaml.cs file, within the OnLaunched method (the code in some cases may appear in the App() constructor according to the documentation) there’s the following code

#if DEBUG
   if(System.Diagnostics.Debugger.IsAttached)
   {
      this.DebugSettings.EnableFrameRateCounter = true;
   }
#endif

See also DebugSettings.EnableFrameRateCounter property.

As stated within the above link, this causes an overlay of two sets of numbers. Those in the upper left of the screen/Window relate to the application being debugged those in the upper right apply to the overall system.

Basically the left number is the app’s UI frame rate in frames per second and the right number is the CPU usage of the app’s UI thread per frame in milliseconds.

Excluding assemblies from Code Coverage

I regularly run Visual Studio’s code coverage analysis to get an idea of my test coverage, but there’s a lot of code in the project that’s auto generated code and I wanted to turn off the code coverage metrics for these assemblies.

I could look to add the ExcludeFromCodeCoverage attribute as outlined in a previous post “How to exclude code from code coverage” but this is a little laborious when you have many types to add this to and also, in some cases, I do not have control of the code gen tools to apply such attributes after every regeneration of the code – so not exactly ideal.

There is a solution as described in the post Customizing Code Coverage Analysis which allows us to create solution wide file to exclude assemblies from code coverage, I’m going to summarize the steps to create the file here…

Creating the .runsettings file

  • Select your solution in the solution explorer and then right mouse click and select Add | New Item…
  • Select XML File and change the name to your solution name with the .runsettings extension (the name needn’t be the solution name but it’s a good starting point).
  • Now I’ve taken the following from Customizing Code Coverage Analysis but reduced it to the bare minimum, I would suggest you refer to the aforementioned post for a more complete file if you need to use the extra features.
    <?xml version="1.0" encoding="utf-8"?>
    <!-- File name extension must be .runsettings -->
    <RunSettings>
      <DataCollectionRunSettings>
        <DataCollectors>
          <DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
            <Configuration>
              <CodeCoverage>
                <!-- Match assembly file paths: -->
                <ModulePaths>
                  <Include>
                    <ModulePath>.*\.dll$</ModulePath>
                    <!--<ModulePath>.*\.exe$</ModulePath>-->
                  </Include>
                  <Exclude>
                    <ModulePath>.*AutoGenerated.dll</ModulePath>
                    <ModulePath>.*Tests.dll</ModulePath>
                  </Exclude>
                </ModulePaths>
    
                <!-- We recommend you do not change the following values: -->
                <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
                <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
                <CollectFromChildProcesses>True</CollectFromChildProcesses>
                <CollectAspDotNet>False</CollectAspDotNet>
    
              </CodeCoverage>
            </Configuration>
          </DataCollector>
        </DataCollectors>
      </DataCollectionRunSettings>
    </RunSettings>
    

    In the above code you’ll note I’ve included all dll’s using the Regular Expression .*\.dll$ but then gone on to exclude a couple of assemblies.

    Note: If I do NOT include the .* in the exclude module paths I found that the analysis still included those files. So just typing the correct name of the assembly on it’s own failed and I needed the .* for this to work.

  • The include happens first and then the exclude takes place. Hence we can use wildcards in the include then exclude certain assemblies explicitly.
  • Before we can actually use the runsettings we need to tell Visual Studio to use the runsettings. So before you test your changes you need to select the Test menu item then Test Settings followed by Select Test Settings File. Select your runsettings file.

    Note: you can tick/untick the selected file via the same menu option to turn on/off the runsettings file being used

Now I can run code coverage across my code and will see only the assemblies that matter to me.