Example #1
0
        public void InstallPackagesFromVSExtensionRepository(string extensionId, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions)
        {
            if (String.IsNullOrEmpty(extensionId))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "extensionId");
            }

            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (!packageVersions.Any())
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageVersions");
            }

            PreinstalledRepositoryProvider repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);

            repoProvider.AddFromExtension(_sourceRepositoryProvider, extensionId);

            List <PackageIdentity> toInstall = GetIdentitiesFromDict(packageVersions);

            // Skip assembly references and disable binding redirections should be done together
            bool disableBindingRedirects = skipAssemblyReferences;

            VSAPIProjectContext projectContext = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects);

            PackageManagementHelpers.RunSync(async() => await InstallInternal(project, toInstall, repoProvider, projectContext, ignoreDependencies, CancellationToken.None));
        }
        public void UninstallPackage(Project project, string packageId, bool removeDependencies)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (String.IsNullOrEmpty(packageId))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"));
            }

            PumpingJTF.Run(async delegate
            {
                NuGetPackageManager packageManager =
                    new NuGetPackageManager(
                        _sourceRepositoryProvider,
                        _settings,
                        _solutionManager,
                        _deleteOnRestartManager);

                UninstallationContext uninstallContext = new UninstallationContext(removeDependencies, false);
                VSAPIProjectContext projectContext     = new VSAPIProjectContext();

                // find the project
                NuGetProject nuGetProject = await PackageManagementHelpers.GetProjectAsync(_solutionManager, project, projectContext);

                // uninstall the package
                await packageManager.UninstallPackageAsync(nuGetProject, packageId, uninstallContext, projectContext, CancellationToken.None);
            });
        }
        private async Task <IEnumerable <Packaging.PackageReference> > GetInstalledPackageReferencesAsync(
            Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            var packages = new List <Packaging.PackageReference>();

            if (_solutionManager != null &&
                !string.IsNullOrEmpty(_solutionManager.SolutionDirectory))
            {
                InitializePackageManagerAndPackageFolderPath();

                var nuGetProject = await PackageManagementHelpers.GetProjectAsync(
                    _solutionManager,
                    project,
                    new VSAPIProjectContext());

                var installedPackages = await nuGetProject.GetInstalledPackagesAsync(CancellationToken.None);

                packages.AddRange(installedPackages);
            }

            return(packages);
        }
Example #4
0
        public void RestorePackages(Project project)
        {
            NuGetPackageManager packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, _solutionManager);

            try
            {
                PackageManagementHelpers.RunSync(async() => await _restoreManager.RestoreMissingPackagesInSolutionAsync(CancellationToken.None));
            }
            catch (Exception ex)
            {
                ExceptionHelper.WriteToActivityLog(ex);
            }
        }
        public IEnumerable <IVsPackageMetadata> GetInstalledPackages(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            return(ThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                var packages = new List <IVsPackageMetadata>();

                if (_solutionManager != null &&
                    !string.IsNullOrEmpty(_solutionManager.SolutionDirectory))
                {
                    InitializePackageManagerAndPackageFolderPath();

                    var nuGetProject = await PackageManagementHelpers.GetProjectAsync(
                        _solutionManager,
                        project,
                        new VSAPIProjectContext());

                    var installedPackages = await nuGetProject.GetInstalledPackagesAsync(CancellationToken.None);

                    foreach (var package in installedPackages)
                    {
                        // Get the install path for package
                        string installPath = _packageManager.PackagesFolderNuGetProject.GetInstalledPath(
                            package.PackageIdentity);

                        if (!string.IsNullOrEmpty(installPath))
                        {
                            // normalize the path and take the dir if the nupkg path was given
                            var dir = new DirectoryInfo(installPath);
                            installPath = dir.FullName;
                        }

                        var metadata = new VsPackageMetadata(package.PackageIdentity, installPath);
                        packages.Add(metadata);
                    }
                }

                return packages;
            }));
        }
