Exemplo n.º 1
0
        /// <summary>
        /// Creates a repo provider for the given sources. If null is passed all sources will be returned.
        /// </summary>
        private ISourceRepositoryProvider GetSources(IEnumerable <string> sources)
        {
            ISourceRepositoryProvider provider = null;

            // add everything enabled if null
            if (sources == null)
            {
                // Use the default set of sources
                provider = _sourceRepositoryProvider;
            }
            else
            {
                // Create a custom source provider for the VS API install
                var customProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);

                // Create sources using the given set of sources
                foreach (string source in sources)
                {
                    customProvider.AddFromSource(GetSource(source));
                }

                provider = customProvider;
            }

            return(provider);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates a repo provider for the given sources. If null is passed all sources will be returned.
        /// </summary>
        private ISourceRepositoryProvider GetSources(IEnumerable <string> sources)
        {
            PreinstalledRepositoryProvider provider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);

            IPackageSourceProvider sourceProvider = new PackageSourceProvider(_settings);

            PackageSource[] packageSources = sourceProvider.LoadPackageSources().ToArray();

            // add everything enabled if null
            if (sources == null)
            {
                foreach (var packageSource in packageSources)
                {
                    if (packageSource.IsEnabled)
                    {
                        foreach (string source in sources)
                        {
                            provider.AddFromSource(GetSource(source));
                        }
                    }
                }
            }
            else
            {
                // TODO: disallow disabled sources even if they were provided by the caller?
                foreach (string source in sources)
                {
                    provider.AddFromSource(GetSource(source));
                }
            }

            return(provider);
        }
Exemplo n.º 3
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));
        }
Exemplo n.º 4
0
        public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions)
        {
            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(keyName));
            }

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

            if (packageVersions == null ||
                !packageVersions.Any())
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions));
            }

            RunJTFWithCorrectContext(project, async() =>
            {
                // HACK !!! : This is a hack for PCL projects which send isPreUnzipped = true, but their package source
                // (located at C:\Program Files (x86)\Microsoft SDKs\NuGetPackages) follows the V3
                // folder version format.
                if (isPreUnzipped)
                {
                    var isProjectJsonProject = await EnvDTEProjectUtility.HasBuildIntegratedConfig(project);
                    isPreUnzipped            = isProjectJsonProject ? false : isPreUnzipped;
                }

                // create a repository provider with only the registry repository
                var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                repoProvider.AddFromRegistry(keyName, isPreUnzipped);

                var toInstall = GetIdentitiesFromDict(packageVersions);

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

                var projectContext        = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects);
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var logger = new LoggerAdapter(projectContext);

                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    logger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(_settings, logger));

                await InstallInternalAsync(
                    project,
                    toInstall,
                    repoProvider,
                    projectContext,
                    includePrerelease: false,
                    ignoreDependencies: ignoreDependencies,
                    token: CancellationToken.None);
            });
        }
Exemplo n.º 5
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, nameof(extensionId));
            }

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

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

            try
            {
                RunJTFWithCorrectContext(project, () =>
                {
                    var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                    repoProvider.AddFromExtension(_sourceRepositoryProvider, extensionId);

                    var toInstall = GetIdentitiesFromDict(packageVersions);

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

                    var projectContext = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects)
                    {
                        PackageExtractionContext = new PackageExtractionContext(
                            PackageSaveMode.Defaultv2,
                            PackageExtractionBehavior.XmlDocFileSaveMode,
                            ClientPolicyContext.GetClientPolicy(_settings, NullLogger.Instance),
                            NullLogger.Instance)
                    };

                    return(InstallInternalAsync(
                               project,
                               toInstall,
                               repoProvider,
                               projectContext,
                               includePrerelease: false,
                               ignoreDependencies: ignoreDependencies,
                               token: CancellationToken.None));
                });
            }
            catch (Exception exception)
            {
                _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName);
                throw;
            }
        }
