public VsPackageInstaller(
            ISourceRepositoryProvider sourceRepositoryProvider,
            Configuration.ISettings settings,
            IVsSolutionManager solutionManager,
            IVsPackageInstallerServices packageServices,
            IDeleteOnRestartManager deleteOnRestartManager)
        {
            _sourceRepositoryProvider = sourceRepositoryProvider;
            _settings               = settings;
            _solutionManager        = solutionManager;
            _packageServices        = packageServices;
            _deleteOnRestartManager = deleteOnRestartManager;
            _isCPSJTFLoaded         = false;

            _projectContext = new Lazy <INuGetProjectContext>(() => {
                var projectContext        = new VSAPIProjectContext();
                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));

                return(projectContext);
            });

            PumpingJTF = new PumpingJTF(NuGetUIThreadHelper.JoinableTaskFactory);
        }
        private Task InstallPackageAsync(string source, Project project, string packageId, NuGetVersion version, bool includePrerelease, bool ignoreDependencies)
        {
            IEnumerable <string> sources = null;

            if (!string.IsNullOrEmpty(source) &&
                !StringComparer.OrdinalIgnoreCase.Equals("All", source)) // "All" was supported in V2
            {
                sources = new[] { source };
            }

            var versionRange = VersionRange.All;

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

            var toInstall = new List <PackageIdentity>
            {
                new PackageIdentity(packageId, version)
            };

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

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

            return(InstallInternalAsync(project, toInstall, GetSources(sources), projectContext, includePrerelease, ignoreDependencies, CancellationToken.None));
        }
Esempio n. 3
0
        public VsPathContextProvider(
            IAsyncServiceProvider asyncServiceProvider,
            Lazy <ISettings> settings,
            Lazy <IVsSolutionManager> solutionManager,
            Lazy <NuGet.Common.ILogger> logger)
        {
            _asyncServiceprovider = asyncServiceProvider ?? throw new ArgumentNullException(nameof(asyncServiceProvider));
            _settings             = settings ?? throw new ArgumentNullException(nameof(settings));
            _solutionManager      = solutionManager ?? throw new ArgumentNullException(nameof(solutionManager));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _getLockFileOrNullAsync = BuildIntegratedProjectUtility.GetLockFileOrNull;

            _projectContext = new Lazy <INuGetProjectContext>(() => {
                var projectContext = new VSAPIProjectContext();

                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var adapterLogger         = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    adapterLogger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(_settings.Value, adapterLogger));

                return(projectContext);
            });
        }
        private async Task RestoreMissingPackagesInSolutionAsync(
            string solutionDirectory,
            IEnumerable <PackageRestoreData> packages,
            ILogger logger,
            CancellationToken token)
        {
            await TaskScheduler.Default;

            using (var cacheContext = new SourceCacheContext())
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

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

                await _packageRestoreManager.RestoreMissingPackagesAsync(
                    solutionDirectory,
                    packages,
                    _nuGetProjectContext,
                    downloadContext,
                    logger,
                    token);
            }
        }
        protected NuGetPowerShellBaseCommand()
        {
            _sourceRepositoryProvider = ServiceLocator.GetInstance <ISourceRepositoryProvider>();
            ConfigSettings            = ServiceLocator.GetInstance <Configuration.ISettings>();
            VsSolutionManager         = ServiceLocator.GetInstance <IVsSolutionManager>();
            DTE = ServiceLocator.GetInstance <DTE>();
            SourceControlManagerProvider = ServiceLocator.GetInstance <ISourceControlManagerProvider>();
            _commonOperations            = ServiceLocator.GetInstance <ICommonOperations>();
            PackageRestoreManager        = ServiceLocator.GetInstance <IPackageRestoreManager>();
            _deleteOnRestartManager      = ServiceLocator.GetInstance <IDeleteOnRestartManager>();

            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var logger = new LoggerAdapter(this);

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

            if (_commonOperations != null)
            {
                ExecutionContext = new IDEExecutionContext(_commonOperations);
            }

            ActivityCorrelationId.StartNew();
        }
        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);
            });
        }
        public async Task ClientPolicies_WithoutSignerInTrustedSignersList_WithMatchingOwnersAsync(SigningTestType signature, string validationMode, bool expectedResult, int expectedErrors, int expectedWarnings)
        {
            // Arrange
            using (var dir = TestDirectory.Create())
                using (var authorCertificate = new X509Certificate2(_trustedAuthorTestCert.Source.Cert))
                    using (var repoCertificate = new X509Certificate2(_trustedRepoTestCert.Source.Cert))
                    {
                        var authorCertificateFingerprintString = SignatureTestUtility.GetFingerprint(authorCertificate, HashAlgorithmName.SHA256);
                        var repoCertificateFingerprintString   = SignatureTestUtility.GetFingerprint(repoCertificate, HashAlgorithmName.SHA256);

                        var signedPackagePath = await CreateSignedPackageAsync(dir, signature, authorCertificate, repoCertificate);

                        var config = $@"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""{validationMode}"" />
    </config>
    <trustedSigners>
        <repository name=""repo1"" serviceIndex=""https://api.v3serviceIndex.test/json"">
            <certificate fingerprint=""abc"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
            <owners>owner1</owners>
        </repository>
    </trustedSigners>
</configuration>";

                        var nugetConfigPath = "NuGet.Config";
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, dir, config);

                        // Act and Assert
                        var settings = new Settings(dir);

                        var verifierSettings = SignedPackageVerifierSettings.GetClientPolicy(settings, NullLogger.Instance);
                        var trustProviders   = new[]
                        {
                            new AllowListVerificationProvider()
                        };
                        var verifier = new PackageSignatureVerifier(trustProviders);

                        using (var packageReader = new PackageArchiveReader(signedPackagePath))
                        {
                            // Act
                            var result = await verifier.VerifySignaturesAsync(packageReader, verifierSettings, CancellationToken.None);

                            var resultsWithWarnings = result.Results.Where(r => r.GetWarningIssues().Any());
                            var resultsWithErrors   = result.Results.Where(r => r.GetErrorIssues().Any());
                            var totalWarningIssues  = resultsWithWarnings.SelectMany(r => r.GetWarningIssues());
                            var totalErrorIssues    = resultsWithErrors.SelectMany(r => r.GetErrorIssues());

                            // Assert
                            result.Valid.Should().Be(expectedResult);
                            totalWarningIssues.Count().Should().Be(expectedWarnings);
                            totalErrorIssues.Count().Should().Be(expectedErrors);
                        }
                    }
        }
Esempio n. 8
0
        internal PackageExtractionContext GetPackageExtractionContext(ISettings settings)
        {
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

            return(new PackageExtractionContext(
                       PackageSaveMode,
                       PackageExtractionBehavior.XmlDocFileSaveMode,
                       Log,
                       signedPackageVerifier,
                       SignedPackageVerifierSettings.GetClientPolicy(settings, Log)));
        }
        public void GetClientPolicy_ReadsAndParsesTrustedSigners()
        {
            // Arrange
            var config = @"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""require"" />
    </config>
    <trustedSigners>
        <author name=""author1"">
            <certificate fingerprint=""abc"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </author>
        <repository name=""repository1"" serviceIndex=""https://v3serviceIndex.test/api/json"">
            <certificate fingerprint=""def"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </repository>
    </trustedSigners>
</configuration>";

            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
            {
                SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);

                // Act and Assert
                var settings = new Settings(mockBaseDirectory);
                settings.Should().NotBeNull();

                var expectedAllowList = new List <VerificationAllowListEntry>()
                {
                    new TrustedSignerAllowListEntry(VerificationTarget.Author, SignaturePlacement.PrimarySignature, "abc", HashAlgorithmName.SHA256),
                    new TrustedSignerAllowListEntry(VerificationTarget.Repository, SignaturePlacement.Any, "def", HashAlgorithmName.SHA256)
                };

                var verifierSettings = SignedPackageVerifierSettings.GetClientPolicy(settings, NullLogger.Instance);

                verifierSettings.AllowUnsigned.Should().Be(false);
                verifierSettings.AllowIllegal.Should().Be(false);
                verifierSettings.AllowUntrusted.Should().Be(false);
                verifierSettings.AllowIgnoreTimestamp.Should().Be(true);
                verifierSettings.AllowMultipleTimestamps.Should().Be(true);
                verifierSettings.AllowNoTimestamp.Should().Be(true);
                verifierSettings.AllowUnknownRevocation.Should().Be(true);
                verifierSettings.ReportUnknownRevocation.Should().Be(true);
                verifierSettings.AllowNoRepositoryCertificateList.Should().Be(true);
                verifierSettings.AllowNoClientCertificateList.Should().Be(false);
                verifierSettings.VerificationTarget.Should().Be(VerificationTarget.All);
                verifierSettings.SignaturePlacement.Should().Be(SignaturePlacement.Any);
                verifierSettings.RepositoryCountersignatureVerificationBehavior.Should().Be(SignatureVerificationBehavior.IfExistsAndIsNecessary);
                verifierSettings.RevocationMode.Should().Be(RevocationMode.Online);
                verifierSettings.RepositoryCertificateList.Should().BeNull();
                verifierSettings.ClientCertificateList.Should().BeEquivalentTo(expectedAllowList);
            }
        }
        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);
            }
        }
