Skip to content

Instantly share code, notes, and snippets.

@sayedihashimi
Last active July 6, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayedihashimi/65352be3f025ab35e467e72e17afebcf to your computer and use it in GitHub Desktop.
Save sayedihashimi/65352be3f025ab35e467e72e17afebcf to your computer and use it in GitHub Desktop.
how to limit nuget packages and versions to specific ones

Question: How can I ensure that all projects only use a specific set of nuget packages and versions? I'm using VS2017.

The way that I would handle this is to add a (directory.build.targets)[https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build#directorybuildprops-and-directorybuildtargets] to help in this scenario.

The idea is that you will add an msbuild .targets file in the source root named directory.build.targets. In that file you can inject a target to be run before the build starts. For example,

<Target Name="ValidateNuGetPackages" BeforeTargets="Build">
<!--
    do the work here
-->
</Target>

This target will run before the build target for each project that is being built under that directory that it lives in.

You can store the list of allowed NuGet packages in a text file that is easily parsed. Maybe a JSON or CSV file. You should create a custom task, let's call it ValidateNuGetPackages which is passed the following.

  1. Full path to the project file
  2. Full path to the file that contains the list of allowed packages
  3. Boolean property to determine if using a not-allowed package raises an error or warning.

When the task is run it should do the following.

  1. Get the list of allowed packages from the file that contains that info.
  2. It gets the list of used packages from the project. If you want to future proof it, then have it support projects that use packages.config and new SDK style projects which have the packages listed in the project itself.
  3. Compare the used packages/versions with the allowed ones. If a package is being used that is not allowed then an error/warning should be raised.

When creating the task you have essentially two options.

  1. Create a .csproj and author the task there and compile it to a .dll which is then loaded in directory.build.targets
  2. Create an (inline task)[https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-inline-tasks]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment