private async Task <Dictionary <Packaging.PackageReference, List <string> > > GetPackagesReferencesDictionaryAsync(CancellationToken token)
        {
            var packageReferencesDict = new Dictionary <Packaging.PackageReference, List <string> >(new PackageReferenceComparer());

            if (!SolutionManager.IsSolutionAvailable)
            {
                return(packageReferencesDict);
            }

            foreach (var nuGetProject in SolutionManager.GetNuGetProjects())
            {
                // skip project k projects and build aware projects
                if (nuGetProject is INuGetIntegratedProject)
                {
                    continue;
                }

                var nuGetProjectName           = NuGetProject.GetUniqueNameOrName(nuGetProject);
                var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);

                foreach (var installedPackageReference in installedPackageReferences)
                {
                    List <string> projectNames = null;
                    if (!packageReferencesDict.TryGetValue(installedPackageReference, out projectNames))
                    {
                        projectNames = new List <string>();
                        packageReferencesDict.Add(installedPackageReference, projectNames);
                    }
                    projectNames.Add(nuGetProjectName);
                }
            }

            return(packageReferencesDict);
        }
        private void Restore(bool forceRestore, bool showOptOutMessage)
        {
            // Reset flags for the final status messsage
            _hasErrors             = false;
            _canceled              = false;
            _hasMissingPackages    = false;
            _displayRestoreSummary = false;
            _hasOptOutBeenShown    = !showOptOutMessage;

            try
            {
                _errorListProvider.Tasks.Clear();
                PackageRestoreManager.PackageRestoredEvent      += PackageRestoreManager_PackageRestored;
                PackageRestoreManager.PackageRestoreFailedEvent += PackageRestoreManager_PackageRestoreFailedEvent;

                var solutionDirectory   = SolutionManager.SolutionDirectory;
                var isSolutionAvailable = SolutionManager.IsSolutionAvailable;

                ThreadHelper.JoinableTaskFactory.Run(async delegate
                {
                    // Get MSBuildOutputVerbosity from _dte
                    _msBuildOutputVerbosity = GetMSBuildOutputVerbositySetting(_dte);

                    // Get the projects from the SolutionManager
                    // Note that projects that are not supported by NuGet, will not show up in this list
                    var projects = SolutionManager.GetNuGetProjects().ToList();

                    // Check if there are any projects that are not INuGetIntegratedProject, that is,
                    // projects with packages.config. If so, perform package restore on them
                    if (projects.Any(project => !(project is INuGetIntegratedProject)))
                    {
                        await RestorePackagesOrCheckForMissingPackagesAsync(
                            solutionDirectory,
                            isSolutionAvailable);
                    }

                    // Call DNU to restore for BuildIntegratedProjectSystem projects
                    var buildEnabledProjects = projects.OfType <BuildIntegratedProjectSystem>();

                    await RestoreBuildIntegratedProjectsAsync(
                        solutionDirectory,
                        buildEnabledProjects.ToList(),
                        forceRestore,
                        isSolutionAvailable);
                }, JoinableTaskCreationOptions.LongRunning);
            }
            finally
            {
                PackageRestoreManager.PackageRestoredEvent      -= PackageRestoreManager_PackageRestored;
                PackageRestoreManager.PackageRestoreFailedEvent -= PackageRestoreManager_PackageRestoreFailedEvent;
            }
        }
Exemple #3
0
        public async Task <IEnumerable <PackageReference> > GetPackageReferencesFromSolution(CancellationToken token)
        {
            List <PackageReference> packageReferences = new List <PackageReference>();

            foreach (var nuGetProject in SolutionManager.GetNuGetProjects())
            {
                // skip project k projects
                if (nuGetProject is ProjectManagement.Projects.ProjectKNuGetProjectBase)
                {
                    continue;
                }

                packageReferences.AddRange(await nuGetProject.GetInstalledPackagesAsync(token));
            }

            return(packageReferences);
        }