Example #6
0
        /// <summary>
        /// Core install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternal(Project project, List <PackageIdentity> packages, ISourceRepositoryProvider repoProvider, VSAPIProjectContext projectContext, bool ignoreDependencies, CancellationToken token)
        {
            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = VsHierarchyHelper.GetAllExpandedNodes(_solutionManager);

            try
            {
                DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                bool includePrerelease = false;

                ResolutionContext resolution = new ResolutionContext(depBehavior, includePrerelease, false);

                NuGetPackageManager packageManager = new NuGetPackageManager(repoProvider, _settings, _solutionManager);

                // find the project
                NuGetProject nuGetProject = PackageManagementHelpers.GetProject(_solutionManager, project, projectContext);

                // install the package
                foreach (PackageIdentity package in packages)
                {
                    if (package.Version == null)
                    {
                        if (!_packageServices.IsPackageInstalled(project, package.Id))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package.Id, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                    else
                    {
                        if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToString()))
                        {
                            await packageManager.InstallPackageAsync(nuGetProject, package, resolution, projectContext, repoProvider.GetRepositories(), Enumerable.Empty <SourceRepository>(), token);
                        }
                    }
                }
            }
            finally
            {
                // collapse nodes
                VsHierarchyHelper.CollapseAllNodes(_solutionManager, expandedNodes);
            }
        }
Example #7
0
        private IEnumerable <PackageReference> GetInstalledPackageReferences(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            List <PackageReference> packages = new List <PackageReference>();

            if (_solutionManager != null && !String.IsNullOrEmpty(_solutionManager.SolutionDirectory))
            {
                InitializePackageManagerAndPackageFolderPath();

                var nuGetProject = PackageManagementHelpers.GetProject(_solutionManager, project, new VSAPIProjectContext());
                var task         = System.Threading.Tasks.Task.Run(async() => await nuGetProject.GetInstalledPackagesAsync(CancellationToken.None));
                task.Wait();

                packages.AddRange(task.Result);
            }

            return(packages);
        }
Example #8
0
        public IEnumerable <IVsPackageMetadata> GetInstalledPackages(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            List <IVsPackageMetadata> packages = new List <IVsPackageMetadata>();

            // Debug.Assert(_solutionManager.SolutionDirectory != null, "SolutionDir is null");

            if (_solutionManager != null && !String.IsNullOrEmpty(_solutionManager.SolutionDirectory))
            {
                InitializePackageManagerAndPackageFolderPath();

                var nuGetProject = PackageManagementHelpers.GetProject(_solutionManager, project, new VSAPIProjectContext());
                var task         = System.Threading.Tasks.Task.Run(async() => await nuGetProject.GetInstalledPackagesAsync(CancellationToken.None));
                task.Wait();

                foreach (var package in task.Result)
                {
                    // Get the install path for package
                    string installPath = _packageManager.PackagesFolderNuGetProject.GetInstalledPath(package.PackageIdentity);

                    if (!String.IsNullOrEmpty(installPath))
                    {
                        // normalize the path and take the dir if the nupkg path was given
                        var dir = new DirectoryInfo(installPath);
                        installPath = dir.FullName;
                    }

                    var metadata = new VsPackageMetadata(package.PackageIdentity, installPath);
                    packages.Add(metadata);
                }
            }

            return(packages);
        }
Example #9
0
        private void InstallPackage(string source, Project project, string packageId, NuGetVersion version, bool ignoreDependencies)
        {
            IEnumerable <string> sources = null;

            if (!String.IsNullOrEmpty(source))
            {
                sources = new string[] { source };
            }

            VersionRange versionRange = VersionRange.All;

            if (version != null)
            {
                versionRange = new VersionRange(version, true, version, true);
            }

            List <PackageIdentity> toInstall = new List <PackageIdentity>();

            toInstall.Add(new PackageIdentity(packageId, version));

            VSAPIProjectContext projectContext = new VSAPIProjectContext();

            PackageManagementHelpers.RunSync(async() => await InstallInternal(project, toInstall, GetSources(sources), projectContext, ignoreDependencies, CancellationToken.None));
        }