Exemplo n.º 6
0
        public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions)
        {
            if (String.IsNullOrEmpty(keyName))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(keyName));
            }

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

            if (packageVersions == null ||
                !packageVersions.Any())
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions));
            }

            PumpingJTF.Run(async() =>
            {
                // HACK !!! : This is a hack for PCL projects which send isPreUnzipped = true, but their package source
                // (located at C:\Program Files (x86)\Microsoft SDKs\NuGetPackages) follows the V3
                // folder version format.
                if (isPreUnzipped)
                {
                    var isProjectJsonProject = await EnvDTEProjectUtility.HasBuildIntegratedConfig(project);
                    isPreUnzipped            = isProjectJsonProject ? false : isPreUnzipped;
                }

                // create a repository provider with only the registry repository
                PreinstalledRepositoryProvider repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                repoProvider.AddFromRegistry(keyName, isPreUnzipped);

                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);

                await InstallInternalAsync(
                    project,
                    toInstall,
                    repoProvider,
                    projectContext,
                    includePrerelease: false,
                    ignoreDependencies: ignoreDependencies,
                    token: CancellationToken.None);
            });
        }
Exemplo n.º 7
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, nameof(extensionId));
            }

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

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

            RunJTFWithCorrectContext(project, () =>
            {
                var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                repoProvider.AddFromExtension(_sourceRepositoryProvider, extensionId);

                var toInstall = GetIdentitiesFromDict(packageVersions);

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

                var projectContext        = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects);
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    new LoggerAdapter(projectContext),
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetDefault());

                return(InstallInternalAsync(
                           project,
                           toInstall,
                           repoProvider,
                           projectContext,
                           includePrerelease: false,
                           ignoreDependencies: ignoreDependencies,
                           token: CancellationToken.None));
            });
        }
        public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions)
        {
            if (String.IsNullOrEmpty(keyName))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(keyName));
            }

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

            if (packageVersions == null ||
                !packageVersions.Any())
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions));
            }

            PumpingJTF.Run(() =>
            {
                // create a repository provider with only the registry repository
                PreinstalledRepositoryProvider repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);
                repoProvider.AddFromRegistry(keyName, isPreUnzipped);

                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);

                return(InstallInternalAsync(
                           project,
                           toInstall,
                           repoProvider,
                           projectContext,
                           includePrerelease: false,
                           ignoreDependencies: ignoreDependencies,
                           token: CancellationToken.None));
            });
        }
Exemplo n.º 9
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,
            EnvDTE.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 _solutionManager.GetOrCreateProjectAsync(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 (EnvDTEProjectInfoUtility.IsWebSite(project))
                {
                    CreateRefreshFilesInBin(
                        project,
                        repositoryPath,
                        configuration.Packages.Where(p => p.SkipAssemblyReferences));

                    CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages);
                }
            }
            finally
            {
                // collapse nodes
                await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes);
            }
        }
        /// <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);
        }
        /// <summary>
        /// Creates a repo provider for the given sources. If null is passed all sources will be returned.
        /// </summary>
        private ISourceRepositoryProvider GetSources(IEnumerable<string> sources)
        {
            PreinstalledRepositoryProvider provider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);

            IPackageSourceProvider sourceProvider = new PackageSourceProvider(_settings);

            PackageSource[] packageSources = sourceProvider.LoadPackageSources().ToArray();

            // add everything enabled if null
            if (sources == null)
            {
                foreach (var packageSource in packageSources)
                {
                    if (packageSource.IsEnabled)
                    {
                        foreach (string source in sources)
                        {
                            provider.AddFromSource(GetSource(source));
                        }
                    }
                }
            }
            else
            {
                // TODO: disallow disabled sources even if they were provided by the caller?
                foreach (string source in sources)
                {
                    provider.AddFromSource(GetSource(source));
                }
            }

            return provider;
        }
        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));
        }
Exemplo n.º 13
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);
        }