Exemple #4
0
        private void BeforeQueryStatusForAddPackageForSolutionDialog(object sender, EventArgs args)
        {
            NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                OleMenuCommand command = (OleMenuCommand)sender;

                // Enable the 'Manage NuGet Packages For Solution' dialog menu
                // a) if the console is NOT busy executing a command, AND
                // b) if the solution exists and not debugging and not building AND
                // c) if the solution is DPL enabled or there are NuGetProjects. This means that there loaded, supported projects
                // Checking for DPL more is a temporary code until we've the capability to get nuget projects
                // even in DPL mode. See https://github.com/NuGet/Home/issues/3711
                command.Enabled = !ConsoleStatus.Value.IsBusy && IsSolutionExistsAndNotDebuggingAndNotBuilding() &&
                                  (SolutionManager.IsSolutionDPLEnabled || SolutionManager.GetNuGetProjects().Any());
            });
        }
Exemple #5
0
        private void BeforeQueryStatusForAddPackageForSolutionDialog(object sender, EventArgs args)
        {
            NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var command = (OleMenuCommand)sender;

                // Enable the 'Manage NuGet Packages For Solution' dialog menu
                // - if the console is NOT busy executing a command, AND
                // - if the solution exists and not debugging and not building AND
                // - if there are NuGetProjects. This means there are loaded, supported projects.
                command.Enabled =
                    IsSolutionExistsAndNotDebuggingAndNotBuilding() &&
                    !ConsoleStatus.Value.IsBusy &&
                    SolutionManager.GetNuGetProjects().Any();
            });
        }
        private void BeforeQueryStatusForPackageRestore(object sender, EventArgs args)
        {
            ThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                OleMenuCommand command = (OleMenuCommand)sender;

                // Enable the 'Restore NuGet Packages' dialog menu
                // a) if the console is NOT busy executing a command, AND
                // b) if the solution exists and not debugging and not building AND
                // c) if there are no NuGetProjects. This means that there no loaded, supported projects
                command.Enabled = !ConsoleStatus.IsBusy && IsSolutionExistsAndNotDebuggingAndNotBuilding() && SolutionManager.GetNuGetProjects().Any();
            });
        }
Exemple #7
0
        private async Task<IVsWindowFrame> CreateDocWindowForSolutionAsync()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsWindowFrame windowFrame = null;
            var solution = await this.GetServiceAsync<IVsSolution>();
            var uiShell = await this.GetServiceAsync<SVsUIShell, IVsUIShell>();
            var windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            if (!SolutionManager.IsSolutionAvailable)
            {
                throw new InvalidOperationException(Resources.SolutionIsNotSaved);
            }

            var projects = SolutionManager.GetNuGetProjects();
            if (!projects.Any())
            {
                // NOTE: The menu 'Manage NuGet Packages For Solution' will be disabled in this case.
                // But, it is possible, that, before NuGetPackage is loaded in VS, the menu is enabled and used.
                // For once, this message will be shown. Once the package is loaded, the menu will get disabled as appropriate
                MessageHelper.ShowWarningMessage(Resources.NoSupportedProjectsInSolution, Resources.ErrorDialogBoxTitle);
                return null;
            }

            // load packages.config. This makes sure that an exception will get thrown if there
            // are problems with packages.config, such as duplicate packages. When an exception
            // is thrown, an error dialog will pop up and this doc window will not be created.
            foreach (var project in projects)
            {
                await project.GetInstalledPackagesAsync(CancellationToken.None);
            }

            var uiController = UIFactory.Create(projects.ToArray());

            var solutionName = (string)_dte.Solution.Properties.Item("Name").Value;

            var model = new PackageManagerModel(
                uiController,
                isSolution: true,
                editorFactoryGuid: GuidList.guidNuGetEditorType)
            {
                SolutionName = solutionName
            };

            var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory;
            var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4;
            var control = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger);
            var windowPane = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI = Guid.Empty;
            var caption = Resx.Label_SolutionNuGetWindowCaption;
            var documentName = _dte.Solution.FullName;

            var ppunkDocView = IntPtr.Zero;
            var ppunkDocData = IntPtr.Zero;
            var hr = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)solution,
                    (uint)VSConstants.VSITEMID.Root,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return windowFrame;
        }
Exemple #8
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);
        }