Exemple #1
0
        public async ValueTask UninstallPackagesAsync(
            string projectId,
            IReadOnlyList <PackageIdentity> packageIdentities,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);
            Assumes.NotNullOrEmpty(packageIdentities);

            cancellationToken.ThrowIfCancellationRequested();

            MSBuildNuGetProject project = await GetMsBuildNuGetProjectAsync(projectId, cancellationToken);

            IEnumerable <NuGetProjectAction>?actions = packageIdentities
                                                       .Select(packageIdentity => NuGetProjectAction.CreateUninstallProjectAction(packageIdentity, project));

            NuGetPackageManager packageManager = await _state.GetPackageManagerAsync(cancellationToken);

            Assumes.NotNull(packageManager);

            INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();

            Assumes.NotNull(projectContext);

            await packageManager.ExecuteNuGetProjectActionsAsync(
                project,
                actions,
                projectContext,
                NullSourceCacheContext.Instance,
                CancellationToken.None);
        }
Exemple #2
0
        public MSBuildNuGetProject AddNewMSBuildProject(string projectName = null, NuGetFramework projectTargetFramework = null, string packagesConfigName = null)
        {
            var existingProject = Task.Run(async() => await GetNuGetProjectAsync(projectName));

            existingProject.Wait();
            if (existingProject.IsCompleted && existingProject.Result != null)
            {
                throw new ArgumentException("Project with " + projectName + " already exists");
            }

            var packagesFolder = PackagesFolder;

            projectName = string.IsNullOrEmpty(projectName) ? Guid.NewGuid().ToString() : projectName;
            var projectFullPath = Path.Combine(SolutionDirectory, projectName);

            Directory.CreateDirectory(projectFullPath);

            projectTargetFramework = projectTargetFramework ?? NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext(),
                                                                              projectFullPath, projectName);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolder, projectFullPath);

            NuGetProjects.Add(msBuildNuGetProject);
            return(msBuildNuGetProject);
        }
Exemple #3
0
        private async Task <IEnumerable <NuGetProjectAction> > PacManCleanInstall(SourceRepositoryProvider sourceRepositoryProvider, PackageIdentity target)
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager())
                using (var randomPackagesConfigFolderPath = TestDirectory.Create())
                {
                    var testSettings          = NullSettings.Instance;
                    var token                 = CancellationToken.None;
                    var deleteOnRestartManger = new TestDeleteOnRestartManager();
                    var nuGetPackageManager   = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManger);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

                    var projectTargetFramework    = NuGetFramework.Parse("net45");
                    var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
                    var msBuildNuGetProject       = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigFolderPath);

                    // Act
                    var nugetProjectActions = await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, target,
                                                                                                   new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    return(nugetProjectActions);
                }
        }
        private async Task <IVsPathContext> GetPathContextFromPackagesConfigAsync(
            MSBuildNuGetProject msbuildNuGetProject, CancellationToken token)
        {
            var packageReferences = await msbuildNuGetProject.GetInstalledPackagesAsync(token);

            // switch to a background thread to process packages data
            await TaskScheduler.Default;

            var trie = new PathLookupTrie <string>();

            foreach (var pid in packageReferences.Select(pr => pr.PackageIdentity))
            {
                var packageInstallPath = msbuildNuGetProject.FolderNuGetProject.GetInstalledPath(pid);
                if (string.IsNullOrEmpty(packageInstallPath))
                {
                    throw new KeyNotFoundException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_PackageDirectoryNotFound, pid));
                }

                trie[packageInstallPath] = packageInstallPath;
            }

            var pathContext = GetSolutionPathContext();

            return(new VsIndexedPathContext(
                       pathContext.UserPackageFolder,
                       pathContext.FallbackPackageFolders.Cast <string>(),
                       trie,
                       _telemetryProvider));
        }
            public NuGetProject(List <string> packagesList, string packagesPath, ProjectFile projectFile, ILog log)
            {
                this.log          = log;
                this.packagesList = packagesList;
                this.projectFile  = projectFile;
                installedPackages = new HashSet <PackageIdentity>();
                var sourceProvider           = new PackageSourceProvider(Settings.LoadDefaultSettings(null));
                var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);

                repositories = sourceProvider.LoadPackageSources().Select(sourceRepositoryProvider.CreateRepository)
                               .ToList();
                logger = new Console();

                var projectFilePath = projectFile.FilePath;

                var msbuildDirectory =
                    Path.GetDirectoryName(ModuleBuilderHelper.FindMsBuild(null, "Cement NuGet Package Installer"));

                projectContext = new ConsoleProjectContext(logger);
                projectSystem  = new MSBuildProjectSystem(
                    msbuildDirectory,
                    projectFilePath,
                    projectContext);
                var projectFolder = Path.GetDirectoryName(projectFilePath);

                project = new MSBuildNuGetProject(projectSystem, packagesPath, projectFolder);
            }
Exemple #6
0
        public NuGetProject CreateNuGetProject(EnvDTEProject envDTEProject, INuGetProjectContext nuGetProjectContext = null)
        {
            if (nuGetProjectContext == null)
            {
                nuGetProjectContext = EmptyNuGetProjectContext;
            }

            var projectK = GetProjectKProject(envDTEProject);

            if (projectK != null)
            {
                return(new ProjectKNuGetProject(projectK, envDTEProject.Name, envDTEProject.UniqueName));
            }

            var msBuildNuGetProjectSystem  = MSBuildNuGetProjectSystemFactory.CreateMSBuildNuGetProjectSystem(envDTEProject, nuGetProjectContext);
            var folderNuGetProjectFullPath = _packagesPath();
            var packagesConfigFiles        = EnvDTEProjectUtility.GetPackageReferenceFileFullPaths(envDTEProject);

            // Item1 is path to "packages.<projectName>.config". Item2 is path to "packages.config"
            string packagesConfigWithProjectNameFullPath = packagesConfigFiles.Item1;
            string packagesConfigFullPath = packagesConfigFiles.Item2;

            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, folderNuGetProjectFullPath,
                                                              File.Exists(packagesConfigWithProjectNameFullPath) ? packagesConfigWithProjectNameFullPath : packagesConfigFullPath);

            return(msBuildNuGetProject);
        }
        internal static string GetPackagesLockFilePath(MSBuildNuGetProject msbuildProject)
        {
            var directory       = (string)msbuildProject.Metadata["FullPath"];
            var msbuildProperty = msbuildProject?.ProjectSystem?.GetPropertyValue("NuGetLockFilePath");
            var projectName     = (string)msbuildProject.Metadata["UniqueName"];

            return(GetPackagesLockFilePath(directory, msbuildProperty, projectName));
        }
        public async Task TestMSBuildNuGetProjectUninstallReferences()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetLegacyTestPackage(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            using (var packageStream = packageFileInfo.OpenRead())
            {
                // Act
                await msBuildNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
            }

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            // Check that the reference has been added to MSBuildNuGetProjectSystem
            Assert.Equal(1, msBuildNuGetProjectSystem.References.Count);
            Assert.Equal("test45.dll", msBuildNuGetProjectSystem.References.First().Key);
            Assert.Equal(Path.Combine(msBuildNuGetProject.FolderNuGetProject.GetInstalledPath(packageIdentity),
                "lib\\net45\\test45.dll"), msBuildNuGetProjectSystem.References.First().Value);

            // Main Act
            await msBuildNuGetProject.UninstallPackageAsync(packageIdentity, testNuGetProjectContext, token);
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            // Check that the reference has been added to MSBuildNuGetProjectSystem
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomPackagesConfigFolderPath);
        }
