public async Task TestGetMissingPackagesForSolution_NoPackagesInstalled()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
            {
                var projectA = testSolutionManager.AddNewMSBuildProject();
                var projectB = testSolutionManager.AddNewMSBuildProject();

                var testNuGetProjectContext = new TestNuGetProjectContext();
                var token = CancellationToken.None;

                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                var testSettings             = Configuration.NullSettings.Instance;
                var deleteOnRestartManager   = new TestDeleteOnRestartManager();
                var packageRestoreManager    = new PackageRestoreManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager);

                // Act
                var packagesFromSolution = (await packageRestoreManager.GetPackagesInSolutionAsync(testSolutionManager.SolutionDirectory, token));

                Assert.False(packagesFromSolution.Any());
            }
        }
Exemplo n.º 2
0
 public MonoDevelopPackageRestoreManager(IMonoDevelopSolutionManager solutionManager)
 {
     restoreManager = new PackageRestoreManager(
         solutionManager.CreateSourceRepositoryProvider(),
         solutionManager.Settings,
         solutionManager);
 }
        protected async Task CheckMissingPackagesAsync()
        {
            var solutionDirectory = VsSolutionManager.SolutionDirectory;

            var packages = await PackageRestoreManager.GetPackagesInSolutionAsync(solutionDirectory, CancellationToken.None);

            if (packages.Any(p => p.IsMissing))
            {
                var packageRestoreConsent = new VisualStudio.PackageRestoreConsent(ConfigSettings);
                if (packageRestoreConsent.IsGranted)
                {
                    await TaskScheduler.Default;

                    var result = await PackageRestoreManager.RestoreMissingPackagesAsync(solutionDirectory,
                                                                                         packages,
                                                                                         this,
                                                                                         Token);

                    if (result.Restored)
                    {
                        await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory, CancellationToken.None);

                        return;
                    }
                }

                ErrorHandler.HandleException(
                    new InvalidOperationException(Resources.Cmdlet_MissingPackages),
                    terminating: true,
                    errorId: NuGetErrorId.MissingPackages,
                    category: ErrorCategory.InvalidOperation);
            }
        }
        public async Task TestPackageRestoredEvent()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
            {
                var projectA = testSolutionManager.AddNewMSBuildProject();
                var projectB = testSolutionManager.AddNewMSBuildProject();

                var packageIdentity          = Packages[0];
                var testNuGetProjectContext  = new TestNuGetProjectContext();
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                var testSettings             = Configuration.NullSettings.Instance;
                var resolutionContext        = new ResolutionContext();
                var token = CancellationToken.None;

                var deleteOnRestartManager = new TestDeleteOnRestartManager();
                var nuGetPackageManager    = new NuGetPackageManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager,
                    deleteOnRestartManager);

                await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                              resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                var packageRestoreManager = new PackageRestoreManager(
                    sourceRepositoryProvider,
                    testSettings,
                    testSolutionManager);
                var restoredPackages = new List <PackageIdentity>();
                packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args)
                {
                    if (args.Restored)
                    {
                        restoredPackages.Add(args.Package);
                    }
                };

                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

                // Delete packages folder
                TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

                // Act
                await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                  testNuGetProjectContext,
                                                                                  new TestLogger(),
                                                                                  CancellationToken.None);

                Assert.Equal(1, restoredPackages.Count);
                Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
            }
        }