Esempio n. 11
0
        public override async Task ExecuteCommandAsync()
        {
            // Arguments[0] or Arguments[1] will not be null at this point.
            // Because, this command has MinArgs set to 2.
            var source      = Arguments[0];
            var destination = Arguments[1];

            OfflineFeedUtility.ThrowIfInvalidOrNotFound(
                source,
                isDirectory: true,
                resourceString: LocalizedResourceManager.GetString(nameof(NuGetResources.InitCommand_FeedIsNotFound)));

            // If the Destination Feed Folder does not exist, it will be created.
            OfflineFeedUtility.ThrowIfInvalid(destination);

            var packagePaths = GetPackageFilePaths(source, "*" + PackagingCoreConstants.NupkgExtension);

            if (packagePaths.Count > 0)
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var signingSettings       = SignedPackageVerifierSettings.GetClientPolicy(Settings, Console);

                var packageExtractionContext = new PackageExtractionContext(
                    Expand ? PackageSaveMode.Defaultv3 : PackageSaveMode.Nuspec | PackageSaveMode.Nupkg,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    Console,
                    signedPackageVerifier,
                    signingSettings);

                foreach (var packagePath in packagePaths)
                {
                    var offlineFeedAddContext = new OfflineFeedAddContext(
                        packagePath,
                        destination,
                        Console, // IConsole is an ILogger
                        throwIfSourcePackageIsInvalid: false,
                        throwIfPackageExistsAndInvalid: false,
                        throwIfPackageExists: false,
                        extractionContext: packageExtractionContext);

                    await OfflineFeedUtility.AddPackageToSource(offlineFeedAddContext, CancellationToken.None);
                }
            }
            else
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString(nameof(NuGetResources.InitCommand_FeedContainsNoPackages)),
                    source);

                Console.LogMinimal(message);
            }
        }