Exemple #9
0
        public async ValueTask SaveProjectAsync(string projectId, CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);

            cancellationToken.ThrowIfCancellationRequested();

            MSBuildNuGetProject project = await GetMsBuildNuGetProjectAsync(projectId, cancellationToken);

            await project.SaveAsync(cancellationToken);
        }
Exemple #10
0
        private static void OverrideProject(MSBuildNuGetProject project)
        {
            var folderNuGetProjectField = typeof(MSBuildNuGetProject).GetTypeInfo()
                                          .DeclaredFields.First(x => x.FieldType == typeof(FolderNuGetProject));

            folderNuGetProjectField.SetValue(project, new DummyFolderNuGetProject());

            var packagesConfigNuGetProjectField = typeof(MSBuildNuGetProject).GetTypeInfo()
                                                  .DeclaredFields.First(x => x.FieldType == typeof(PackagesConfigNuGetProject));

            packagesConfigNuGetProjectField.SetValue(project, new DummyPackagesConfigNuGetProject(project.Metadata));
        }
        private static bool?IsRestorePackagesWithLockFileEnabled(MSBuildNuGetProject msbuildProject)
        {
            var msbuildProperty = msbuildProject?.ProjectSystem?.GetPropertyValue("RestorePackagesWithLockFile");

            if (msbuildProperty is string restorePackagesWithLockFileValue)
            {
                if (bool.TryParse(restorePackagesWithLockFileValue, out var useLockFile))
                {
                    return(useLockFile);
                }
            }

            return(null);
        }
Exemple #12
0
        public async Task UnzippedPackageInstall_Basic()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();

            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomPackagesConfigFolderPath = TestDirectory.Create())
                {
                    var testSettings           = new Configuration.NullSettings();
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);

                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
                    var token = CancellationToken.None;

                    var projectTargetFramework    = NuGetFramework.Parse("net45");
                    var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
                    var msBuildNuGetProject       = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigFolderPath);
                    var packageIdentity           = NoDependencyLibPackages[0];

                    // Pre-Assert
                    // Check that the packages.config file does not exist
                    Assert.False(File.Exists(randomPackagesConfigPath));
                    // Check that there are no packages returned by PackagesConfigProject
                    var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                    Assert.Equal(0, packagesInPackagesConfig.Count);
                    Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.config file exists after the installation
                    Assert.True(File.Exists(randomPackagesConfigPath));
                    // Check the number of packages and packages returned by PackagesConfigProject after the installation
                    packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                    Assert.Equal(1, packagesInPackagesConfig.Count);
                    Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
                    Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
                }
        }
		public RestoreAndUninstallNuGetPackageAction (
			IMonoDevelopSolutionManager solutionManager,
			IDotNetProject dotNetProject)
		{
			this.dotNetProject = dotNetProject;

			nugetProject = solutionManager.GetNuGetProject (dotNetProject) as MSBuildNuGetProject;
			packagePathResolver = new PackagePathResolver (nugetProject.GetPackagesFolderPath (solutionManager));

			restoreAction = new RestoreNuGetPackagesInProjectAction (
				dotNetProject.DotNetProject,
				nugetProject,
				solutionManager);

			uninstallAction = new UninstallNuGetPackageAction (solutionManager, dotNetProject);
		}
Exemple #14
0
        public RestoreAndUninstallNuGetPackageAction(
            IMonoDevelopSolutionManager solutionManager,
            IDotNetProject dotNetProject)
        {
            this.dotNetProject = dotNetProject;

            nugetProject        = solutionManager.GetNuGetProject(dotNetProject) as MSBuildNuGetProject;
            packagePathResolver = new PackagePathResolver(nugetProject.GetPackagesFolderPath(solutionManager));

            restoreAction = new RestoreNuGetPackagesInProjectAction(
                dotNetProject.DotNetProject,
                nugetProject,
                solutionManager);

            uninstallAction = new UninstallNuGetPackageAction(solutionManager, dotNetProject);
        }
Exemple #15
0
        public async ValueTask <string> BackupProjectAsync(string projectId, CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);

            cancellationToken.ThrowIfCancellationRequested();

            IVsSolutionManager?solutionManager = await _state.SolutionManager.GetValueAsync(cancellationToken);

            Assumes.NotNull(solutionManager);

            string solutionDirectory = await solutionManager.GetSolutionDirectoryAsync();

            await TaskScheduler.Default;

            MSBuildNuGetProject project = await GetMsBuildNuGetProjectAsync(projectId, cancellationToken);

            return(CreateBackup(project, solutionDirectory));
        }
        public async Task TestPacManInstallPackage()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = NoDependencyLibPackages[0];

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);            

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        internal static void UpdateLockFile(
            MSBuildNuGetProject msbuildProject,
            List <NuGetProjectAction> actionsList,
            CancellationToken token)
        {
            if (msbuildProject == null)
            {
                // probably a `nuget.exe install` command, which doesn't support lock files until lock file arguments are implemented
                return;
            }

            var lockFileName   = GetPackagesLockFilePath(msbuildProject);
            var lockFileExists = File.Exists(lockFileName);
            var enableLockFile = IsRestorePackagesWithLockFileEnabled(msbuildProject);

            if (enableLockFile == false && lockFileExists)
            {
                var message = string.Format(CultureInfo.CurrentCulture, Strings.Error_InvalidLockFileInput, lockFileName);
                throw new InvalidOperationException(message);
            }
            else if (enableLockFile == true || lockFileExists)
            {
                var lockFile = GetLockFile(lockFileExists, lockFileName);
                lockFile.Targets[0].TargetFramework = msbuildProject.ProjectSystem.TargetFramework;
                var contentHashUtil = new PackagesConfigContentHashProvider(msbuildProject.FolderNuGetProject);
                ApplyChanges(lockFile, actionsList, contentHashUtil, token);
                PackagesLockFileFormat.Write(lockFileName, lockFile);

                // Add lock file to msbuild project, so it appears in solution explorer and is added to TFS source control.
                if (msbuildProject != null)
                {
                    var projectUri           = new Uri(msbuildProject.MSBuildProjectPath);
                    var lockFileUri          = new Uri(lockFileName);
                    var lockFileRelativePath = projectUri.MakeRelativeUri(lockFileUri).OriginalString;
                    if (Path.DirectorySeparatorChar != '/')
                    {
                        lockFileRelativePath.Replace('/', Path.DirectorySeparatorChar);
                    }
                    msbuildProject.ProjectSystem.AddExistingFile(lockFileRelativePath);
                }
            }
        }
        public NuGetProject AddNewMSBuildProject(string projectName = null, NuGetFramework projectTargetFramework = null, string packagesConfigName = null)
        {
            if (GetNuGetProject(projectName) != null)
            {
                throw new ArgumentException("Project with " + projectName + " already exists");
            }

            var packagesFolder = Path.Combine(SolutionDirectory, PackagesFolder);
            projectName = String.IsNullOrEmpty(projectName) ? Guid.NewGuid().ToString() : projectName;
            var projectFullPath = Path.Combine(SolutionDirectory, projectName);
            Directory.CreateDirectory(projectFullPath);
            var packagesConfigPath = Path.Combine(projectFullPath, String.IsNullOrEmpty(packagesConfigName) ? "packages.config" : packagesConfigName);

            projectTargetFramework = projectTargetFramework ?? NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext(),
                projectFullPath, projectName);
            NuGetProject nuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolder, packagesConfigPath);
            NuGetProjects.Add(nuGetProject);
            return nuGetProject;
        }