Exemplo n.º 5
0
        private async Task PerformV2Restore(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: null,
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }
            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload);

                await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    new ConsoleProjectContext(Console),
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }
            }
        }
        public async Task TestCheckForMissingPackages()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomPackageSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var projectA = testSolutionManager.AddNewMSBuildProject();
                    var projectB = testSolutionManager.AddNewMSBuildProject();

                    var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomPackageSourcePath,
                                                                                           packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
                    var testNuGetProjectContext = new TestNuGetProjectContext();
                    var token = CancellationToken.None;

                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectA.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);

                        await projectB.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                    }

                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                    var testSettings             = Configuration.NullSettings.Instance;
                    var deleteOnRestartManager   = new TestDeleteOnRestartManager();
                    var packageRestoreManager    = new PackageRestoreManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager);

                    var packagesMissingEventCount = 0;
                    var packagesMissing           = false;
                    packageRestoreManager.PackagesMissingStatusChanged += delegate(object sender, PackagesMissingStatusEventArgs args)
                    {
                        packagesMissingEventCount++;
                        packagesMissing = args.PackagesMissing;
                    };

                    // Act
                    await packageRestoreManager.RaisePackagesMissingEventForSolutionAsync(testSolutionManager.SolutionDirectory, token);

                    // Assert
                    Assert.Equal(1, packagesMissingEventCount);
                    Assert.False(packagesMissing);

                    // Delete packages folder
                    TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                    // Act
                    await packageRestoreManager.RaisePackagesMissingEventForSolutionAsync(testSolutionManager.SolutionDirectory, token);

                    // Assert
                    Assert.Equal(2, packagesMissingEventCount);
                    Assert.True(packagesMissing);
                }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService().
            // Doing so is illegal and may cause VS to hang.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            _dteEvents = _dte.Events.DTEEvents;
            _dteEvents.OnBeginShutdown += OnBeginShutDown;

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));

            Debug.Assert(webProxy != null);

            var settings = Settings.LoadDefaultSettings(
                _solutionManager == null ? null : _solutionManager.SolutionFileSystem,
                configFileName: null,
                machineWideSettings: MachineWideSettings);
            var packageSourceProvider = new PackageSourceProvider(settings);

            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new VSRequestCredentialProvider(webProxy), packageSourceProvider);

            // when NuGet loads, if the current solution has package
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                if (VsVersionHelper.IsVisualStudio2013)
                {
                    // Run on a background thread in VS2013 to avoid CPS hangs. The modal loading dialog will block
                    // until this completes.
                    ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
                                                                  PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false)));
                }
                else
                {
                    PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
                }
            }

            // when NuGet loads, if the current solution has some package
            // folders marked for deletion (because a previous uninstalltion didn't succeed),
            // delete them now.
            if (SolutionManager.IsSolutionOpen)
            {
                DeleteOnRestart.DeleteMarkedPackageDirectories();
            }
        }
        protected async Task CheckMissingPackagesAsync()
        {
            var solutionDirectory = VsSolutionManager.SolutionDirectory;

            var packages = await PackageRestoreManager.GetPackagesInSolutionAsync(solutionDirectory, CancellationToken.None);

            if (packages.Any(p => p.IsMissing))
            {
                var packageRestoreConsent = new PackageRestoreConsent(ConfigSettings);
                if (packageRestoreConsent.IsGranted)
                {
                    await TaskScheduler.Default;

                    using (var cacheContext = new SourceCacheContext())
                    {
                        var logger = new LoggerAdapter(this);

                        var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                        var downloadContext = new PackageDownloadContext(cacheContext)
                        {
                            ParentId          = OperationId,
                            ExtractionContext = new PackageExtractionContext(
                                PackageSaveMode.Defaultv3,
                                PackageExtractionBehavior.XmlDocFileSaveMode,
                                logger,
                                signedPackageVerifier,
                                SignedPackageVerifierSettings.GetClientPolicy(ConfigSettings, logger))
                        };

                        var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                            solutionDirectory,
                            packages,
                            this,
                            downloadContext,
                            logger,
                            Token);

                        if (result.Restored)
                        {
                            await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory, CancellationToken.None);

                            return;
                        }
                    }
                }

                ErrorHandler.HandleException(
                    new InvalidOperationException(Resources.Cmdlet_MissingPackages),
                    terminating: true,
                    errorId: NuGetErrorId.MissingPackages,
                    category: ErrorCategory.InvalidOperation);
            }
        }
Exemplo n.º 9
0
        private async Task RestoreMissingPackagesInSolutionAsync(string solutionDirectory,
                                                                 IEnumerable <PackageRestoreData> packages,
                                                                 CancellationToken token)
        {
            await TaskScheduler.Default;

            await PackageRestoreManager.RestoreMissingPackagesAsync(solutionDirectory,
                                                                    packages,
                                                                    NuGetProjectContext,
                                                                    token);
        }
Exemplo n.º 10
0
        public async override Task ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            DetermineRestoreMode();
            if (_restoringForSolution && !String.IsNullOrEmpty(SolutionDirectory))
            {
                // option -SolutionDirectory is not valid when we are restoring packages for a solution
                throw new InvalidOperationException(LocalizedResourceManager.GetString("RestoreCommandOptionSolutionDirectoryIsInvalid"));
            }

            string packagesFolderPath       = GetPackagesFolderPath();
            var    packageSourceProvider    = new NuGet.Configuration.PackageSourceProvider(Settings);
            var    sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);
            var    nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, packagesFolderPath);
            HashSet <PackageReference> installedPackageReferences;
            Stopwatch watch = new Stopwatch();

            if (_restoringForSolution)
            {
                watch.Restart();
                installedPackageReferences = GetInstalledPackageReferencesFromSolutionFile(_solutionFileFullPath);
                watch.Stop();
                DisplayExecutedTime(watch.Elapsed, "GetInstalledPackageReferencesFromSolution");
            }
            else
            {
                // By default the PackageReferenceFile does not throw if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                if (!File.Exists(_packagesConfigFileFullPath))
                {
                    string message = String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("RestoreCommandFileNotFound"), _packagesConfigFileFullPath);
                    throw new InvalidOperationException(message);
                }

                watch.Restart();
                installedPackageReferences = GetInstalledPackageReferences(_packagesConfigFileFullPath);
                watch.Stop();
                DisplayExecutedTime(watch.Elapsed, "GetInstalledPackageReferences");
            }

            watch.Restart();
            var missingPackages = PackageRestoreManager.GetMissingPackages(nuGetPackageManager, installedPackageReferences);

            watch.Stop();
            DisplayExecutedTime(watch.Elapsed, "GetMissingPackages");

            watch.Restart();
            // If sourceRepositories parameter below is null, then the sourceRepositories from the SourceRepositoryProvider in NuGetPackageManager will be used
            await PackageRestoreManager.RestoreMissingPackages(nuGetPackageManager, missingPackages, Console, CancellationToken.None,
                                                               packageRestoredEvent : null, sourceRepositories : GetSourceRepositoriesFromSourceSwitch(sourceRepositoryProvider));

            watch.Stop();
            DisplayExecutedTime(watch.Elapsed, "RestorePackages");
        }
        public async Task TestGetMissingPackagesForSolution()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomPackageSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var projectA = testSolutionManager.AddNewMSBuildProject();
                    var projectB = testSolutionManager.AddNewMSBuildProject();

                    var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomPackageSourcePath,
                                                                                           packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
                    var testNuGetProjectContext = new TestNuGetProjectContext();
                    var token = CancellationToken.None;

                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectA.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);

                        await projectB.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                    }

                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                    var testSettings             = Configuration.NullSettings.Instance;
                    var deleteOnRestartManager   = new TestDeleteOnRestartManager();
                    var packageRestoreManager    = new PackageRestoreManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager);

                    // Act
                    var packagesFromSolution = (await packageRestoreManager.GetPackagesInSolutionAsync(testSolutionManager.SolutionDirectory, token));

                    var packagesFromSolutionList        = packagesFromSolution.ToList();
                    var missingPackagesFromSolutionList = packagesFromSolution.Where(p => p.IsMissing).ToList();

                    Assert.Equal(1, packagesFromSolutionList.Count);
                    Assert.Equal(0, missingPackagesFromSolutionList.Count);

                    // Delete packages folder
                    TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                    packagesFromSolution = (await packageRestoreManager.GetPackagesInSolutionAsync(testSolutionManager.SolutionDirectory, token));

                    packagesFromSolutionList        = packagesFromSolution.ToList();
                    missingPackagesFromSolutionList = packagesFromSolution.Where(p => p.IsMissing).ToList();

                    Assert.Equal(1, missingPackagesFromSolutionList.Count);
                }
        }