Esempio n. 12
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());
                var logger = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    logger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(_settings, logger));

                return(InstallInternalAsync(
                           project,
                           toInstall,
                           repoProvider,
                           projectContext,
                           includePrerelease: false,
                           ignoreDependencies: ignoreDependencies,
                           token: CancellationToken.None));
            });
        }
        private async Task PushPackageToFileSystem(Uri sourceUri,
                                                   string pathToPackage,
                                                   ILogger log,
                                                   CancellationToken token)
        {
            var             root            = sourceUri.LocalPath;
            PackageIdentity packageIdentity = null;

            using (var reader = new PackageArchiveReader(pathToPackage))
            {
                packageIdentity = reader.GetIdentity();
            }

            if (IsV2LocalRepository(root))
            {
                var pathResolver    = new PackagePathResolver(root, useSideBySidePaths: true);
                var packageFileName = pathResolver.GetPackageFileName(packageIdentity);

                var fullPath = Path.Combine(root, packageFileName);
                File.Copy(pathToPackage, fullPath, overwrite: true);
            }
            else
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                var packageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    log,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(Settings, log));

                var context = new OfflineFeedAddContext(pathToPackage,
                                                        root,
                                                        log,
                                                        throwIfSourcePackageIsInvalid: true,
                                                        throwIfPackageExistsAndInvalid: false,
                                                        throwIfPackageExists: false,
                                                        extractionContext: packageExtractionContext);

                await OfflineFeedUtility.AddPackageToSource(context, token);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// This constructor is just used for testing.
        /// </summary>
        public VsPathContextProvider(
            ISettings settings,
            IVsSolutionManager solutionManager,
            NuGet.Common.ILogger logger,
            Func <BuildIntegratedNuGetProject, Task <LockFile> > getLockFileOrNullAsync)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

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

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

            _settings               = new Lazy <ISettings>(() => settings);
            _solutionManager        = new Lazy <IVsSolutionManager>(() => solutionManager);
            _logger                 = new Lazy <NuGet.Common.ILogger>(() => logger);
            _getLockFileOrNullAsync = getLockFileOrNullAsync ?? BuildIntegratedProjectUtility.GetLockFileOrNull;

            _projectContext = new Lazy <INuGetProjectContext>(() => {
                var projectContext = new VSAPIProjectContext();

                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var adapterLogger         = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    adapterLogger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(settings, adapterLogger));

                return(projectContext);
            });
        }
        public void GetClientPolicy_RequireMode_ReadsClientPolicyCorrectly()
        {
            // Arrange
            var config = @"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""require"" />
    </config>
</configuration>";

            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
            {
                SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);

                // Act and Assert
                var settings = new Settings(mockBaseDirectory);
                settings.Should().NotBeNull();

                var verifierSettings = SignedPackageVerifierSettings.GetClientPolicy(settings, NullLogger.Instance);

                verifierSettings.AllowUnsigned.Should().Be(false);
                verifierSettings.AllowIllegal.Should().Be(false);
                verifierSettings.AllowUntrusted.Should().Be(false);
                verifierSettings.AllowIgnoreTimestamp.Should().Be(true);
                verifierSettings.AllowMultipleTimestamps.Should().Be(true);
                verifierSettings.AllowNoTimestamp.Should().Be(true);
                verifierSettings.AllowUnknownRevocation.Should().Be(true);
                verifierSettings.ReportUnknownRevocation.Should().Be(true);
                verifierSettings.AllowNoRepositoryCertificateList.Should().Be(true);
                verifierSettings.AllowNoClientCertificateList.Should().Be(false);
                verifierSettings.VerificationTarget.Should().Be(VerificationTarget.All);
                verifierSettings.SignaturePlacement.Should().Be(SignaturePlacement.Any);
                verifierSettings.RepositoryCountersignatureVerificationBehavior.Should().Be(SignatureVerificationBehavior.IfExistsAndIsNecessary);
                verifierSettings.RevocationMode.Should().Be(RevocationMode.Online);
                verifierSettings.RepositoryCertificateList.Should().BeNull();
                verifierSettings.ClientCertificateList.Should().BeEmpty();
            }
        }
        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();

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

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

                // uninstall the package
                await packageManager.UninstallPackageAsync(nuGetProject, packageId, uninstallContext, projectContext, CancellationToken.None);
            });
        }
Esempio n. 17
0
        /// <summary>
        /// Restores missing packages for the entire solution
        /// </summary>
        /// <returns></returns>
        public virtual async Task <PackageRestoreResult> RestoreMissingPackagesInSolutionAsync(
            string solutionDirectory,
            INuGetProjectContext nuGetProjectContext,
            ILogger logger,
            CancellationToken token)
        {
            var packageReferencesDictionary = await GetPackagesReferencesDictionaryAsync(token);

            // When this method is called, the step to compute if a package is missing is implicit. Assume it is true
            var packages = packageReferencesDictionary.Select(p =>
            {
                Debug.Assert(p.Value != null);
                return(new PackageRestoreData(p.Key, p.Value, isMissing: true));
            });

            using (var cacheContext = new SourceCacheContext())
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var adapterLogger         = new LoggerAdapter(nuGetProjectContext);

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

                return(await RestoreMissingPackagesAsync(
                           solutionDirectory,
                           packages,
                           nuGetProjectContext,
                           downloadContext,
                           logger,
                           token));
            }
        }
