Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enable NuGet Package Restore in Visual Studio?

People also ask

How do I run a NuGet package restorer?

Restore and Upgrade NuGet packages We recommend using force restore for large projects. It is available in the main menu (Tools | NuGet | NuGet Force Restore) or in the NuGet quick list Alt+Shift+N .

Was not found it might have been deleted since NuGet restore?

It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. Here are some actions you can take to resolve this error: Add the /restore option to your MSBuild.exe command.


It took far too long but I finally found this document on Migrating MSBuild-Integrated solutions to Automatic Package Restore and I was able to resolve the issue using the methods described here.

  1. Remove the '.nuget' solution directory along from the solution
  2. Remove all references to nuget.targets from your .csproj or .vbproj files. Though not officially supported, the document links to a PowerShell script if you have a lot of projects which need to be cleaned up. I manually edited mine by hand so I can't give any feedback regarding my experience with it.

When editing your files by hand, here's what you'll be looking for:

Solution File (.sln)

Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F4AEBB8B-A367-424E-8B14-F611C9667A85}"
ProjectSection(SolutionItems) = preProject
    .nuget\NuGet.Config = .nuget\NuGet.Config
    .nuget\NuGet.exe = .nuget\NuGet.exe
    .nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject

Project File (.csproj / .vbproj)

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

Microsoft has dropped support for the 'Enable NuGet Package Restore' in VS2015 and you need to do some manual changes to either migrate old solutions or add the feature to new solutions. The new feature is described pretty well in NuGet Package Restore.

There is also a migration guide for existing projects (as previously mentioned) here: NuGet Migration Guide

When upgrading:

  1. do not delete the .nuget directory.
  2. Delete the nuget.exe and nuget.targets files.
  3. Leave the nuget.config.
  4. Purge each of the project files of any reference to the NuGet targets by hand. The Powershell script mentioned seemed to do more damage than good.

When creating a new project:

  1. In your Visual Studio 2015 solution, create a Solution Directory called .nuget.

  2. Create an actual directory of the solution directory (where the .sln file lives) and call it .nuget (note that the solution directory is not the same as the actual file system directory even though they have the same name).

  3. Create a file in the .nuget directory called nuget.config.

  4. Add the 'nuget.config' to the solution directory created in step #2.

  5. Place the following text in the nuget.config file:

    <?xml version="1.0" encoding="utf-8"?>
     <configuration>
      <config>
        <add key="repositorypath" value="$\..\..\..\..\Packages" />
      </config>
      <solution>
        <add key="disableSourceControlIntegration" value="true" />
      </solution>
    </configuration>
    

This configuration file will allow you to consolidate all your packages in a single place so you don't have 20 different copies of the same package floating around on your file system. The relative path will change depending on your solution directory architecture but it should point to a directory common to all your solutions.

You need to restart visual studio after doing step 5. Nuget won't recognize the changes until you do so.

Finally, you may have to use the 'Nuget Package Manager for Solutions' to uninstall and then re-install the packages. I don't know if this was a side-effect of the Powershell script I ran or just a method to kick NuGet back into gear. Once I did all these steps, my complicated build architecture worked flawlessly at bringing down new packages when I checked projects out of TFVC.


As already mentioned by Mike, there is no option 'Enable NuGet Package Restore' in VS2015. You'll have to invoke the restore process manually. A nice way - without messing with files and directories - is using the NuGet Package Management Console: Click into the 'Quick start' field (usually in the upper right corner), enter console, open the management console, and enter command:

Update-Package –reinstall

This will re-install all packages of all projects in your solution. To specify a single project, enter:

Update-Package –reinstall -ProjectName MyProject

Of course this is only necessary when the Restore button - sometimes offered by VS2015 - is not available. More useful update commands are listed and explained here: https://docs.microsoft.com/en-us/nuget/consume-packages/reinstalling-and-updating-packages


Optionally you can remove all folders from "packages" folder and select "Manage NuGet Packages for Solution...". In this case "Restore" button appears on NuGet Packages Windows.


If you have any problems or are missing any packages you can simply right-click in your project and select "Manage NuGet Packages for Solution...". After clicking on this a screen will open where you see a menu bar saying "Restore": Restore

Click on it and the required packages will be installed automatically.
I believe this is what you're looking for, this solved my problems.


Use this command to restore all packages

dotnet restore

When upgrading projects with nuget packages from Vx20XX to VS2015, you might have a problem with nuget packages.

Example of error message: This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.

Update 2016-02-06: I had a link to the information but it does not work anymore. I suspect that a recent path has solved the problem ???

I fixed my problem writing a little program that do MSBuild-Integrated package restore vs. Automatic Package Restore

You can download executable of the tool here.

Please let me know the result :-) !

enter image description here

Code as reference:

<Window x:Class="FixNuGetProblemsInVs2015.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FixNuGetProblemsInVs2015"
        mc:Ignorable="d"
        Title="Fix NuGet Packages problems in Visual Studio 2015 (By Eric Ouellet)" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="10"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Grid.Column="0">Root directory of projects</TextBlock>
        <Grid Grid.Row="0" Grid.Column="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <TextBox Grid.Column="0" Name="DirProjects"></TextBox>
            <Button Grid.Column="1" VerticalAlignment="Bottom" Name="BrowseDirProjects" Click="BrowseDirProjectsOnClick">Browse...</Button>
        </Grid>

        <!--<TextBlock Grid.Row="1" Grid.Column="0">Directory of NuGet Packages</TextBlock>
        <Grid Grid.Row="1" Grid.Column="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <TextBox Grid.Column="0" Name="DirPackages"></TextBox>
            <Button Grid.Column="1"  Name="BrowseDirPackages" Click="BrowseDirPackagesOnClick">Browse...</Button>
        </Grid>-->

        <TextBox Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Name="TxtLog" IsReadOnly="True"></TextBox>

        <Button Grid.Row="3" Grid.Column="0" Click="ButtonRevertOnClick">Revert back</Button>
        <Button Grid.Row="3" Grid.Column="2" Click="ButtonFixOnClick">Fix</Button>
    </Grid>
</Window>


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
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.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;

/// <summary>
/// Applying recommanded modifications in section : "MSBuild-Integrated package restore vs. Automatic Package Restore"
/// of : http://docs.nuget.org/Consume/Package-Restore/Migrating-to-Automatic-Package-Restore
/// </summary>

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

            DirProjects.Text = @"c:\prj";
            // DirPackages.Text = @"C:\PRJ\NuGetPackages";
        }

        private void BrowseDirProjectsOnClick(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.SelectedPath = DirProjects.Text;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DirProjects.Text = dlg.SelectedPath;
            }
        }

        //private void BrowseDirPackagesOnClick(object sender, RoutedEventArgs e)
        //{
        //  FolderBrowserDialog dlg = new FolderBrowserDialog();
        //  dlg.SelectedPath = DirPackages.Text;
        //  if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //  {
        //      DirPackages.Text = dlg.SelectedPath;
        //  }
        //}

        // private string _dirPackages;

        private void ButtonFixOnClick(object sender, RoutedEventArgs e)
        {
            DoJob(false);
        }

        private void ButtonRevertOnClick(object sender, RoutedEventArgs e)
        {
            DoJob(true);
        }

        private void DoJob(bool revert = false)
        {
            TxtLog.Text = "";

            string dirProjects = DirProjects.Text;
            // _dirPackages = DirPackages.Text;

            if (!Directory.Exists(dirProjects))
            {
                MessageBox.Show("Projects directory does not exists: " + dirProjects);
                return;
            }

            //if (!Directory.Exists(_dirPackages))
            //{
            //  MessageBox.Show("Packages directory does not exists: " + _dirPackages);
            //  return;
            //}

            RecurseFolder(dirProjects, revert);
        }

        private void RecurseFolder(string dirProjects, bool revert = false)
        {
            if (revert)
            {
                Revert(dirProjects);
            }
            else
            {
                FixFolder(dirProjects);
            }

            foreach (string subfolder in Directory.EnumerateDirectories(dirProjects))
            {
                RecurseFolder(subfolder, revert);
            }
        }

        private const string BackupSuffix = ".fix_nuget_backup";

        private void Revert(string dirProject)
        {
            foreach (string filename in Directory.EnumerateFiles(dirProject))
            {
                if (filename.ToLower().EndsWith(BackupSuffix))
                {
                    string original = filename.Substring(0, filename.Length - BackupSuffix.Length);
                    if (File.Exists(original))
                    {
                        File.Delete(original);                                          
                    }
                    File.Move(filename, original);
                    Log("File reverted: " + filename + " ==> " + original);
                }
            }
        }

        private void FixFolder(string dirProject)
        {
            BackupFile(System.IO.Path.Combine(dirProject, "nuget.targets"));
            BackupFile(System.IO.Path.Combine(dirProject, "nuget.exe"));

            foreach (string filename in Directory.EnumerateFiles(dirProject))
            {
                if (filename.ToLower().EndsWith(".csproj"))
                {
                    FromProjectFileRemoveNugetTargets(filename);
                }
            }
        }

        private void BackupFile(string path)
        {
            if (File.Exists(path))
            {
                string backup = path + BackupSuffix;
                if (!File.Exists(backup))
                {
                    File.Move(path, backup);
                    Log("File backup: " + backup);
                }
                else
                {
                    Log("Project has already a backup: " + backup);
                }
            }
        }

        private void FromProjectFileRemoveNugetTargets(string prjFilename)
        {
            XDocument xml = XDocument.Load(prjFilename);

            List<XElement> elementsToRemove = new List<XElement>();

            foreach (XElement element in xml.Descendants())
            {
                if (element.Name.LocalName == "Import")
                {
                    var att = element.Attribute("Project");
                    if (att != null)
                    {
                        if (att.Value.Contains("NuGet.targets"))
                        {
                            elementsToRemove.Add(element);
                        }
                    }
                }

                if (element.Name.LocalName == "Target")
                {
                    var att = element.Attribute("Name");
                    if (att != null && att.Value == "EnsureNuGetPackageBuildImports")
                    {
                        elementsToRemove.Add(element);
                    }
                }
            }

            if (elementsToRemove.Count > 0)
            {
                elementsToRemove.ForEach(element => element.Remove());
                BackupFile(prjFilename);
                xml.Save(prjFilename);
                Log("Project updated: " + prjFilename);
            }
        }

        private void Log(string msg)
        {
            TxtLog.Text += msg + "\r\n";
        }

    }
}