Exemplo n.º 12
0
        private void CreatePackageManagerControl()
        {
            _container = Initialize();

            // This method is called from MainWindow's constructor. Current thread is the main thread
            var mainThread             = Thread.CurrentThread;
            var synchronizationContext = SynchronizationContext.Current;

            NuGetUIThreadHelper.SetCustomJoinableTaskFactory(mainThread, synchronizationContext);

            Title  = "NuGet Standalone UI";
            Height = 800;
            Width  = 1000;

            var repositoryProvider = new SourceRepositoryProvider(_settings, Repository.Provider.GetVisualStudio());
            var settings           = new DefaultSettings();

            var testSolutionManager = new TestSolutionManager(@"c:\temp\test");

            var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
            //var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
            //var projectC = testSolutionManager.AddProjectKProject("projectK");
            var projectBuildIntegrated = testSolutionManager.AddBuildIntegratedProject("BuildIntProj", NuGetFramework.Parse("net46"));

            var projects = new[] { projectBuildIntegrated };

            var packageRestoreManager = new PackageRestoreManager(
                repositoryProvider,
                settings,
                testSolutionManager);

            var contextFactory = new StandaloneUIContextFactory(
                repositoryProvider,
                testSolutionManager,
                settings,
                packageRestoreManager: packageRestoreManager,
                optionsPage: null);
            var context      = contextFactory.Create(@"c:\temp\test\settings.txt", projects);
            var uiController = _uiServiceFactory.Create(
                context,
                new NuGetUIProjectContext(new StandaloneUILogger(_textBox, _scrollViewer), _sourceControlManagerProvider, _commonOperations));

            var model = new PackageManagerModel(uiController, context, isSolution: false, editorFactoryGuid: Guid.Empty);

            model.SolutionName     = "test solution";
            _packageManagerControl =
                new PackageManagerControl(model, _settings, new SimpleSearchBoxFactory(), vsShell: null);
            layoutGrid.Children.Add(_packageManagerControl);
        }
        protected async Task CheckMissingPackagesAsync()
        {
            var solutionDirectory = await VsSolutionManager.GetSolutionDirectoryAsync();

            var packages = await PackageRestoreManager.GetPackagesInSolutionAsync(solutionDirectory, CancellationToken.None);

            if (packages.Any(p => p.IsMissing))
            {
                var packageRestoreConsent = new PackageRestoreConsent(ConfigSettings);
                if (packageRestoreConsent.IsGranted)
                {
                    await TaskScheduler.Default;

                    using (var cacheContext = new SourceCacheContext())
                    {
                        var logger = new LoggerAdapter(this);

                        var downloadContext = new PackageDownloadContext(cacheContext)
                        {
                            ParentId            = OperationId,
                            ClientPolicyContext = ClientPolicyContext.GetClientPolicy(ConfigSettings, logger)
                        };

                        var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                            solutionDirectory,
                            packages,
                            this,
                            downloadContext,
                            logger,
                            Token);

                        if (result.Restored)
                        {
                            await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory, CancellationToken.None);

                            return;
                        }
                    }
                }

                ErrorHandler.HandleException(
                    new InvalidOperationException(Resources.Cmdlet_MissingPackages),
                    terminating: true,
                    errorId: NuGetErrorId.MissingPackages,
                    category: ErrorCategory.InvalidOperation);
            }
        }
        public RestoreNuGetPackagesInProjectAction(
            DotNetProject project,
            NuGetProject nugetProject,
            IMonoDevelopSolutionManager solutionManager)
        {
            this.project         = project;
            this.nugetProject    = nugetProject;
            this.solutionManager = solutionManager;

            packageManagementEvents = PackageManagementServices.PackageManagementEvents;

            restoreManager = new PackageRestoreManager(
                solutionManager.CreateSourceRepositoryProvider(),
                solutionManager.Settings,
                solutionManager
                );
        }
Exemplo n.º 15
0
        protected static Task <PackageRestoreResult> RestoreNuGetPackages(Solution solution)
        {
            var solutionManager = new MonoDevelopSolutionManager(solution);
            var context         = new FakeNuGetProjectContext {
                LogToConsole = true
            };

            var restoreManager = new PackageRestoreManager(
                solutionManager.CreateSourceRepositoryProvider(),
                solutionManager.Settings,
                solutionManager
                );

            return(restoreManager.RestoreMissingPackagesInSolutionAsync(
                       solutionManager.SolutionDirectory,
                       context,
                       CancellationToken.None));
        }