Esempio n. 18
0
        public override async Task ExecuteCommandAsync()
        {
            // Arguments[0] will not be null at this point.
            // Because, this command has MinArgs set to 1.
            var packagePath = Arguments[0];

            if (string.IsNullOrEmpty(Source))
            {
                throw new CommandLineException(
                          LocalizedResourceManager.GetString(nameof(NuGetResources.AddCommand_SourceNotProvided)));
            }

            OfflineFeedUtility.ThrowIfInvalidOrNotFound(
                packagePath,
                isDirectory: false,
                resourceString: LocalizedResourceManager.GetString(nameof(NuGetResources.NupkgPath_NotFound)));

            // If the Source Feed Folder does not exist, it will be created.
            OfflineFeedUtility.ThrowIfInvalid(Source);

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

            var packageExtractionContext = new PackageExtractionContext(
                Expand ? PackageSaveMode.Defaultv3 : PackageSaveMode.Nuspec | PackageSaveMode.Nupkg,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                Console,
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetClientPolicy(Settings, Console));

            var offlineFeedAddContext = new OfflineFeedAddContext(
                packagePath,
                Source,
                Console, // IConsole is an ILogger
                throwIfSourcePackageIsInvalid: true,
                throwIfPackageExistsAndInvalid: true,
                throwIfPackageExists: false,
                extractionContext: packageExtractionContext);

            await OfflineFeedUtility.AddPackageToSource(offlineFeedAddContext, CancellationToken.None);
        }
Esempio n. 19
0
        /// <summary>
        /// By convention, we copy all files under the NativeBinaries folder under package root to the bin folder of
        /// the Website.
        /// </summary>
        /// <param name="project">The target Website project.</param>
        /// <param name="repositoryPath">The local repository path.</param>
        /// <param name="packageInfos">The packages that were installed.</param>
        private void CopyNativeBinariesToBin(EnvDTE.Project project, string repositoryPath, IEnumerable <PreinstalledPackageInfo> packageInfos)
        {
            var context = new VSAPIProjectContext();
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var logger = new LoggerAdapter(context);

            context.PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                logger,
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetClientPolicy(_settings, logger));
            var projectSystem = new VsMSBuildProjectSystem(_vsProjectAdapterProvider.CreateAdapterForFullyLoadedProject(project), context);

            foreach (var packageInfo in packageInfos)
            {
                var packagePath = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", packageInfo.Id, packageInfo.Version);

                CopyNativeBinaries(projectSystem, repositoryPath,
                                   Path.Combine(repositoryPath, packagePath));
            }
        }
Esempio n. 20
0
        public virtual Task <PackageRestoreResult> RestoreMissingPackagesAsync(string solutionDirectory,
                                                                               IEnumerable <PackageRestoreData> packages,
                                                                               INuGetProjectContext nuGetProjectContext,
                                                                               PackageDownloadContext downloadContext,
                                                                               ILogger logger,
                                                                               CancellationToken token)
        {
            if (packages == null)
            {
                throw new ArgumentNullException(nameof(packages));
            }

            var nuGetPackageManager = GetNuGetPackageManager(solutionDirectory);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packages,
                token,
                PackageRestoredEvent,
                PackageRestoreFailedEvent,
                sourceRepositories: null,
                maxNumberOfParallelTasks: PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: logger);

            if (nuGetProjectContext.PackageExtractionContext == null)
            {
                var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

                nuGetProjectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    packageRestoreContext.Logger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(Settings, packageRestoreContext.Logger));
            }

            return(RestoreMissingPackagesAsync(packageRestoreContext, nuGetProjectContext, downloadContext));
        }
        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 signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var projectContext        = new VSAPIProjectContext();
                var logger = new LoggerAdapter(projectContext);
                projectContext.PackageExtractionContext = new PackageExtractionContext(
                    PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    logger,
                    signedPackageVerifier,
                    SignedPackageVerifierSettings.GetClientPolicy(_settings, logger));

                var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(
                    project,
                    projectContext);

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

                packages.AddRange(installedPackages);
            }

            return(packages);
        }
Esempio n. 22
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 signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                var signingSettings       = SignedPackageVerifierSettings.GetClientPolicy(Settings, Console);

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

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload)
                {
                    ExtractionContext = new PackageExtractionContext(
                        Packaging.PackageSaveMode.Defaultv3,
                        PackageExtractionBehavior.XmlDocFileSaveMode,
                        Console,
                        signedPackageVerifier,
                        signingSettings)
                };

                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);
                }
            }
        }