Example #10
0
        /// <summary>
        /// Installs one or more packages into the specified project.
        /// </summary>
        /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param>
        /// <param name="project">The target project for installation.</param>
        /// <param name="configuration">
        /// The packages to install, where to install them from, and additional options for
        /// their installation.
        /// </param>
        /// <param name="repositorySettings">The repository settings for the packages being installed.</param>
        /// <param name="warningHandler">
        /// An action that accepts a warning message and presents it to the user, allowing
        /// execution to continue.
        /// </param>
        /// <param name="errorHandler">
        /// An action that accepts an error message and presents it to the user, allowing
        /// execution to continue.
        /// </param>
        internal async Task PerformPackageInstallAsync(
            IVsPackageInstaller packageInstaller,
            Project project,
            PreinstalledPackageConfiguration configuration,
            Action <string> warningHandler,
            Action <string> errorHandler)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            string repositoryPath      = configuration.RepositoryPath;
            var    repositorySource    = new Configuration.PackageSource(repositoryPath);
            var    failedPackageErrors = new List <string>();

            // find the project
            var defaultProjectContext = new VSAPIProjectContext();
            var nuGetProject          = await PackageManagementHelpers.GetProjectAsync(_solutionManager, project, defaultProjectContext);

            // For BuildIntegratedNuGetProject, nuget will ignore preunzipped configuration.
            var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;

            var repository = (buildIntegratedProject == null && configuration.IsPreunzipped) ?
                             _sourceProvider.CreateRepository(repositorySource, FeedType.FileSystemUnzipped) :
                             _sourceProvider.CreateRepository(repositorySource);

            var repoProvider = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider);

            repoProvider.AddFromSource(repository);

            var packageManager = _installer.CreatePackageManager(repoProvider);
            var gatherCache    = new GatherCache();

            var sources = repoProvider.GetRepositories().ToList();

            // store expanded node state
            var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager);

            try
            {
                foreach (var package in configuration.Packages)
                {
                    var packageIdentity = new PackageIdentity(package.Id, package.Version);

                    // Does the project already have this package installed?
                    if (_packageServices.IsPackageInstalled(project, package.Id))
                    {
                        // If so, is it the right version?
                        if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString()))
                        {
                            // No? Raise a warning (likely written to the Output window) and ignore this package.
                            warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version));
                        }
                        // Yes? Just silently ignore this package!
                    }
                    else
                    {
                        try
                        {
                            if (InfoHandler != null)
                            {
                                InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version));
                            }

                            // Skip assembly references and disable binding redirections should be done together
                            bool disableBindingRedirects = package.SkipAssemblyReferences;

                            var projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects);

                            // Old templates have hardcoded non-normalized paths
                            projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true;

                            // This runs from the UI thread
                            await _installer.InstallInternalCoreAsync(
                                packageManager,
                                gatherCache,
                                nuGetProject,
                                packageIdentity,
                                sources,
                                projectContext,
                                includePrerelease : false,
                                ignoreDependencies : package.IgnoreDependencies,
                                token : CancellationToken.None);
                        }
                        catch (InvalidOperationException exception)
                        {
                            failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                        }
                        catch (AggregateException aggregateEx)
                        {
                            var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault();
                            if (ex is InvalidOperationException)
                            {
                                failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }

                if (failedPackageErrors.Any())
                {
                    var errorString = new StringBuilder();
                    errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath);
                    errorString.AppendLine();
                    errorString.AppendLine();
                    errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));

                    errorHandler(errorString.ToString());
                }

                // RepositorySettings = null in unit tests
                if (EnvDTEProjectUtility.IsWebSite(project))
                {
                    CreateRefreshFilesInBin(
                        project,
                        repositoryPath,
                        configuration.Packages.Where(p => p.SkipAssemblyReferences));

                    CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
Example #11
0
        /// <summary>
        /// Internal install method. All installs from the VS API and template wizard end up here.
        /// </summary>
        internal async Task InstallInternalAsync(
            Project project,
            List <PackageIdentity> packages,
            ISourceRepositoryProvider repoProvider,
            VSAPIProjectContext projectContext,
            bool includePrerelease,
            bool ignoreDependencies,
            CancellationToken token)
        {
            // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary
            // This method installs multiple packages and can likely take more than a few secs
            // So, go off the UI thread explicitly to improve responsiveness
            await TaskScheduler.Default;

            var gatherCache = new GatherCache();
            var sources     = repoProvider.GetRepositories().ToList();

            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager);

            try
            {
                DependencyBehavior depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest;

                ResolutionContext resolution = new ResolutionContext(
                    depBehavior,
                    includePrerelease,
                    includeUnlisted: false,
                    versionConstraints: VersionConstraints.None);

                var packageManager = CreatePackageManager(repoProvider);

                // find the project
                var nuGetProject = await PackageManagementHelpers.GetProjectAsync(_solutionManager, project, projectContext);

                // install the package
                foreach (PackageIdentity package in packages)
                {
                    // Check if the package is already installed
                    if (package.Version == null)
                    {
                        if (_packageServices.IsPackageInstalled(project, package.Id))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToString()))
                        {
                            continue;
                        }
                    }

                    // Perform the install
                    await InstallInternalCoreAsync(
                        packageManager,
                        gatherCache,
                        nuGetProject,
                        package,
                        sources,
                        projectContext,
                        includePrerelease,
                        ignoreDependencies,
                        token);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
Example #12
0
        /// <summary>
        /// Installs one or more packages into the specified project.
        /// </summary>
        /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param>
        /// <param name="project">The target project for installation.</param>
        /// <param name="configuration">The packages to install, where to install them from, and additional options for their installation.</param>
        /// <param name="repositorySettings">The repository settings for the packages being installed.</param>
        /// <param name="warningHandler">An action that accepts a warning message and presents it to the user, allowing execution to continue.</param>
        /// <param name="errorHandler">An action that accepts an error message and presents it to the user, allowing execution to continue.</param>
        internal void PerformPackageInstall(
            IVsPackageInstaller packageInstaller,
            Project project,
            PreinstalledPackageConfiguration configuration,
            Action <string> warningHandler,
            Action <string> errorHandler)
        {
            string repositoryPath      = configuration.RepositoryPath;
            var    failedPackageErrors = new List <string>();

            LegacyNuGet.IPackageRepository repository = configuration.IsPreunzipped
                                                ? (LegacyNuGet.IPackageRepository) new LegacyNuGet.UnzippedPackageRepository(repositoryPath)
                                                : (LegacyNuGet.IPackageRepository) new LegacyNuGet.LocalPackageRepository(repositoryPath);

            PreinstalledRepositoryProvider repos = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider);

            repos.AddFromRepository(repository);

            // store expanded node state
            IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = VsHierarchyHelper.GetAllExpandedNodes(_solutionManager);

            foreach (var package in configuration.Packages)
            {
                // Does the project already have this package installed?
                if (_packageServices.IsPackageInstalled(project, package.Id))
                {
                    // If so, is it the right version?
                    if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString()))
                    {
                        // No? Raise a warning (likely written to the Output window) and ignore this package.
                        warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version));
                    }
                    // Yes? Just silently ignore this package!
                }
                else
                {
                    try
                    {
                        if (InfoHandler != null)
                        {
                            InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version));
                        }

                        List <PackageIdentity> toInstall = new List <PackageIdentity>();
                        toInstall.Add(new PackageIdentity(package.Id, package.Version));

                        // Skip assembly references and disable binding redirections should be done together
                        bool disableBindingRedirects = package.SkipAssemblyReferences;

                        VSAPIProjectContext projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects);

                        // Old templates have hardcoded non-normalized paths
                        projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true;

                        // This runs from the UI thread
                        PackageManagementHelpers.RunSync(async() => await _installer.InstallInternal(project, toInstall, repos, projectContext, package.IgnoreDependencies, CancellationToken.None));
                    }
                    catch (InvalidOperationException exception)
                    {
                        failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message);
                    }
                    catch (AggregateException aggregateEx)
                    {
                        var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault();
                        if (ex is InvalidOperationException)
                        {
                            failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            if (failedPackageErrors.Any())
            {
                var errorString = new StringBuilder();
                errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath);
                errorString.AppendLine();
                errorString.AppendLine();
                errorString.Append(String.Join(Environment.NewLine, failedPackageErrors));

                errorHandler(errorString.ToString());
            }

            // RepositorySettings = null in unit tests
            if (EnvDTEProjectUtility.IsWebSite(project))
            {
                CreateRefreshFilesInBin(
                    project,
                    repositoryPath,
                    configuration.Packages.Where(p => p.SkipAssemblyReferences));

                CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages);
            }

            // collapse nodes
            VsHierarchyHelper.CollapseAllNodes(_solutionManager, expandedNodes);
        }