Exemplo n.º 16
0
        public async Task TestGetMissingPackagesForSolution()
        {
            // Arrange
            var testSolutionManager = new TestSolutionManager();
            var projectA            = testSolutionManager.AddNewMSBuildProject();
            var projectB            = testSolutionManager.AddNewMSBuildProject();

            var packageIdentity         = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var packageFileInfo         = TestPackages.GetLegacyTestPackage(randomPackageSourcePath,
                                                                            packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var token = CancellationToken.None;

            using (var packageStream = packageFileInfo.OpenRead())
            {
                // Act
                await projectA.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);

                await projectB.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
            }

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSettings             = NullSettings.Instance;
            var packageRestoreManager    = new PackageRestoreManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            // Act
            var packageReferencesFromSolution = (await packageRestoreManager.GetPackageReferencesFromSolution(token)).ToList();
            var missingPackagesFromSolution   = (await packageRestoreManager.GetMissingPackagesInSolution(token)).ToList();

            Assert.Equal(2, packageReferencesFromSolution.Count);
            Assert.Equal(0, missingPackagesFromSolution.Count);

            // Delete packages folder
            Directory.Delete(Path.Combine(testSolutionManager.SolutionDirectory, "packages"), recursive: true);

            packageReferencesFromSolution = (await packageRestoreManager.GetPackageReferencesFromSolution(token)).ToList();
            missingPackagesFromSolution   = (await packageRestoreManager.GetMissingPackagesInSolution(token)).ToList();
            Assert.Equal(2, packageReferencesFromSolution.Count);
            Assert.Equal(1, missingPackagesFromSolution.Count);
        }
Exemplo n.º 17
0
        public async Task <bool> UIRestorePackagesAsync(CancellationToken token)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            ShowProgressUI();
            OperationId = Guid.NewGuid();

            try
            {
                PackageRestoreManager.PackageRestoreFailedEvent += PackageRestoreFailedEvent;
                var solutionDirectory = SolutionManager.SolutionDirectory;
                await PackageRestoreManager.RestoreMissingPackagesInSolutionAsync(solutionDirectory,
                                                                                  this,
                                                                                  new LoggerAdapter(this),
                                                                                  token);

                if (RestoreException == null)
                {
                    // when the control is first loaded, check for missing packages
                    await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory, token);
                }
                else
                {
                    ShowErrorUI(RestoreException.Message);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ShowErrorUI(ex.Message);
                return(false);
            }
            finally
            {
                PackageRestoreManager.PackageRestoreFailedEvent -= PackageRestoreFailedEvent;
                RestoreException = null;
            }

            NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageRestoreCompleted);
            return(true);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService().
            // Doing so is illegal and may cause VS to hang.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));

            Debug.Assert(webProxy != null);

            var settings = Settings.LoadDefaultSettings(_solutionManager == null ? null : _solutionManager.SolutionFileSystem);
            var packageSourceProvider = new PackageSourceProvider(settings);

            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new VSRequestCredentialProvider(webProxy), packageSourceProvider);

            // when NuGet loads, if the current solution has package
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
            }

            // when NuGet loads, if the current solution has some package
            // folders marked for deletion (because a previous uninstalltion didn't succeed),
            // delete them now.
            if (SolutionManager.IsSolutionOpen)
            {
                DeleteOnRestart.DeleteMarkedPackageDirectories();
            }
        }
Exemplo n.º 19
0
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (PackageRestoreManager != null)
            {
                NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async delegate
                {
                    try
                    {
                        var solutionDirectory = SolutionManager.SolutionDirectory;

                        // when the control is first loaded, check for missing packages
                        await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        // By default, restore bar is invisible. So, in case of failure of RaisePackagesMissingEventForSolutionAsync, assume it is needed
                        UpdateRestoreBar(packagesMissing: true);
                        var unwrappedException = ExceptionUtility.Unwrap(ex);
                        ShowErrorUI(unwrappedException.Message);
                    }
                });
            }
        }
        private void CreatePackageManagerControl()
        {
            _container = Initialize();

            this.Title = "NuGet Standalone UI";
            Height     = 800;
            Width      = 1000;

            var repositoryProvider = new SourceRepositoryProvider(_settings, Repository.Provider.GetVisualStudio());
            var settings           = new DefaultSettings();

            var testSolutionManager = new TestSolutionManager(@"c:\temp\test");

            var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
            var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
            //var projectC = testSolutionManager.AddProjectKProject("projectK");

            var projects = new NuGetProject[] { projectA, projectB };

            var packageRestoreManager = new PackageRestoreManager(repositoryProvider, settings, testSolutionManager);
            var contextFactory        = new StandaloneUIContextFactory(
                repositoryProvider,
                testSolutionManager,
                settings,
                packageRestoreManager: packageRestoreManager,
                optionsPage: null);
            var context      = contextFactory.Create(@"c:\temp\test\settings.txt", projects);
            var uiController = _uiServiceFactory.Create(
                context,
                new NuGetUIProjectContext(new StandaloneUILogger(_textBox, _scrollViewer), _sourceControlManagerProvider, _commonOperations));

            PackageManagerModel model = new PackageManagerModel(uiController, context);

            model.SolutionName     = "test solution";
            _packageManagerControl = new PackageManagerControl(model, _settings);
            layoutGrid.Children.Add(_packageManagerControl);
        }