Esempio n. 23
0
        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));
            }

            // 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);
                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 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 signedPackageVerifier       = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var signingVerificationSettings = SignedPackageVerifierSettings.GetClientPolicy(Settings, collectorLogger);
            var projectContext = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    Packaging.PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    collectorLogger,
                    signedPackageVerifier,
                    signingVerificationSettings)
            };

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

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

                var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload)
                {
                    ExtractionContext = new PackageExtractionContext(
                        Packaging.PackageSaveMode.Defaultv3,
                        PackageExtractionBehavior.XmlDocFileSaveMode,
                        collectorLogger,
                        signedPackageVerifier,
                        signingVerificationSettings)
                };

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

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

                return(new RestoreSummary(
                           result.Restored,
                           "packages.config projects",
                           SettingsUtility.GetConfigFilePaths(Settings),
                           packageSources.Select(x => x.Source),
                           installCount,
                           collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents))));
            }
        }
Esempio n. 24
0
        public override async Task ExecuteCommandAsync()
        {
            // update with self as parameter
            if (Self)
            {
                var selfUpdater = new SelfUpdater(repositoryFactory: RepositoryFactory)
                {
                    Console = Console
                };
                selfUpdater.UpdateSelf(Prerelease);
                return;
            }

            string inputFile = GetInputFile();

            if (string.IsNullOrEmpty(inputFile))
            {
                throw new CommandLineException(NuGetResources.InvalidFile);
            }

            _msbuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console).Value.Path;
            var context = new UpdateConsoleProjectContext(Console, FileConflictAction);

            var logger = new LoggerAdapter(context);
            var signedPackageVerifier         = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var signedPackageVerifierSettings = SignedPackageVerifierSettings.GetClientPolicy(Settings, logger);

            context.PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                logger,
                signedPackageVerifier,
                signedPackageVerifierSettings);

            string inputFileName = Path.GetFileName(inputFile);

            // update with packages.config as parameter
            if (CommandLineUtility.IsValidConfigFileName(inputFileName))
            {
                await UpdatePackagesAsync(inputFile, context);

                return;
            }

            // update with project file as parameter
            if (ProjectHelper.SupportedProjectExtensions.Contains(Path.GetExtension(inputFile) ?? string.Empty))
            {
                if (!File.Exists(inputFile))
                {
                    throw new CommandLineException(NuGetResources.UnableToFindProject, inputFile);
                }

                var projectSystem = new MSBuildProjectSystem(
                    _msbuildDirectory,
                    inputFile,
                    context);
                await UpdatePackagesAsync(projectSystem, GetRepositoryPath(projectSystem.ProjectFullPath));

                return;
            }

            if (!File.Exists(inputFile))
            {
                throw new CommandLineException(NuGetResources.UnableToFindSolution, inputFile);
            }

            // update with solution as parameter
            string solutionDir = Path.GetDirectoryName(inputFile);

            await UpdateAllPackages(solutionDir, context);
        }
        public IEnumerable <IVsPackageMetadata> GetInstalledPackages(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

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

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

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

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

                    var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(
                        project,
                        projectContext);

                    if (nuGetProject != null)
                    {
                        FallbackPackagePathResolver pathResolver = null;
                        var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
                        if (buildIntegratedProject != null)
                        {
                            pathResolver = await GetPackagesPathResolverAsync(buildIntegratedProject);
                        }

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

                        foreach (var package in installedPackages)
                        {
                            if (!package.PackageIdentity.HasVersion)
                            {
                                // Currently we are not supporting floating versions
                                // because of that we will skip this package so that it doesn't throw ArgumentNullException
                                continue;
                            }

                            string installPath;
                            if (buildIntegratedProject != null)
                            {
                                installPath = pathResolver.GetPackageDirectory(package.PackageIdentity.Id, package.PackageIdentity.Version);
                            }
                            else
                            {
                                // Get the install path for package
                                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;
            }));
        }