Exemple #19
0
        private static string CreateBackup(MSBuildNuGetProject msBuildNuGetProject, string solutionDirectory)
        {
            var guid       = Guid.NewGuid().ToString().Split('-').First();
            var backupPath = Path.Combine(solutionDirectory, "MigrationBackup", guid, NuGetProject.GetUniqueNameOrName(msBuildNuGetProject));

            Directory.CreateDirectory(backupPath);

            // Backup packages.config
            var packagesConfigFullPath = msBuildNuGetProject.PackagesConfigNuGetProject.FullPath;
            var packagesConfigFileName = Path.GetFileName(packagesConfigFullPath);

            File.Copy(packagesConfigFullPath, Path.Combine(backupPath, packagesConfigFileName), overwrite: true);

            // Backup project file
            var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem;
            var projectFullPath           = msBuildNuGetProjectSystem.ProjectFileFullPath;
            var projectFileName           = Path.GetFileName(projectFullPath);

            File.Copy(projectFullPath, Path.Combine(backupPath, projectFileName), overwrite: true);

            return(backupPath);
        }
Exemple #20
0
        private MSBuildNuGetProject GetProject(string project, ICanAddFileStrategy canAddFileStrategy = null)
        {
            MSBuildNuGetProject msBuildNuGetProject;

            if (!_loadedMsBuildNuGetProjects.TryGetValue(project, out msBuildNuGetProject))
            {
                var msbuildNuGetProjectSystem = new CustomMsbuildProjectSystem(
                    msbuildDirectory: MsBuildUtility.GetMsbuildDirectory(null, _console),
                    projectFullPath: project,
                    projectContext: _nuGetProjectContext);

                msBuildNuGetProject = new MSBuildNuGetProject(
                    msbuildNuGetProjectSystem: msbuildNuGetProjectSystem,
                    folderNuGetProjectPath: _packagesFolder,
                    packagesConfigFolderPath: Path.GetDirectoryName(project));

                _loadedMsBuildNuGetProjects.Add(project, msBuildNuGetProject);
            }

            ((CustomMsbuildProjectSystem)msBuildNuGetProject.MSBuildNuGetProjectSystem).ApplyCanAddFileStrategy(canAddFileStrategy);

            return(msBuildNuGetProject);
        }
        public NuGetProject AddNewMSBuildProject(string projectName = null, NuGetFramework projectTargetFramework = null, string packagesConfigName = null)
        {
            if (GetNuGetProject(projectName) != null)
            {
                throw new ArgumentException("Project with " + projectName + " already exists");
            }

            var packagesFolder = Path.Combine(SolutionDirectory, PackagesFolder);

            projectName = String.IsNullOrEmpty(projectName) ? Guid.NewGuid().ToString() : projectName;
            var projectFullPath = Path.Combine(SolutionDirectory, projectName);

            Directory.CreateDirectory(projectFullPath);
            var packagesConfigPath = Path.Combine(projectFullPath, String.IsNullOrEmpty(packagesConfigName) ? "packages.config" : packagesConfigName);

            projectTargetFramework = projectTargetFramework ?? NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext(),
                                                                              projectFullPath, projectName);
            NuGetProject nuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolder, packagesConfigPath);

            NuGetProjects.Add(nuGetProject);
            return(nuGetProject);
        }
        public async Task<NuGetInstallResult> InstallPackage(
            string packageId,
            NuGetVersion version,
            bool prerelease)
        {
            var installPath = Path.Combine(Path.GetTempPath(), "testnuget");

            var projectContext = new EmptyNuGetProjectContext
            {
                PackageExtractionContext = new PackageExtractionContext()
            };

            var references = new List<string>();
            var frameworkReferences = new List<string>();
            var projectSystem = new DelegateNuGetProjectSystem(projectContext, (reference, isFrameworkReference) =>
            {
                if (isFrameworkReference) frameworkReferences.Add(reference);
                else references.Add(reference);
            });

            var project = new MSBuildNuGetProject(projectSystem, installPath, installPath);
            OverrideProject(project);

            var packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, installPath);

            var primaryRepositories = _packageSources.Select(_sourceRepositoryProvider.CreateRepository).ToArray();

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: prerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                version = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    project,
                    resolutionContext,
                    primaryRepositories,
                    NullLogger.Instance,
                    CancellationToken.None).ConfigureAwait(false);

                if (version == null)
                {
                    throw new Exception("Unable to find package");
                }
            }

            var packageIdentity = new PackageIdentity(packageId, version);

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

            return new NuGetInstallResult(references.AsReadOnly(), frameworkReferences.AsReadOnly());
        }
        private static void OverrideProject(MSBuildNuGetProject project)
        {
            var folderNuGetProjectField = typeof(MSBuildNuGetProject).GetTypeInfo()
                .DeclaredFields.First(x => x.FieldType == typeof(FolderNuGetProject));
            folderNuGetProjectField.SetValue(project, new DummyFolderNuGetProject());

            var packagesConfigNuGetProjectField = typeof(MSBuildNuGetProject).GetTypeInfo()
                .DeclaredFields.First(x => x.FieldType == typeof(PackagesConfigNuGetProject));
            packagesConfigNuGetProjectField.SetValue(project, new DummyPackagesConfigNuGetProject(project.Metadata));
        }
        public async Task TestPacManInstallMvcTargetingNet45()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = LatestAspNetPackages[0]; // Microsoft.AspNet.Mvc.6.0.0-beta3

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, includePrelease: true);

            Exception exception = null;
            try
            {
                // Act
                await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                    resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
            Assert.True(exception is InvalidOperationException);
            var errorMessage = String.Format(CultureInfo.CurrentCulture,
                           Strings.UnableToFindCompatibleItems, packageIdentity.Id + " " + packageIdentity.Version.ToNormalizedString(), projectTargetFramework);
            Assert.Equal(errorMessage, exception.Message);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomPackagesConfigPath, randomPackagesConfigFolderPath);
        }
        public async Task TestPacManPreviewUninstallDependencyPackage()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var resolutionContext = new ResolutionContext();
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = PackageWithDependents[2];

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                resolutionContext, testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(2, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[1].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[1].TargetFramework);
            Assert.Equal(PackageWithDependents[0], packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);

            // Main Act
            Exception exception = null;
            try
            {
                var uninstallationContext = new UninstallationContext();
                var packageActions = await nuGetPackageManager.PreviewUninstallPackageAsync(msBuildNuGetProject, "jQuery",
                        uninstallationContext, testNuGetProjectContext, token);
            }
            catch (InvalidOperationException ex)
            {
                exception = ex;
            }
            catch (AggregateException ex)
            {
                exception = ExceptionUtility.Unwrap(ex);
            }

            Assert.NotNull(exception);
            Assert.True(exception is InvalidOperationException);
            Assert.Equal("Unable to uninstall 'jQuery.1.4.4' because 'jQuery.Validation.1.13.1' depends on it.",
                exception.Message);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestMSBuildNuGetProjectUninstallPPFiles()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomProjectFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomProjectFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext, randomProjectFolderPath);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetPackageWithPPFiles(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            using (var packageStream = packageFileInfo.OpenRead())
            {
                // Act
                await msBuildNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
            }

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            // Check that the reference has been added to MSBuildNuGetProjectSystem
            Assert.Equal(3, msBuildNuGetProjectSystem.Files.Count);
            var filesList = msBuildNuGetProjectSystem.Files.ToList();
            Assert.Equal("Foo.cs", filesList[0]);
            Assert.Equal("Bar.cs", filesList[1]);
            Assert.Equal("packages.config", filesList[2]);
            var processedFilesList = msBuildNuGetProjectSystem.ProcessedFiles.ToList();
            Assert.Equal(2, processedFilesList.Count);
            Assert.Equal("Foo.cs", processedFilesList[0]);
            Assert.Equal("Bar.cs", processedFilesList[1]);

            // Main Act
            await msBuildNuGetProject.UninstallPackageAsync(packageIdentity, testNuGetProjectContext, token);
            // Check that the packages.config file does not exist after the uninstallation
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            // Check that the files have been removed from MSBuildNuGetProjectSystem
            Assert.Equal(0, msBuildNuGetProjectSystem.Files.Count);
            Assert.False(Directory.Exists(Path.Combine(randomProjectFolderPath, "Content")));

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomProjectFolderPath);
        }
        public async Task TestPacManOpenReadmeFile()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);
            var packagePathResolver = new PackagePathResolver(packagesFolderPath);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var testNuGetProjectContext = new TestNuGetProjectContext();

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = new PackageIdentity("elmah", new NuGetVersion("1.2.2"));

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            // Set the direct install on the execution context of INuGetProjectContext before installing a package
            testNuGetProjectContext.TestExecutionContext = new TestExecutionContext(packageIdentity);
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(2, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            Assert.Equal(1, testNuGetProjectContext.TestExecutionContext.FilesOpened.Count);
            Assert.True(String.Equals(Path.Combine(packagePathResolver.GetInstallPath(packageIdentity), "ReadMe.txt"),
                testNuGetProjectContext.TestExecutionContext.FilesOpened.First(), StringComparison.OrdinalIgnoreCase));

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestPacManThrowsLatestVersionNotFound()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = "DoesNotExist";

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            Exception exception = null;
            try
            {
                await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                    new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
            Assert.True(exception is InvalidOperationException);
            Assert.Equal("No latest version found for the 'DoesNotExist' for the given source repositories and resolution context", exception.Message);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestPacManPreviewInstallDependencyVersionHighestAndPrerelease()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var primarySourceRepository = sourceRepositoryProvider.GetRepositories().First();

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var dotnetrdfPackageIdentity = new PackageIdentity("dotnetrdf", new NuGetVersion("1.0.8-prerelease1"));
            var resolutionContext = new ResolutionContext(DependencyBehavior.Highest, includePrelease: true);

            var newtonsoftJsonPackageId = "newtonsoft.json";

            // Act
            NuGetVersion latestNewtonsoftPrereleaseVersion = await NuGetPackageManager.GetLatestVersionAsync(newtonsoftJsonPackageId, resolutionContext, primarySourceRepository, CancellationToken.None);
            var newtonsoftJsonPackageIdentity = new PackageIdentity(newtonsoftJsonPackageId, latestNewtonsoftPrereleaseVersion);

            var nuGetProjectActions = (await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, dotnetrdfPackageIdentity, resolutionContext,
                new TestNuGetProjectContext(), primarySourceRepository, null, CancellationToken.None)).ToList();

            // Assert
            Assert.Equal(4, nuGetProjectActions.Count);
            var newtonsoftJsonAction = nuGetProjectActions.Where(a => a.PackageIdentity.Equals(newtonsoftJsonPackageIdentity)).FirstOrDefault();

            Assert.NotNull(newtonsoftJsonAction);
        }
        public async Task TestPacManPreviewInstallPackageThrowsDependencyDowngrade()
        {
            // Arrange
            var packageIdentityA = new PackageIdentity("DotNetOpenAuth.OAuth.Core", new NuGetVersion("4.3.2.13293"));
            var packageIdentityB1 = new PackageIdentity("DotNetOpenAuth.Core", new NuGetVersion("4.3.2.13293"));
            var packageIdentityB2 = new PackageIdentity("DotNetOpenAuth.Core", new NuGetVersion("4.3.4.13329"));
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var primarySourceRepository = sourceRepositoryProvider.GetRepositories().First();

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentityB2, new ResolutionContext(DependencyBehavior.Lowest, includePrelease: true),
                testNuGetProjectContext, primarySourceRepository, null, token);

            // Check that the packages.config file does not exist
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(2, packagesInPackagesConfig.Count);

            Exception exception = null;
            try
            {
                var packageActions = (await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, packageIdentityA,
            new ResolutionContext(), testNuGetProjectContext, primarySourceRepository, null, token)).ToList();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
            Assert.True(exception is InvalidOperationException);
            Assert.Equal("Already referencing a newer version of '" + packageIdentityB1.Id + "'..",
                exception.Message);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestMSBuildNuGetProjectInstall()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetEmptyNet45TestPackage(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString());

            Exception exception = null;
            try
            {
                using (var packageStream = packageFileInfo.OpenRead())
                {
                    // Act
                    await msBuildNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
            Assert.True(exception is InvalidOperationException);
            var errorMessage = String.Format(CultureInfo.CurrentCulture,
                           Strings.UnableToFindCompatibleItems, packageIdentity, projectTargetFramework);
            Assert.Equal(errorMessage, exception.Message);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomPackagesConfigFolderPath);
        }
        public async Task TestPacManUpdateDependencyToPrereleaseVersion()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var primarySourceRepository = sourceRepositoryProvider.GetRepositories().First();

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var webgreasePackageIdentity = new PackageIdentity("WebGrease", new NuGetVersion("1.6.0"));
            var resolutionContext = new ResolutionContext(DependencyBehavior.Lowest, includePrelease: true);

            var newtonsoftJsonPackageId = "newtonsoft.json";

            // Act
            NuGetVersion latestNewtonsoftPrereleaseVersion = await NuGetPackageManager.GetLatestVersionAsync(newtonsoftJsonPackageId, resolutionContext, primarySourceRepository, CancellationToken.None);
            var newtonsoftJsonLatestPrereleasePackageIdentity = new PackageIdentity(newtonsoftJsonPackageId, latestNewtonsoftPrereleaseVersion);

            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, webgreasePackageIdentity, resolutionContext,
                new TestNuGetProjectContext(), primarySourceRepository, null, CancellationToken.None);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(3, packagesInPackagesConfig.Count);

            // Main Act - Update newtonsoft.json to latest pre-release
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, newtonsoftJsonLatestPrereleasePackageIdentity, resolutionContext,
                new TestNuGetProjectContext(), primarySourceRepository, null, CancellationToken.None);
        }
        public async Task TestPacManPreviewInstallWithAllowedVersionsConstraint()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var newtonsoftJsonPackageId = "newtonsoft.json";
            var newtonsoftJsonPackageIdentity = new PackageIdentity(newtonsoftJsonPackageId, NuGetVersion.Parse("4.5.11"));
            var primarySourceRepository = sourceRepositoryProvider.GetRepositories().Single();
            var resolutionContext = new ResolutionContext();
            var testNuGetProjectContext = new TestNuGetProjectContext();

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, newtonsoftJsonPackageIdentity,
                resolutionContext, testNuGetProjectContext, primarySourceRepository, null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(newtonsoftJsonPackageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            var installedPackages = await msBuildNuGetProject.GetInstalledPackagesAsync(token);
            var newtonsoftJsonPackageReference = installedPackages.Where(pr => pr.PackageIdentity.Equals(newtonsoftJsonPackageIdentity)).FirstOrDefault();

            Assert.Null(newtonsoftJsonPackageReference.AllowedVersions);

            const string newPackagesConfig = @"<?xml version='1.0' encoding='utf-8'?>
  <packages>
    <package id='Newtonsoft.Json' version='4.5.11' allowedVersions='[4.0,5.0)' targetFramework='net45' />
  </packages> ";

            File.WriteAllText(randomPackagesConfigPath, newPackagesConfig);

            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(newtonsoftJsonPackageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            installedPackages = await msBuildNuGetProject.GetInstalledPackagesAsync(token);
            newtonsoftJsonPackageReference = installedPackages.Where(pr => pr.PackageIdentity.Equals(newtonsoftJsonPackageIdentity)).FirstOrDefault();

            Assert.NotNull(newtonsoftJsonPackageReference.AllowedVersions);

            Exception exception = null;
            try
            {
                // Main Act
                await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, newtonsoftJsonPackageId,
                    resolutionContext, testNuGetProjectContext, primarySourceRepository, null, token);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
        }
        public async Task TestPacManPreviewUninstallPackageWithDeepDependency()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = PackageWithDeepDependency[6]; // WindowsAzure.Storage.4.3.0

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(7, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[6].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[6].TargetFramework);

            // Main Act
            var packageActions = (await nuGetPackageManager.PreviewUninstallPackageAsync(msBuildNuGetProject, PackageWithDeepDependency[6],
                new UninstallationContext(removeDependencies: true), new TestNuGetProjectContext(), token)).ToList();
            Assert.Equal(7, packageActions.Count);
            var soleSourceRepository = sourceRepositoryProvider.GetRepositories().Single();
            Assert.Equal(PackageWithDeepDependency[6], packageActions[0].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[0].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[2], packageActions[1].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[1].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[5], packageActions[2].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[2].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[4], packageActions[3].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[3].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[1], packageActions[4].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[4].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[3], packageActions[5].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[5].NuGetProjectActionType);
            Assert.Equal(PackageWithDeepDependency[0], packageActions[6].PackageIdentity);
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[6].NuGetProjectActionType);
            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestMSBuildNuGetProjectPSUninstall()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetPackageWithPowershellScripts(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            using (var packageStream = packageFileInfo.OpenRead())
            {
                // Act
                await msBuildNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
            }

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            // Check that the ps script install.ps1 has been executed
            var keys = msBuildNuGetProjectSystem.ScriptsExecuted.Keys.ToList();
            Assert.Equal(2, msBuildNuGetProjectSystem.ScriptsExecuted.Count);
            Assert.Equal("tools\\init.ps1", keys[0]);
            Assert.Equal("tools\\net45\\install.ps1", keys[1]);
            Assert.Equal(1, msBuildNuGetProjectSystem.ScriptsExecuted[keys[0]]);
            Assert.Equal(1, msBuildNuGetProjectSystem.ScriptsExecuted[keys[1]]);

            // Main Act
            await msBuildNuGetProject.UninstallPackageAsync(packageIdentity, testNuGetProjectContext, token);

            // Assert
            // Check that the packages.config file does not exist after uninstallation
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            // Check that the ps script install.ps1 has been executed
            Assert.Equal(3, msBuildNuGetProjectSystem.ScriptsExecuted.Count);
            keys = msBuildNuGetProjectSystem.ScriptsExecuted.Keys.ToList();
            Assert.Equal("tools\\init.ps1", keys[0]);
            Assert.Equal("tools\\net45\\install.ps1", keys[1]);
            Assert.Equal("tools\\net45\\uninstall.ps1", keys[2]);
            Assert.Equal(1, msBuildNuGetProjectSystem.ScriptsExecuted[keys[0]]);
            Assert.Equal(1, msBuildNuGetProjectSystem.ScriptsExecuted[keys[1]]);
            Assert.Equal(1, msBuildNuGetProjectSystem.ScriptsExecuted[keys[2]]);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomPackagesConfigFolderPath);
        }
        public async Task TestPacManGetInstalledPackagesByDependencyOrder()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var testNuGetProjectContext = new TestNuGetProjectContext();

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = PackageWithDeepDependency[6]; // WindowsAzure.Storage.4.3.0

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(7, packagesInPackagesConfig.Count);
            var installedPackages = PackageWithDeepDependency.OrderBy(f => f.Id).ToList();
            for (int i = 0; i < 7; i++)
            {
                Assert.True(installedPackages[i].Equals(packagesInPackagesConfig[i].PackageIdentity));
                Assert.Equal(projectTargetFramework, packagesInPackagesConfig[i].TargetFramework);
            }

            // Main Assert
            List<PackageIdentity> installedPackagesInDependencyOrder = (await nuGetPackageManager.GetInstalledPackagesInDependencyOrder
                (msBuildNuGetProject, testNuGetProjectContext, token)).ToList();
            Assert.Equal(7, installedPackagesInDependencyOrder.Count);
            for (int i = 0; i < 7; i++)
            {
                Assert.Equal(PackageWithDeepDependency[i], installedPackagesInDependencyOrder[i], PackageIdentity.Comparer);
            }

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public async Task TestMSBuildNuGetProjectUninstallWebConfigTransform()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomProjectFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomProjectFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext, randomProjectFolderPath);

            // Important: Added "web.config" to project so that the transform may get applied
            msBuildNuGetProjectSystem.AddFile("web.config", StreamUtility.StreamFromString(
@"<configuration>
    <system.web>
        <compilation baz=""test"" />
    </system.web>
</configuration>
"));
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetPackageWithWebConfigTransform(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString(),
@"<configuration>
    <system.web>
        <compilation debug=""true"" targetFramework=""4.0"" />
    </system.web>
</configuration>
");
            using (var packageStream = packageFileInfo.OpenRead())
            {
                // Act
                await msBuildNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
            }

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            // Check that the reference has been added to MSBuildNuGetProjectSystem
            Assert.Equal(2, msBuildNuGetProjectSystem.Files.Count);
            var filesList = msBuildNuGetProjectSystem.Files.ToList();
            Assert.Equal("web.config", filesList[0]);
            Assert.Equal("packages.config", filesList[1]);

            // Check that the transform is applied properly
            using (var streamReader = new StreamReader(Path.Combine(randomProjectFolderPath, "web.config")))
            {
                AssertEqualExceptWhitespaceAndLineEndings(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <system.web>
        <compilation baz=""test"" debug=""true"" targetFramework=""4.0"" />
    </system.web>
</configuration>
", streamReader.ReadToEnd());
            }

            // Main Act
            await msBuildNuGetProject.UninstallPackageAsync(packageIdentity, testNuGetProjectContext, token);

            // Assert
            // Check that the reference has been added to MSBuildNuGetProjectSystem
            Assert.Equal(1, msBuildNuGetProjectSystem.Files.Count);
            filesList = msBuildNuGetProjectSystem.Files.ToList();
            Assert.Equal("web.config", filesList[0]);

            // Check that the transform is applied properly
            using (var streamReader = new StreamReader(Path.Combine(randomProjectFolderPath, "web.config")))
            {
                AssertEqualExceptWhitespaceAndLineEndings(@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <system.web>
        <compilation baz=""test"" />
    </system.web>
</configuration>
", streamReader.ReadToEnd());
            }

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomProjectFolderPath);
        }
Exemple #38
0
        public async Task <NuGetInstallResult> InstallPackage(
            string packageId,
            NuGetVersion version,
            bool prerelease)
        {
            _initializationException?.Throw();

            var installPath = Path.Combine(Path.GetTempPath(), "dummynuget");

            var projectContext = new EmptyNuGetProjectContext
            {
                PackageExtractionContext = new PackageExtractionContext(NullLogger.Instance)
            };

            PackageIdentity currentIdentity     = null;
            var             references          = new List <string>();
            var             frameworkReferences = new List <string>();
            var             projectSystem       = new DummyNuGetProjectSystem(projectContext,
                                                                              path => references.Add(GetPackagePath(currentIdentity, path)),
                                                                              path => frameworkReferences.Add(path));

            var project = new MSBuildNuGetProject(projectSystem, installPath, installPath);

            // this is a hack to get the identity of the package added in DummyNuGetProjectSystem.AddReference
            project.PackageInstalling += (sender, args) => currentIdentity = args.Identity;
            OverrideProject(project);

            var packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, installPath);

            var primaryRepositories = _packageSources.Select(_sourceRepositoryProvider.CreateRepository).ToArray();

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: prerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                var resolvedPackage = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    project,
                    resolutionContext,
                    primaryRepositories,
                    NullLogger.Instance,
                    CancellationToken.None).ConfigureAwait(false);

                if (resolvedPackage == null)
                {
                    throw new Exception("Unable to find package");
                }

                version = resolvedPackage.LatestVersion;
            }

            var packageIdentity = new PackageIdentity(packageId, version);

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

            return(new NuGetInstallResult(references.AsReadOnly(), frameworkReferences.AsReadOnly()));
        }
        public async Task TestPacManPreviewUpdateWithAllowedVersionsConstraint()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var newtonsoftJsonPackageId = "newtonsoft.json";
            var newtonsoftJsonPackageIdentity = new PackageIdentity(newtonsoftJsonPackageId, NuGetVersion.Parse("4.5.11"));
            var primarySourceRepository = sourceRepositoryProvider.GetRepositories().Single();
            var resolutionContext = new ResolutionContext(DependencyBehavior.Highest);
            var testNuGetProjectContext = new TestNuGetProjectContext();

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, newtonsoftJsonPackageIdentity,
                resolutionContext, testNuGetProjectContext, primarySourceRepository, null, token);

            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, new PackageIdentity("Microsoft.Web.Infrastructure", new NuGetVersion("1.0.0.0")),
                resolutionContext, testNuGetProjectContext, primarySourceRepository, null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(2, packagesInPackagesConfig.Count);
            Assert.Equal(newtonsoftJsonPackageIdentity, packagesInPackagesConfig[1].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[1].TargetFramework);
            var installedPackages = await msBuildNuGetProject.GetInstalledPackagesAsync(token);
            var newtonsoftJsonPackageReference = installedPackages.Where(pr => pr.PackageIdentity.Equals(newtonsoftJsonPackageIdentity)).FirstOrDefault();

            Assert.Null(newtonsoftJsonPackageReference.AllowedVersions);

            const string newPackagesConfig = @"<?xml version='1.0' encoding='utf-8'?>
  <packages>
    <package id='Microsoft.Web.Infrastructure' version='1.0.0.0' targetFramework='net45' />
    <package id='Newtonsoft.Json' version='4.5.11' allowedVersions='[4.0,5.0)' targetFramework='net45' />    
  </packages> ";

            File.WriteAllText(randomPackagesConfigPath, newPackagesConfig);

            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(2, packagesInPackagesConfig.Count);
            Assert.Equal(newtonsoftJsonPackageIdentity, packagesInPackagesConfig[1].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[1].TargetFramework);
            installedPackages = await msBuildNuGetProject.GetInstalledPackagesAsync(token);
            newtonsoftJsonPackageReference = installedPackages.Where(pr => pr.PackageIdentity.Equals(newtonsoftJsonPackageIdentity)).FirstOrDefault();

            Assert.NotNull(newtonsoftJsonPackageReference.AllowedVersions);

            // Main Act
            var nuGetProjectActions = (await nuGetPackageManager.PreviewUpdatePackagesAsync(new List<string>() { newtonsoftJsonPackageId, "Microsoft.Web.Infrastructure" }, msBuildNuGetProject,
                resolutionContext, testNuGetProjectContext, primarySourceRepository, null, token)).ToList();

            // Microsoft.Web.Infrastructure has no updates. However, newtonsoft.json has updates but does not satisfy the version range
            // Hence, no nuget project actions to perform
            Assert.Equal(0, nuGetProjectActions.Count);
        }