Exemplo n.º 21
0
        private async System.Threading.Tasks.Task RestorePackagesInProject(NuGetProject nuGetProject, CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                return;
            }

            var  projectName        = nuGetProject.GetMetadata <string>(NuGetProjectMetadataKeys.Name);
            bool hasMissingPackages = false;

            try
            {
                hasMissingPackages = await PackageRestoreManager.RestoreMissingPackagesAsync(nuGetProject, token);

                WriteLine(hasMissingPackages, error: false);
            }
            catch (Exception ex)
            {
                var exceptionMessage = _msBuildOutputVerbosity >= (int)VerbosityLevel.Detailed ?
                                       ex.ToString() :
                                       ex.Message;
                var message = String.Format(
                    CultureInfo.CurrentCulture,
                    Resources.PackageRestoreFailedForProject, projectName,
                    exceptionMessage);
                WriteLine(VerbosityLevel.Quiet, message);
                ActivityLog.LogError(LogEntrySource, message);
                ShowError(_errorListProvider, TaskErrorCategory.Error,
                          TaskPriority.High, message, hierarchyItem: null);
                WriteLine(hasMissingPackages, error: true);
            }
            finally
            {
                WriteLine(VerbosityLevel.Normal, Resources.PackageRestoreFinishedForProject, projectName);
            }
        }
Exemplo n.º 22
0
        public async Task TestRestoreMissingPackages()
        {
            // Arrange
            var testSolutionManager = new TestSolutionManager();
            var projectA            = testSolutionManager.AddNewMSBuildProject();
            var projectB            = testSolutionManager.AddNewMSBuildProject();

            var packageIdentity          = Packages[0];
            var testNuGetProjectContext  = new TestNuGetProjectContext();
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSettings             = NullSettings.Instance;
            var resolutionContext        = new ResolutionContext();
            var token = CancellationToken.None;

            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            await nuGetPackageManager.InstallPackageAsync(projectA, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            await nuGetPackageManager.InstallPackageAsync(projectB, packageIdentity,
                                                          resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            var packageRestoreManager = new PackageRestoreManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(packageIdentity));

            // Delete packages folder
            Directory.Delete(Path.Combine(testSolutionManager.SolutionDirectory, "packages"), recursive: true);

            Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));

            // Act
            await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(CancellationToken.None);

            Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder((packageIdentity)));
        }