Esempio n. 26
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="preferPackageReferenceFormat">Install packages to the project as PackageReference if the project type supports it</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,
            bool preferPackageReferenceFormat,
            Action <string> warningHandler,
            Action <string> errorHandler)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

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

            // find the project
            var defaultProjectContext = new VSAPIProjectContext();
            var signedPackageVerifier = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var logger = new LoggerAdapter(defaultProjectContext);

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

            var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(project, defaultProjectContext);

            if (preferPackageReferenceFormat && await NuGetProjectUpgradeUtility.IsNuGetProjectUpgradeableAsync(nuGetProject, project, needsAPackagesConfig: false))
            {
                nuGetProject = await _solutionManager.UpgradeProjectToPackageReferenceAsync(nuGetProject);
            }

            // 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
                            var disableBindingRedirects = package.SkipAssemblyReferences;

                            var projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects);
                            var loggerAdapter  = new LoggerAdapter(projectContext);
                            projectContext.PackageExtractionContext = new PackageExtractionContext(
                                PackageSaveMode.Defaultv2,
                                PackageExtractionBehavior.XmlDocFileSaveMode,
                                loggerAdapter,
                                signedPackageVerifier,
                                SignedPackageVerifierSettings.GetClientPolicy(_settings, loggerAdapter));

                            // 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);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Adds refresh files to the specified project for all assemblies references belonging to the packages
        /// specified by packageNames.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="repositoryPath">The file system pointing to 'packages' folder under the solution.</param>
        /// <param name="packageNames">The package names.</param>
        private void AddRefreshFilesForReferences(EnvDTE.Project project, string repositoryPath, IEnumerable <PackageIdentity> packageNames)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

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

            if (!packageNames.Any())
            {
                return;
            }

            VSAPIProjectContext context = new VSAPIProjectContext(skipAssemblyReferences: true, bindingRedirectsDisabled: true);
            var signedPackageVerifier   = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var logger = new LoggerAdapter(context);

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

            WebSiteProjectSystem projectSystem = new WebSiteProjectSystem(_vsProjectAdapterProvider.CreateAdapterForFullyLoadedProject(project), context);

            foreach (var packageName in packageNames)
            {
                string packagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", packageName.Id, packageName.Version);

                DirectoryInfo packageFolder = new DirectoryInfo(Path.Combine(repositoryPath, packagePath));

                PackageFolderReader reader = new PackageFolderReader(packageFolder);

                var frameworkGroups = reader.GetReferenceItems();

                var groups = reader.GetReferenceItems();

                var fwComparer           = new NuGetFrameworkFullComparer();
                FrameworkReducer reducer = new FrameworkReducer();
                NuGetFramework   targetGroupFramework = reducer.GetNearest(projectSystem.TargetFramework, groups.Select(e => e.TargetFramework));

                if (targetGroupFramework != null)
                {
                    var refGroup = groups.Where(e => fwComparer.Equals(targetGroupFramework, e.TargetFramework)).FirstOrDefault();

                    foreach (string refItem in refGroup.Items)
                    {
                        string sourcePath = Path.Combine(packageFolder.FullName, refItem.Replace('/', Path.DirectorySeparatorChar));

                        // create one refresh file for each assembly reference, as per required by Website projects
                        // projectSystem.CreateRefreshFile(assemblyPath);
                        RefreshFileUtility.CreateRefreshFile(projectSystem, sourcePath);
                    }
                }
            }
        }
Esempio n. 28
0
        internal async Task InstallInternalAsync(
            Project project,
            List <Packaging.Core.PackageDependency> packages,
            ISourceRepositoryProvider repoProvider,
            bool skipAssemblyReferences,
            bool ignoreDependencies,
            CancellationToken token)
        {
            foreach (var group in packages.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase))
            {
                if (group.Count() > 1)
                {
                    // throw if a package id appears more than once
                    throw new InvalidOperationException(VsResources.InvalidPackageList);
                }
            }

            // find the latest package
            var metadataResources = new List <MetadataResource>();

            // create the resources for looking up the latest version
            foreach (var repo in repoProvider.GetRepositories())
            {
                var resource = await repo.GetResourceAsync <MetadataResource>();

                if (resource != null)
                {
                    metadataResources.Add(resource);
                }
            }

            // find the highest version within the ranges
            var idToIdentity = new Dictionary <string, PackageIdentity>(StringComparer.OrdinalIgnoreCase);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                foreach (var dep in packages)
                {
                    NuGetVersion highestVersion = null;

                    if (dep.VersionRange != null &&
                        VersionComparer.Default.Equals(dep.VersionRange.MinVersion, dep.VersionRange.MaxVersion) &&
                        dep.VersionRange.MinVersion != null)
                    {
                        // this is a single version, not a range
                        highestVersion = dep.VersionRange.MinVersion;
                    }
                    else
                    {
                        var tasks = new List <Task <IEnumerable <NuGetVersion> > >();

                        foreach (var resource in metadataResources)
                        {
                            tasks.Add(resource.GetVersions(dep.Id, sourceCacheContext, NullLogger.Instance, token));
                        }

                        var versions = await Task.WhenAll(tasks.ToArray());

                        highestVersion = versions.SelectMany(v => v).Where(v => dep.VersionRange.Satisfies(v)).Max();
                    }

                    if (highestVersion == null)
                    {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, VsResources.UnknownPackage, dep.Id));
                    }

                    if (!idToIdentity.ContainsKey(dep.Id))
                    {
                        idToIdentity.Add(dep.Id, new PackageIdentity(dep.Id, highestVersion));
                    }
                }
            }

            // 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,
                idToIdentity.Values.ToList(),
                repoProvider,
                projectContext,
                includePrerelease : false,
                ignoreDependencies : ignoreDependencies,
                token : token);
        }