Exemple #40
0
        public async Task <NuGetInstallResult> InstallPackage(
            string packageId,
            NuGetVersion version,
            bool prerelease)
        {
            var installPath = Path.Combine(Path.GetTempPath(), "testnuget");

            var projectContext = new EmptyNuGetProjectContext
            {
                PackageExtractionContext = new PackageExtractionContext()
            };

            var references          = new List <string>();
            var frameworkReferences = new List <string>();
            var projectSystem       = new DelegateNuGetProjectSystem(projectContext, (reference, isFrameworkReference) =>
            {
                if (isFrameworkReference)
                {
                    frameworkReferences.Add(reference);
                }
                else
                {
                    references.Add(reference);
                }
            });

            var project = new MSBuildNuGetProject(projectSystem, installPath, installPath);

            OverrideProject(project);

            var packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, installPath);

            var primaryRepositories = _packageSources.Select(_sourceRepositoryProvider.CreateRepository).ToArray();

            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrelease: prerelease,
                includeUnlisted: true,
                versionConstraints: VersionConstraints.None);

            if (version == null)
            {
                // Find the latest version using NuGetPackageManager
                version = await NuGetPackageManager.GetLatestVersionAsync(
                    packageId,
                    project,
                    resolutionContext,
                    primaryRepositories,
                    NullLogger.Instance,
                    CancellationToken.None).ConfigureAwait(false);

                if (version == null)
                {
                    throw new Exception("Unable to find package");
                }
            }

            var packageIdentity = new PackageIdentity(packageId, version);

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

            return(new NuGetInstallResult(references.AsReadOnly(), frameworkReferences.AsReadOnly()));
        }
        public async Task TestPacManReinstallPackages()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);
            var packagePathResolver = new PackagePathResolver(packagesFolderPath);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var folderNuGetProject = msBuildNuGetProject.FolderNuGetProject;
            var packageIdentity = MorePackageWithDependents[3]; // Microsoft.Net.Http.2.2.22

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(3, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[2].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[2].TargetFramework);
            Assert.Equal(MorePackageWithDependents[0], packagesInPackagesConfig[1].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[1].TargetFramework);
            Assert.Equal(MorePackageWithDependents[2], packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            var installedPackageIdentities = (await msBuildNuGetProject.GetInstalledPackagesAsync(token))
                .Select(pr => pr.PackageIdentity);

            // Act
            var packageActions = (await nuGetPackageManager.PreviewReinstallPackagesAsync(installedPackageIdentities, msBuildNuGetProject,
                new ResolutionContext(DependencyBehavior.Highest), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(),
                null, token)).ToList();

            // Assert
            var singlePackageSource = sourceRepositoryProvider.GetRepositories().Single().PackageSource.Source;
            Assert.Equal(6, packageActions.Count);
            Assert.True(MorePackageWithDependents[3].Equals(packageActions[0].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[0].NuGetProjectActionType);
            Assert.True(MorePackageWithDependents[2].Equals(packageActions[1].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[1].NuGetProjectActionType);
            Assert.True(MorePackageWithDependents[0].Equals(packageActions[2].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[2].NuGetProjectActionType);
            Assert.True(MorePackageWithDependents[0].Equals(packageActions[3].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[3].NuGetProjectActionType);
            Assert.Equal(singlePackageSource, packageActions[3].SourceRepository.PackageSource.Source);
            Assert.True(MorePackageWithDependents[2].Equals(packageActions[4].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[4].NuGetProjectActionType);
            Assert.Equal(singlePackageSource, packageActions[4].SourceRepository.PackageSource.Source);
            Assert.True(MorePackageWithDependents[3].Equals(packageActions[5].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[5].NuGetProjectActionType);
            Assert.Equal(singlePackageSource, packageActions[5].SourceRepository.PackageSource.Source);

            // Main Act
            await nuGetPackageManager.ExecuteNuGetProjectActionsAsync(msBuildNuGetProject, packageActions, new TestNuGetProjectContext(), token);

            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(3, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity, packagesInPackagesConfig[2].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[2].TargetFramework);
            Assert.Equal(MorePackageWithDependents[0], packagesInPackagesConfig[1].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[1].TargetFramework);
            Assert.Equal(MorePackageWithDependents[2], packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            Assert.True(File.Exists(folderNuGetProject.GetInstalledPackageFilePath(packageIdentity)));
            Assert.True(File.Exists(folderNuGetProject.GetInstalledPackageFilePath(MorePackageWithDependents[0])));
            Assert.True(File.Exists(folderNuGetProject.GetInstalledPackageFilePath(MorePackageWithDependents[2])));

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
 public PackageCompatibilityNuGetProject(MSBuildNuGetProject nugetProject)
 {
     this.nugetProject = nugetProject;
 }
        public async Task TestPacManPreviewUpdatePackagesSimple()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity0 = PackageWithDependents[0]; // jQuery.1.4.4
            
            var resolutionContext = new ResolutionContext();
            var latestVersion = await NuGetPackageManager.GetLatestVersionAsync(packageIdentity0.Id, new ResolutionContext(),
                sourceRepositoryProvider.GetRepositories().First(), token);

            var packageLatest = new PackageIdentity(packageIdentity0.Id, latestVersion);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity0,
                resolutionContext, new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);
            Assert.Equal(packageIdentity0, packagesInPackagesConfig[0].PackageIdentity);
            Assert.Equal(projectTargetFramework, packagesInPackagesConfig[0].TargetFramework);
            var installedPackageIds = (await msBuildNuGetProject.GetInstalledPackagesAsync(token))
                .Select(pr => pr.PackageIdentity.Id);

            // Main Act
            var packageActions = (await nuGetPackageManager.PreviewUpdatePackagesAsync(installedPackageIds, msBuildNuGetProject,
                new ResolutionContext(DependencyBehavior.Highest), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(),
                null, token)).ToList();

            // Assert
            Assert.Equal(2, packageActions.Count);
            Assert.True(packageIdentity0.Equals(packageActions[0].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Uninstall, packageActions[0].NuGetProjectActionType);
            Assert.True(packageLatest.Equals(packageActions[1].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[1].NuGetProjectActionType);
            Assert.Equal(sourceRepositoryProvider.GetRepositories().Single().PackageSource.Source,
                packageActions[1].SourceRepository.PackageSource.Source);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        private async Task <(InstalledPackageResultStatus, IReadOnlyCollection <NuGetInstalledPackage>)> GetInstalledPackagesAsync(MSBuildNuGetProject project, CancellationToken cancellationToken)
        {
            NuGetInstalledPackage ToNuGetInstalledPackage(Packaging.PackageReference packageReference, FolderNuGetProject packagesFolder)
            {
                var    id               = packageReference.PackageIdentity.Id;
                string requestedRange   = packageReference.PackageIdentity.Version.OriginalVersion;
                string version          = requestedRange;
                var    installPath      = packagesFolder.GetInstalledPath(packageReference.PackageIdentity);
                bool   directDependency = true;

                return(NuGetContractsFactory.CreateNuGetInstalledPackage(id, requestedRange, version, installPath, directDependency));
            }

            FolderNuGetProject packagesFolder = project.FolderNuGetProject;

            var packageReferences = await project.GetInstalledPackagesAsync(cancellationToken);

            var installedPackages = packageReferences.Select(p => ToNuGetInstalledPackage(p, packagesFolder))
                                    .ToList();
            var status = InstalledPackageResultStatus.Successful;

            return(status, installedPackages);
        }
        public async Task TestPacManPreviewInstallOrderOfDependencies()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV2OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = MorePackageWithDependents[3];

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            var packageActions = (await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token)).ToList();

            // Assert
            Assert.Equal(3, packageActions.Count);
            Assert.True(MorePackageWithDependents[0].Equals(packageActions[0].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[0].NuGetProjectActionType);
            Assert.Equal(sourceRepositoryProvider.GetRepositories().Single().PackageSource.Source,
                packageActions[0].SourceRepository.PackageSource.Source);
            Assert.True(MorePackageWithDependents[2].Equals(packageActions[1].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[1].NuGetProjectActionType);
            Assert.Equal(sourceRepositoryProvider.GetRepositories().Single().PackageSource.Source,
                packageActions[0].SourceRepository.PackageSource.Source);
            Assert.True(MorePackageWithDependents[3].Equals(packageActions[2].PackageIdentity));
            Assert.Equal(NuGetProjectActionType.Install, packageActions[2].NuGetProjectActionType);
            Assert.Equal(sourceRepositoryProvider.GetRepositories().Single().PackageSource.Source,
                packageActions[0].SourceRepository.PackageSource.Source);


            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }
        public NuGetProject CreateNuGetProject(EnvDTEProject envDTEProject, INuGetProjectContext nuGetProjectContext)
        {
            if (envDTEProject == null)
            {
                throw new ArgumentNullException(nameof(envDTEProject));
            }

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

            ThreadHelper.ThrowIfNotOnUIThread();

            NuGetProject result = null;

            var projectK = GetProjectKProject(envDTEProject);

            if (projectK != null)
            {
                result = new ProjectKNuGetProject(
                    projectK,
                    envDTEProject.Name,
                    EnvDTEProjectUtility.GetCustomUniqueName(envDTEProject));
            }
            else
            {
                var msBuildNuGetProjectSystem = MSBuildNuGetProjectSystemFactory.CreateMSBuildNuGetProjectSystem(
                    envDTEProject,
                    nuGetProjectContext);

                var isWebSite = msBuildNuGetProjectSystem is WebSiteProjectSystem;

                // Web sites cannot have project.json
                if (!isWebSite)
                {
                    // Find the project file path
                    var projectFilePath = EnvDTEProjectUtility.GetFullProjectPath(envDTEProject);

                    if (!string.IsNullOrEmpty(projectFilePath))
                    {
                        var msbuildProjectFile         = new FileInfo(projectFilePath);
                        var projectNameFromMSBuildPath = Path.GetFileNameWithoutExtension(msbuildProjectFile.Name);

                        // Treat projects with project.json as build integrated projects
                        // Search for projectName.project.json first, then project.json
                        // If the name cannot be determined, search only for project.json
                        string projectJsonPath = null;
                        if (string.IsNullOrEmpty(projectNameFromMSBuildPath))
                        {
                            projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName,
                                                           ProjectJsonPathUtilities.ProjectConfigFileName);
                        }
                        else
                        {
                            projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(msbuildProjectFile.DirectoryName,
                                                                                            projectNameFromMSBuildPath);
                        }

                        if (File.Exists(projectJsonPath))
                        {
                            result = new BuildIntegratedProjectSystem(
                                projectJsonPath,
                                msbuildProjectFile.FullName,
                                envDTEProject,
                                msBuildNuGetProjectSystem,
                                EnvDTEProjectUtility.GetCustomUniqueName(envDTEProject));
                        }
                    }
                }

                // Create a normal MSBuild project if no project.json was found
                if (result == null)
                {
                    var folderNuGetProjectFullPath = _packagesPath();

                    // Project folder path is the packages config folder path
                    var packagesConfigFolderPath = EnvDTEProjectUtility.GetFullPath(envDTEProject);

                    result = new MSBuildNuGetProject(
                        msBuildNuGetProjectSystem,
                        folderNuGetProjectFullPath,
                        packagesConfigFolderPath);
                }
            }

            return(result);
        }
 public NuGetProjectUpgradeWindowModel(MSBuildNuGetProject project, IList <PackageDependencyInfo> packageDependencyInfos)
 {
     PackageDependencyInfos = packageDependencyInfos;
     Project = project;
 }
Exemple #48
0
        private async Task UpdatePackagesAsync(MSBuildProjectSystem project, string packagesDirectory)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesDirectory);
            var nugetProject             = new MSBuildNuGetProject(project, packagesDirectory, project.ProjectFullPath);

            if (!nugetProject.PackagesConfigNuGetProject.PackagesConfigExists())
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("NoPackagesConfig"));
            }

            var versionConstraints = Safe ?
                                     VersionConstraints.ExactMajor | VersionConstraints.ExactMinor :
                                     VersionConstraints.None;

            var projectActions = new List <NuGetProjectAction>();

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var resolutionContext = new ResolutionContext(
                    Resolver.DependencyBehavior.Highest,
                    Prerelease,
                    includeUnlisted: false,
                    versionConstraints: versionConstraints,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                var packageSources = GetPackageSources();

                Console.PrintPackageSources(packageSources);

                var sourceRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);
                if (Id.Count > 0)
                {
                    var targetIds = new HashSet <string>(Id, StringComparer.OrdinalIgnoreCase);

                    var installed = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

                    // If -Id has been specified and has exactly one package, use the explicit version requested
                    var targetVersion = Version != null && Id != null && Id.Count == 1 ? new NuGetVersion(Version) : null;

                    var targetIdentities = installed
                                           .Select(pr => pr.PackageIdentity.Id)
                                           .Where(id => targetIds.Contains(id))
                                           .Select(id => new PackageIdentity(id, targetVersion))
                                           .ToList();

                    if (targetIdentities.Any())
                    {
                        var actions = await packageManager.PreviewUpdatePackagesAsync(
                            targetIdentities,
                            new[] { nugetProject },
                            resolutionContext,
                            project.NuGetProjectContext,
                            sourceRepositories,
                            Enumerable.Empty <SourceRepository>(),
                            CancellationToken.None);

                        projectActions.AddRange(actions);
                    }
                }
                else
                {
                    var actions = await packageManager.PreviewUpdatePackagesAsync(
                        new[] { nugetProject },
                        resolutionContext,
                        project.NuGetProjectContext,
                        sourceRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    projectActions.AddRange(actions);
                }

                await packageManager.ExecuteNuGetProjectActionsAsync(
                    nugetProject,
                    projectActions,
                    project.NuGetProjectContext,
                    sourceCacheContext,
                    CancellationToken.None);
            }

            project.Save();
        }
        public async Task TestMSBuildNuGetProjectEmptyPackageWithDependencies()
        {
            // Arrange
            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));
            var randomTestPackageSourcePath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var token = CancellationToken.None;

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var testNuGetProjectContext = new TestNuGetProjectContext();
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, randomPackagesFolderPath, randomPackagesConfigPath);

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            var packageFileInfo = TestPackages.GetEmptyPackageWithDependencies(randomTestPackageSourcePath,
                packageIdentity.Id, packageIdentity.Version.ToNormalizedString());

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

            Assert.True(File.Exists(randomPackagesConfigPath));
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(1, packagesInPackagesConfig.Count);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(randomTestPackageSourcePath, randomPackagesFolderPath, randomPackagesConfigFolderPath);
        }