Exemplo n.º 23
0
        private async Task RestorePackagesOrCheckForMissingPackagesAsync(
            string solutionDirectory,
            bool isSolutionAvailable)
        {
            // To be sure, switch to main thread before doing anything on this method
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var waitDialogFactory
                = ServiceLocator.GetGlobalService <SVsThreadedWaitDialogFactory, IVsThreadedWaitDialogFactory>();

            if (string.IsNullOrEmpty(solutionDirectory))
            {
                // If the solution is closed, SolutionDirectory will be unavailable. Just return. Do nothing
                return;
            }

            var packages = await PackageRestoreManager.GetPackagesInSolutionAsync(solutionDirectory,
                                                                                  CancellationToken.None);

            if (IsConsentGranted(Settings))
            {
                CurrentCount = 0;

                if (!packages.Any())
                {
                    if (!isSolutionAvailable &&
                        GetProjectFolderPath().Any(p => CheckPackagesConfig(p.ProjectPath, p.ProjectName)))
                    {
                        MessageHelper.ShowError(_errorListProvider,
                                                TaskErrorCategory.Error,
                                                TaskPriority.High,
                                                NuGet.PackageManagement.VisualStudio.Strings.SolutionIsNotSaved,
                                                hierarchyItem: null);

                        WriteLine(
                            VerbosityLevel.Quiet,
                            NuGet.PackageManagement.VisualStudio.Strings.SolutionIsNotSaved);
                    }

                    // Restore is not applicable, since, there is no project with installed packages
                    return;
                }

                var missingPackagesList = packages.Where(p => p.IsMissing).ToList();
                TotalCount = missingPackagesList.Count;
                if (TotalCount > 0)
                {
                    // Only show the wait dialog, when there are some packages to restore
                    using (var threadedWaitDialogSession = waitDialogFactory.StartWaitDialog(
                               waitCaption: Resources.DialogTitle,
                               initialProgress: new ThreadedWaitDialogProgressData(
                                   Resources.RestoringPackages,
                                   string.Empty,
                                   string.Empty,
                                   isCancelable: true,
                                   currentStep: 0,
                                   totalSteps: 0)))
                    {
                        Token = threadedWaitDialogSession.UserCancellationToken;
                        ThreadedWaitDialogProgress = threadedWaitDialogSession.Progress;

                        // Display the restore opt out message if it has not been shown yet
                        DisplayOptOutMessage();

                        await RestoreMissingPackagesInSolutionAsync(solutionDirectory, packages, Token);

                        // Mark that work is being done during this restore
                        _hasMissingPackages    = true;
                        _displayRestoreSummary = true;
                    }
                }
            }
            else
            {
                // When the user consent is not granted, missing packages may not be restored.
                // So, we just check for them, and report them as warning(s) on the error list window

                using (var twd = waitDialogFactory.StartWaitDialog(
                           waitCaption: Resources.DialogTitle,
                           initialProgress: new ThreadedWaitDialogProgressData(
                               Resources.RestoringPackages,
                               string.Empty,
                               string.Empty,
                               isCancelable: true,
                               currentStep: 0,
                               totalSteps: 0)))
                {
                    CheckForMissingPackages(packages);
                }
            }

            await PackageRestoreManager.RaisePackagesMissingEventForSolutionAsync(solutionDirectory,
                                                                                  CancellationToken.None);
        }
        private async Task <RestoreSummary> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = GetPackagesFolder(packageRestoreInputs);

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);
                return(new RestoreSummary(true));
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount = 0;
            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            CheckRequireConsent();

            var collectorLogger = new CollectorLogger(Console);
            var projectContext  = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(collectorLogger)
            };

            if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
            {
                projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
            }

            var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                packageRestoreContext,
                projectContext);

            return(new RestoreSummary(
                       result.Restored,
                       "packages.config projects",
                       Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),
                       packageSources.Select(x => x.Source),
                       installCount,
                       collectorLogger.Errors.Concat(failedEvents.Select(e => e.Exception.Message))));
        }
        public async Task Test_PackageRestoreFailure_WithRaisedEvents()
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomTestPackageSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
                    var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
                    var projectC = testSolutionManager.AddNewMSBuildProject("projectC");

                    var jQuery144                = Packages[0];
                    var jQueryValidation         = Packages[2];
                    var testNuGetProjectContext  = new TestNuGetProjectContext();
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
                    var testSettings             = Configuration.NullSettings.Instance;
                    var resolutionContext        = new ResolutionContext();
                    var token = CancellationToken.None;

                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);

                    await nuGetPackageManager.InstallPackageAsync(projectA, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    await nuGetPackageManager.InstallPackageAsync(projectB, jQueryValidation,
                                                                  resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

                    var testPackage1 = new PackageIdentity("package1A", new NuGetVersion("1.0.0"));
                    var testPackage2 = new PackageIdentity("package1B", new NuGetVersion("1.0.0"));

                    var packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                           testPackage1.Id, testPackage1.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectB.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage1, packageStream, testNuGetProjectContext, token);
                    }

                    packageFileInfo = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestPackageSourcePath,
                                                                                       testPackage2.Id, testPackage2.Version.ToNormalizedString());
                    using (var packageStream = GetDownloadResult(packageFileInfo))
                    {
                        // Act
                        await projectA.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);

                        await projectC.InstallPackageAsync(testPackage2, packageStream, testNuGetProjectContext, token);
                    }

                    var packageRestoreManager = new PackageRestoreManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager);
                    var restoredPackages = new List <PackageIdentity>();
                    packageRestoreManager.PackageRestoredEvent += delegate(object sender, PackageRestoredEventArgs args) { restoredPackages.Add(args.Package); };

                    var restoreFailedPackages = new ConcurrentDictionary <Packaging.PackageReference, IEnumerable <string> >(new PackageReferenceComparer());
                    packageRestoreManager.PackageRestoreFailedEvent += delegate(object sender, PackageRestoreFailedEventArgs args)
                    {
                        restoreFailedPackages.AddOrUpdate(args.RestoreFailedPackageReference,
                                                          args.ProjectNames,
                                                          (Packaging.PackageReference packageReference, IEnumerable <string> oldValue) => { return(oldValue); });
                    };

                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));

                    // Delete packages folder
                    TestFileSystemUtility.DeleteRandomTestFolder(Path.Combine(testSolutionManager.SolutionDirectory, "packages"));

                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    // Act
                    await packageRestoreManager.RestoreMissingPackagesInSolutionAsync(testSolutionManager.SolutionDirectory,
                                                                                      testNuGetProjectContext,
                                                                                      CancellationToken.None);

                    // Assert
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQuery144));
                    Assert.True(nuGetPackageManager.PackageExistsInPackagesFolder(jQueryValidation));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage1));
                    Assert.False(nuGetPackageManager.PackageExistsInPackagesFolder(testPackage2));

                    Assert.Equal(4, restoredPackages.Count);
                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    Assert.True(restoredPackages.Contains(jQuery144));
                    Assert.True(restoredPackages.Contains(jQueryValidation));
                    Assert.True(restoredPackages.Contains(testPackage1));
                    Assert.True(restoredPackages.Contains(testPackage2));

                    Assert.Equal(2, restoreFailedPackages.Count);

                    // The ordering is not guaranteed and can vary. Do not assert based on that
                    var restoreFailedPackageKeys = restoreFailedPackages.Keys;
                    var testPackage1Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage1)).First();
                    var testPackage1ProjectNames = restoreFailedPackages[testPackage1Key].ToList();

                    Assert.Equal(2, testPackage1ProjectNames.Count);
                    Assert.True(testPackage1ProjectNames.Contains("projectB", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage1ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));

                    var testPackage2Key          = restoreFailedPackageKeys.Where(r => r.PackageIdentity.Equals(testPackage2)).First();
                    var testPackage2ProjectNames = restoreFailedPackages[testPackage2Key].ToList();

                    Assert.Equal(2, testPackage2ProjectNames.Count);
                    Assert.True(testPackage2ProjectNames.Contains("projectA", StringComparer.OrdinalIgnoreCase));
                    Assert.True(testPackage2ProjectNames.Contains("projectC", StringComparer.OrdinalIgnoreCase));
                }
        }