Esempio n. 29
0
        private async Task InstallPackageAsync(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                // Avoid searching for the highest version in the global packages folder,
                // it needs to come from the feeds instead. Once found it may come from
                // the global packages folder unless NoCache is true.
                ExcludeCacheAsSource = true;
            }

            var framework = GetTargetFramework();

            // Create the project and set the framework if available.
            var project = new InstallCommandProject(
                root: installPath,
                packagePathResolver: new PackagePathResolver(installPath, !ExcludeVersion),
                targetFramework: framework);

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources      = GetPackageSources(Settings);
            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            Console.PrintPackageSources(packageSources);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var dependencyBehavior = GetDependencyBehavior();

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease: allowPrerelease,
                    includeUnlisted: true,
                    versionConstraints: VersionConstraints.None,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                if (version == null)
                {
                    // Write out a helpful message before the http messages are shown
                    Console.Log(LogLevel.Minimal, string.Format(
                                    CultureInfo.CurrentCulture,
                                    LocalizedResourceManager.GetString("InstallPackageMessage"), packageId, installPath));

                    // Find the latest version using NuGetPackageManager
                    var resolvePackage = await NuGetPackageManager.GetLatestVersionAsync(
                        packageId,
                        project,
                        resolutionContext,
                        primaryRepositories,
                        Console,
                        CancellationToken.None);

                    if (resolvePackage == null || resolvePackage.LatestVersion == null)
                    {
                        var message = string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                            packageId);

                        throw new CommandLineException(message);
                    }

                    version = resolvePackage.LatestVersion;
                }

                // Get a list of packages already in the folder.
                var installedPackages = await project.GetFolderPackagesAsync(CancellationToken.None);

                // Find existing versions of the package
                var alreadyInstalledVersions = new HashSet <NuGetVersion>(installedPackages
                                                                          .Where(e => StringComparer.OrdinalIgnoreCase.Equals(packageId, e.PackageIdentity.Id))
                                                                          .Select(e => e.PackageIdentity.Version));

                var packageIdentity = new PackageIdentity(packageId, version);

                // Check if the package already exists or a higher version exists already.
                var skipInstall = project.PackageExists(packageIdentity);

                // For SxS allow other versions to install. For non-SxS skip if a higher version exists.
                skipInstall |= (ExcludeVersion && alreadyInstalledVersions.Any(e => e >= version));

                if (skipInstall)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                        packageIdentity);

                    Console.LogMinimal(message);
                }
                else
                {
                    var signedPackageVerifier       = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
                    var signingVerificationSettings = SignedPackageVerifierSettings.GetClientPolicy(Settings, Console);

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

                    resolutionContext.SourceCacheContext.NoCache        = NoCache;
                    resolutionContext.SourceCacheContext.DirectDownload = DirectDownload;

                    var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, installPath, DirectDownload)
                    {
                        ExtractionContext = new PackageExtractionContext(
                            Packaging.PackageSaveMode.Defaultv3,
                            PackageExtractionBehavior.XmlDocFileSaveMode,
                            Console,
                            signedPackageVerifier,
                            signingVerificationSettings)
                    };

                    if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        downloadContext.ExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    await packageManager.InstallPackageAsync(
                        project,
                        packageIdentity,
                        resolutionContext,
                        projectContext,
                        downloadContext,
                        primaryRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

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