Exemplo n.º 26
0
        private async System.Threading.Tasks.Task RestorePackagesOrCheckForMissingPackages(vsBuildScope scope)
        {
            _msBuildOutputVerbosity = GetMSBuildOutputVerbositySetting(_dte);
            var waitDialogFactory = ServiceLocator.GetGlobalService <SVsThreadedWaitDialogFactory, IVsThreadedWaitDialogFactory>();

            waitDialogFactory.CreateInstance(out _waitDialog);
            var token = CancellationTokenSource.Token;

            try
            {
                if (IsConsentGranted())
                {
                    if (scope == vsBuildScope.vsBuildScopeSolution || scope == vsBuildScope.vsBuildScopeBatch || scope == vsBuildScope.vsBuildScopeProject)
                    {
                        TotalCount = (await PackageRestoreManager.GetMissingPackagesInSolution(token)).ToList().Count;
                        if (TotalCount > 0)
                        {
                            if (_outputOptOutMessage)
                            {
                                _waitDialog.StartWaitDialog(
                                    Resources.DialogTitle,
                                    Resources.RestoringPackages,
                                    String.Empty,
                                    varStatusBmpAnim: null,
                                    szStatusBarText: null,
                                    iDelayToShowDialog: 0,
                                    fIsCancelable: true,
                                    fShowMarqueeProgress: true);
                                WriteLine(VerbosityLevel.Quiet, Resources.PackageRestoreOptOutMessage);
                                _outputOptOutMessage = false;
                            }

                            System.Threading.Tasks.Task waitDialogCanceledCheckTask = System.Threading.Tasks.Task.Run(() =>
                            {
                                // Just create an extra task that can keep checking if the wait dialog was cancelled
                                // If so, cancel the CancellationTokenSource
                                bool canceled = false;
                                try
                                {
                                    while (!canceled && CancellationTokenSource != null && !CancellationTokenSource.IsCancellationRequested && _waitDialog != null)
                                    {
                                        _waitDialog.HasCanceled(out canceled);
                                        // Wait on the cancellation handle for 100ms to avoid checking on the wait dialog too frequently
                                        CancellationTokenSource.Token.WaitHandle.WaitOne(100);
                                    }

                                    CancellationTokenSource.Cancel();
                                }
                                catch (Exception)
                                {
                                    // Catch all and don't throw
                                    // There is a slight possibility that the _waitDialog was set to null by another thread right after the check for null
                                    // So, it could be null or disposed. Just ignore all errors
                                }
                            });

                            System.Threading.Tasks.Task whenAllTaskForRestorePackageTasks =
                                System.Threading.Tasks.Task.WhenAll(SolutionManager.GetNuGetProjects().Select(nuGetProject => RestorePackagesInProject(nuGetProject, token)));

                            await System.Threading.Tasks.Task.WhenAny(whenAllTaskForRestorePackageTasks, waitDialogCanceledCheckTask);

                            // Once all the tasks are completed, just cancel the CancellationTokenSource
                            // This will prevent the wait dialog from getting updated
                            CancellationTokenSource.Cancel();
                        }
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    _waitDialog.StartWaitDialog(
                        Resources.DialogTitle,
                        Resources.RestoringPackages,
                        String.Empty,
                        varStatusBmpAnim: null,
                        szStatusBarText: null,
                        iDelayToShowDialog: 0,
                        fIsCancelable: true,
                        fShowMarqueeProgress: true);
                    CheckForMissingPackages((await PackageRestoreManager.GetMissingPackagesInSolution(token)).ToList());
                }
            }
            finally
            {
                int canceled;
                _waitDialog.EndWaitDialog(out canceled);
                _waitDialog = null;
            }

            await PackageRestoreManager.RaisePackagesMissingEventForSolution(CancellationToken.None);
        }
Exemplo n.º 27
0
        private async Task PerformV2RestoreAsync(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: Console);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }
            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, Console);

                var projectContext = new ConsoleProjectContext(Console)
                {
                    PackageExtractionContext = new PackageExtractionContext(
                        Packaging.PackageSaveMode.Defaultv2,
                        PackageExtractionBehavior.XmlDocFileSaveMode,
                        clientPolicyContext,
                        Console)
                };

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                // Use failure count to determine errors. result.Restored will be false for noop restores.
                if (failedEvents.Count > 0)
                {
                    // Log errors if they exist
                    foreach (var message in failedEvents.Select(e => new RestoreLogMessage(LogLevel.Error, NuGetLogCode.Undefined, e.Exception.Message)))
                    {
                        await Console.LogAsync(message);
                    }

                    throw new ExitCodeException(1);
                }
            }
        }
Exemplo n.º 28
0
        private async Task <IReadOnlyList <RestoreSummary> > PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = Path.GetFullPath(GetPackagesFolder(packageRestoreInputs));

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            // EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as
            // Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the
            // actual V2 restore flow and should match in this preliminary missing packages check.
            var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  EffectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);

                var restoreSummaries = new List <RestoreSummary>();

                ValidatePackagesConfigLockFiles(
                    packageRestoreInputs.PackagesConfigFiles,
                    packageRestoreInputs.ProjectReferenceLookup.Projects,
                    packagesFolderPath,
                    restoreSummaries);

                if (restoreSummaries.Count == 0)
                {
                    restoreSummaries.Add(new RestoreSummary(success: true));
                }

                return(restoreSummaries);
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(Console);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    Packaging.PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

            if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
            {
                projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
            }

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var packageSourceMapping = PackageSourceMapping.GetPackageSourceMapping(Settings);

                var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload, packageSourceMapping)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                IReadOnlyList <IRestoreLogMessage> errors = collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToList();
                var restoreSummaries = new List <RestoreSummary>()
                {
                    new RestoreSummary(
                        result.Restored,
                        "packages.config projects",
                        Settings.GetConfigFilePaths().ToList().AsReadOnly(),
                        packageSources.Select(x => x.Source).ToList().AsReadOnly(),
                        installCount,
                        errors)
                };

                if (result.Restored)
                {
                    ValidatePackagesConfigLockFiles(
                        packageRestoreInputs.PackagesConfigFiles,
                        packageRestoreInputs.ProjectReferenceLookup.Projects,
                        packagesFolderPath,
                        restoreSummaries);
                }

                return(restoreSummaries);
            }
        }
Exemplo n.º 29
0
        private static async Task <RestoreSummary> PerformNuGetV2RestoreAsync(Common.ILogger log, DependencyGraphSpec dgFile, bool noCache, bool disableParallel, bool interactive)
        {
            string globalPackageFolder           = null;
            string repositoryPath                = null;
            string firstPackagesConfigPath       = null;
            IList <PackageSource> packageSources = null;

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            ISettings settings = null;

            foreach (PackageSpec packageSpec in dgFile.Projects.Where(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig))
            {
                var pcRestoreMetadata = (PackagesConfigProjectRestoreMetadata)packageSpec.RestoreMetadata;
                globalPackageFolder = globalPackageFolder ?? pcRestoreMetadata.PackagesPath;
                repositoryPath      = repositoryPath ?? pcRestoreMetadata.RepositoryPath;

                if (packageSources == null)
                {
                    packageSources = new List <PackageSource>();
                    if (!noCache)
                    {
                        if (!string.IsNullOrEmpty(globalPackageFolder) && Directory.Exists(globalPackageFolder))
                        {
                            packageSources.Add(new FeedTypePackageSource(globalPackageFolder, FeedType.FileSystemV3));
                        }
                    }

                    packageSources.AddRange(pcRestoreMetadata.Sources);
                }

                settings = settings ?? Settings.LoadSettingsGivenConfigPaths(pcRestoreMetadata.ConfigFilePaths);

                var packagesConfigPath = Path.Combine(Path.GetDirectoryName(pcRestoreMetadata.ProjectPath), NuGetConstants.PackageReferenceFile);

                firstPackagesConfigPath = firstPackagesConfigPath ?? packagesConfigPath;

                installedPackageReferences.AddRange(GetInstalledPackageReferences(packagesConfigPath, allowDuplicatePackageIds: true, log));
            }

            if (string.IsNullOrEmpty(repositoryPath))
            {
                throw new InvalidOperationException(Strings.RestoreNoSolutionFound);
            }

            PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new CachingSourceProvider(packageSourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, settings, repositoryPath);

            var effectivePackageSaveMode = CalculateEffectivePackageSaveMode(settings);

            var packageSaveMode = effectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  effectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                return(new RestoreSummary(true));
            }
            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { firstPackagesConfigPath },
                                                                         isMissing: true));

            var repositories = sourceRepositoryProvider.GetRepositories().ToArray();

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(log);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: disableParallel
                    ? 1
                    : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            // TODO: Check require consent?
            // NOTE: This feature is currently not working at all. See https://github.com/NuGet/Home/issues/4327
            // CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    packageSaveMode,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

            if (effectivePackageSaveMode != Packaging.PackageSaveMode.None)
            {
                projectContext.PackageExtractionContext.PackageSaveMode = packageSaveMode;
            }

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache = noCache;

                var downloadContext = new PackageDownloadContext(cacheContext, repositoryPath, directDownload: false)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive);

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                return(new RestoreSummary(
                           result.Restored,
                           "packages.config projects",
                           settings.GetConfigFilePaths().ToArray(),
                           packageSources.Select(x => x.Source).ToArray(),
                           installCount,
                           collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToArray()
                           ));
            }
        }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            Styles.Initialize();

            // ***
            // VsNuGetDiagnostics.Initialize(
            //    ServiceLocator.GetInstance<IDebugConsoleController>());

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService().
            // Doing so is illegal and may cause VS to stop responding.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            _dteEvents = _dte.Events.DTEEvents;
            _dteEvents.OnBeginShutdown += OnBeginShutDown;

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));

            Debug.Assert(webProxy != null);

            if (SolutionManager != null)
            {
                SolutionManager.SolutionOpened += (obj, ev) =>
                {
                    _nugetSettings = new NuGetSettings();
                    LoadNuGetSettings();
                };
            }

            // when NuGet loads, if the current solution has package
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                if (VSVersionHelper.IsVisualStudio2013)
                {
                    // Run on a background thread in VS2013 to avoid CPS hangs. The modal loading dialog will block
                    // until this completes.
                    ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
                                                                  PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false)));
                }
                else
                {
                    PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
                }
            }

            _outputConsoleLogger = new OutputConsoleLogger(this);
            _uiProjectContext    = new NuGetUIProjectContext(
                _outputConsoleLogger,
                SourceControlManagerProvider,
                CommonOperations);

            /* ****
             * // when NuGet loads, if the current solution has some package
             * // folders marked for deletion (because a previous uninstalltion didn't succeed),
             * // delete them now.
             * if (SolutionManager.IsSolutionOpen)
             * {
             *  DeleteOnRestart.DeleteMarkedPackageDirectories();
             * } */

            // NOTE: Don't use the exported IPackageRestoreManager for OnBuildPackageRestorer. Exported IPackageRestoreManager also uses 'PackageRestoreManager'
            //       but, overrides RestoreMissingPackages to catch the exceptions. OnBuildPackageRestorer needs to catch the exception by itself to populate error list window
            //       Exported IPackageRestoreManager is used by UI manual restore, Powershell manual restore and by VS extensibility package restore
            // var packageRestoreManagerForOnBuildPackageRestorer = new PackageRestoreManager(SourceRepositoryProvider, Settings, SolutionManager);
            OnBuildPackageRestorer = new OnBuildPackageRestorer(SolutionManager, PackageRestoreManager, this);

            var vsSourceControlTracker = VSSourceControlTracker;

            LoadNuGetSettings();
        }