/// <summary>
        /// Get all versions for a specific package Id.
        /// </summary>
        /// <param name="sourceRepository"></param>
        /// <param name="packageId"></param>
        /// <param name="project"></param>
        /// <param name="includePrerelease"></param>
        /// <returns></returns>
        public static IEnumerable<NuGetVersion> GetAllVersionsForPackageId(SourceRepository sourceRepository, string packageId, NuGetProject project, bool includePrerelease)
        {
            IEnumerable<string> targetFrameworks = GetProjectTargetFrameworks(project);
            SearchFilter searchfilter = new SearchFilter();
            searchfilter.IncludePrerelease = includePrerelease;
            searchfilter.SupportedFrameworks = targetFrameworks;
            searchfilter.IncludeDelisted = false;
            PSSearchResource resource = sourceRepository.GetResource<PSSearchResource>();
            PSSearchMetadata result = null;
            IEnumerable<NuGetVersion> allVersions = Enumerable.Empty<NuGetVersion>();

            try
            {
                Task<IEnumerable<PSSearchMetadata>> task = resource.Search(packageId, searchfilter, 0, 30, CancellationToken.None);
                result = task.Result
                    .Where(p => string.Equals(p.Identity.Id, packageId, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefault();
                allVersions = result.Versions;
            }
            catch (Exception)
            {
                if (result == null || !allVersions.Any())
                {
                    throw new InvalidOperationException(
                        String.Format(CultureInfo.CurrentCulture,
                        Resources.UnknownPackage, packageId));
                }

            }
            return result.Versions;
        }
		public MultiSourcePackageMetadataProvider(
			IEnumerable<SourceRepository> sourceRepositories,
			SourceRepository optionalLocalRepository,
			IEnumerable<SourceRepository> optionalGlobalLocalRepositories,
			NuGetProject[] projects,
			bool isSolution,
			Common.ILogger logger)
		{
			if (sourceRepositories == null)
			{
				throw new ArgumentNullException(nameof(sourceRepositories));
			}

			if (projects == null)
			{
				throw new ArgumentNullException(nameof(projects));
			}
			_sourceRepositories = sourceRepositories;

			_localRepository = optionalLocalRepository;

			_globalLocalRepositories = optionalGlobalLocalRepositories;

			_projects = projects;

			_isSolution = isSolution;

			if (logger == null)
			{
				throw new ArgumentNullException(nameof(logger));
			}
			_logger = logger;
		}
        /// <summary>
        /// Install package by Identity
        /// </summary>
        /// <param name="project"></param>
        /// <param name="identity"></param>
        /// <param name="resolutionContext"></param>
        /// <param name="projectContext"></param>
        /// <param name="isPreview"></param>
        /// <param name="isForce"></param>
        /// <param name="uninstallContext"></param>
        /// <returns></returns>
        protected async Task InstallPackageByIdentityAsync(NuGetProject project, PackageIdentity identity, ResolutionContext resolutionContext, INuGetProjectContext projectContext, bool isPreview, bool isForce = false, UninstallationContext uninstallContext = null)
        {
            List<NuGetProjectAction> actions = new List<NuGetProjectAction>();
            // For Install-Package -Force
            if (isForce)
            {
                PackageReference installedReference = project.GetInstalledPackagesAsync(CancellationToken.None).Result.Where(p =>
                    StringComparer.OrdinalIgnoreCase.Equals(identity.Id, p.PackageIdentity.Id)).FirstOrDefault();
                if (installedReference != null)
                {
                    actions.AddRange(await PackageManager.PreviewUninstallPackageAsync(project, installedReference.PackageIdentity, uninstallContext, projectContext, CancellationToken.None));
                }
                NuGetProjectAction installAction = NuGetProjectAction.CreateInstallProjectAction(identity, ActiveSourceRepository);
                actions.Add(installAction);
            }
            else
            {
                actions.AddRange(await PackageManager.PreviewInstallPackageAsync(project, identity, resolutionContext, projectContext, ActiveSourceRepository, null, CancellationToken.None));
            }

            if (isPreview)
            {
                PreviewNuGetPackageActions(actions);
            }
            else
            {
                await PackageManager.ExecuteNuGetProjectActionsAsync(project, actions, this, CancellationToken.None);
            }
        }
 public bool TryGetNuGetProject(string name, out NuGetProject nuGetProject)
 {
     nuGetProject = null;
     // First try to find the project name in one of the dictionaries. Then locate the project for that name.
     EnvDTEProjectName envDTEProjectName;
     return TryGetNuGetProjectName(name, out envDTEProjectName) &&
         _nuGetProjectCache.TryGetValue(envDTEProjectName, out nuGetProject);
 }
 private PackageReference GetInstalledPackage(NuGetProject project, string id)
 {
     var installedPackagesTask = project.GetInstalledPackagesAsync(CancellationToken.None);
     installedPackagesTask.Wait();
     var installedPackage = installedPackagesTask.Result
         .Where(p => StringComparer.OrdinalIgnoreCase.Equals(p.PackageIdentity.Id, id))
         .FirstOrDefault();
     return installedPackage;
 }
 public void AddNewNuGetProject(NuGetProject nuGetProject)
 {
     string nuGetProjectName = GetName(nuGetProject);
     if (NuGetProjects.ContainsKey(nuGetProjectName))
     {
         throw new ArgumentException(String.Format(Strings.AnotherNuGetProjectWithSameNameExistsInSolution, nuGetProjectName));
     }
     NuGetProjects.Add(nuGetProjectName, nuGetProject);
 }
        protected virtual bool EnablePackageRestore(NuGetProject nuGetProject)
        {
            var installedPackages = nuGetProject.GetInstalledPackagesAsync(CancellationToken.None).Result;
            if(!installedPackages.Any())
            {
                return true;
            }

            return false;
        }
 /// <summary>
 /// Get project's target frameworks
 /// </summary>
 /// <param name="project"></param>
 /// <returns></returns>
 public static IEnumerable<string> GetProjectTargetFrameworks(NuGetProject project)
 {
     List<string> frameworks = new List<string>();
     NuGetFramework nugetFramework = project.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
     if (nugetFramework != null)
     {
         string framework = nugetFramework.ToString();
         frameworks.Add(framework);
     }
     return frameworks;
 }
		public Task ExecuteNuGetProjectActionsAsync (
			NuGetProject nuGetProject,
			IEnumerable<NuGetProjectAction> nuGetProjectActions,
			INuGetProjectContext nuGetProjectContext,
			CancellationToken token)
		{
			return packageManager.ExecuteNuGetProjectActionsAsync (
				nuGetProject,
				nuGetProjectActions,
				nuGetProjectContext,
				token);
		}
		//public IEnumerable<IVsPackageManagerProvider> PackageManagerProviders { get; private set; }

		//public PackageSearchMetadataCache CachedPackages { get; set; }

		public PackageLoadContext(
			IEnumerable<SourceRepository> sourceRepositories,
			bool isSolution,
			NuGetProject project)
		{
			SourceRepositories = sourceRepositories;
			IsSolution = isSolution;
			//PackageManager = uiContext.PackageManager;
			Projects = new [] { project };
			//PackageManagerProviders = uiContext.PackageManagerProviders;

			//_installedPackagesTask = PackageCollection.FromProjectsAsync(Projects, CancellationToken.None);
		}
		public UninstallNuGetPackageAction (
			IMonoDevelopSolutionManager solutionManager,
			IDotNetProject dotNetProject,
			INuGetProjectContext projectContext,
			INuGetPackageManager packageManager,
			IPackageManagementEvents packageManagementEvents)
		{
			this.dotNetProject = dotNetProject;
			this.context = projectContext;
			this.packageManager = packageManager;
			this.packageManagementEvents = packageManagementEvents;

			project = solutionManager.GetNuGetProject (dotNetProject);
		}
Ejemplo n.º 12
0
		protected void CreateInitNuGetProject ()
		{
			var solutionManager = PackageManagementServices.Workspace.GetSolutionManager (project.ParentSolution);
			nugetProject = solutionManager.GetNuGetProject (project);

			if (nugetProject is INuGetIntegratedProject) {
				PackagesFolderPath = SettingsUtility.GetGlobalPackagesFolder (solutionManager.Settings); 
				packagePathResolver = new VersionFolderPathResolver ( 
					PackagesFolderPath);
			} else {
				PackagesFolderPath = nugetProject.GetPackagesFolderPath (solutionManager);
				folder = new FolderNuGetProject (PackagesFolderPath);
			}
		}
		public UpdatedNuGetPackagesProvider (
			IDotNetProject dotNetProject,
			IMonoDevelopSolutionManager solutionManager,
			NuGetProject project,
			CancellationToken cancellationToken = default(CancellationToken))
		{
			this.dotNetProject = dotNetProject;
			this.project = project;

			var sourceRepositoryProvider = solutionManager.CreateSourceRepositoryProvider ();
			this.sourceRepositories = sourceRepositoryProvider.GetRepositories ().ToList ();

			this.cancellationToken = cancellationToken;
		}
Ejemplo n.º 14
0
        public static async Task <bool> IsNuGetProjectUpgradeableAsync(NuGetProject nuGetProject, Project envDTEProject = null, bool needsAPackagesConfig = true)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (nuGetProject == null && envDTEProject == null)
            {
                return(false);
            }

            nuGetProject = nuGetProject ?? await GetNuGetProject(envDTEProject);

            if (nuGetProject == null)
            {
                return(false);
            }

            // check if current project is packages.config based or not
            var msBuildNuGetProject = nuGetProject as MSBuildNuGetProject;

            if (msBuildNuGetProject == null || (!msBuildNuGetProject.PackagesConfigNuGetProject.PackagesConfigExists() && needsAPackagesConfig))
            {
                return(false);
            }

            // this further check if current project system supports VSProject4 or not which is essential to skip
            // projects like c++ which currently doesn't support VSProject4 implementation for PackageReference
            if (!msBuildNuGetProject.ProjectServices.Capabilities.SupportsPackageReferences)
            {
                return(false);
            }

            if (envDTEProject == null)
            {
                var vsmsBuildNuGetProjectSystem =
                    msBuildNuGetProject.ProjectSystem as VsMSBuildProjectSystem;
                if (vsmsBuildNuGetProjectSystem == null)
                {
                    return(false);
                }
                envDTEProject = vsmsBuildNuGetProjectSystem.VsProjectAdapter.Project;
            }

            if (!EnvDTEProjectUtility.IsSupported(envDTEProject))
            {
                return(false);
            }

            return(IsProjectPackageReferenceCompatible(envDTEProject));
        }
        public UpdatedNuGetPackagesProvider(
            IDotNetProject dotNetProject,
            ISourceRepositoryProvider sourceRepositoryProvider,
            NuGetProject project,
            Action <string, Exception> logError,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            this.dotNetProject = dotNetProject;
            this.project       = project;
            this.logError      = logError;

            this.sourceRepositories = sourceRepositoryProvider.GetRepositories().ToList();

            this.cancellationToken = cancellationToken;
        }
Ejemplo n.º 16
0
        public static FilePath GetPackagesFolderPath(this NuGetProject project, IMonoDevelopSolutionManager solutionManager)
        {
            if (project is BuildIntegratedProjectSystem)
            {
                string globalPackagesPath = BuildIntegratedProjectUtility.GetEffectiveGlobalPackagesFolder(
                    solutionManager.SolutionDirectory,
                    solutionManager.Settings);

                return(new FilePath(globalPackagesPath).FullPath);
            }

            string path = PackagesFolderPathUtility.GetPackagesFolderPath(solutionManager, solutionManager.Settings);

            return(new FilePath(path).FullPath);
        }
Ejemplo n.º 17
0
        public Task <PackageRestoreResult> RestoreMissingPackagesAsync(
            string solutionDirectory,
            NuGetProject nuGetProject,
            INuGetProjectContext nuGetProjectContext,
            CancellationToken token)
        {
            RestoreMissingPackagesSolutionDirectory = solutionDirectory;
            RestoreMissingPackagesProject           = nuGetProject;
            RestoreMissingPackagesProjectContext    = nuGetProjectContext;
            RestoreMissingPackagesCancellationToken = token;

            BeforeRestoreMissingPackagesAsync();

            return(Task.FromResult(RestoreResult));
        }
Ejemplo n.º 18
0
        public UpdatedNuGetPackagesProvider(
            IDotNetProject dotNetProject,
            IMonoDevelopSolutionManager solutionManager,
            NuGetProject project,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            this.dotNetProject = dotNetProject;
            this.project       = project;

            var sourceRepositoryProvider = solutionManager.CreateSourceRepositoryProvider();

            this.sourceRepositories = sourceRepositoryProvider.GetRepositories().ToList();

            this.cancellationToken = cancellationToken;
        }
        protected async Task <IPackageSearchMetadata> GetLatestPackageFromRemoteSourceAsync(
            NuGetProject nugetProject,
            PackageIdentity identity,
            bool includePrerelease)
        {
            var metadataProvider = new MultiSourcePackageMetadataProvider(
                PrimarySourceRepositories,
                optionalLocalRepository: null,
                optionalGlobalLocalRepositories: null,
                projects: new [] { nugetProject },
                isSolution: false,
                logger: NuGet.Common.NullLogger.Instance);

            return(await metadataProvider.GetLatestPackageMetadataAsync(identity, includePrerelease, ConsoleHost.Token));
        }
Ejemplo n.º 20
0
        public Task ExecuteNuGetProjectActionsAsync(
            NuGetProject nuGetProject,
            IEnumerable <NuGetProjectAction> nuGetProjectActions,
            INuGetProjectContext nuGetProjectContext,
            CancellationToken token)
        {
            ExecutedNuGetProject      = nuGetProject;
            ExecutedActions           = nuGetProjectActions.ToList();
            ExecutedProjectContext    = nuGetProjectContext;
            ExecutedCancellationToken = token;

            BeforeExecuteAction();

            return(Task.FromResult(0));
        }
        public string GetPackageInstallPath(NuGetProject nugetProject, PackageIdentity package)
        {
            if (!package.HasVersion)
            {
                return(string.Empty);
            }

            if (nugetProject is INuGetIntegratedProject)
            {
                return(pathResolver.GetPackageDirectory(package.Id, package.Version) ??
                       globalPackagesFolderResolver.GetInstallPath(package.Id, package.Version));
            }

            return(folderNuGetProject.GetInstalledPath(package));
        }
 public Task <IEnumerable <NuGetProjectAction> > PreviewUninstallPackageAsync(
     NuGetProject nuGetProject,
     string packageId,
     UninstallationContext uninstallationContext,
     INuGetProjectContext nuGetProjectContext,
     CancellationToken token)
 {
     return(packageManager.PreviewUninstallPackageAsync(
                nuGetProject,
                packageId,
                uninstallationContext,
                nuGetProjectContext,
                token
                ));
 }
Ejemplo n.º 23
0
        public void EmitNuGetProject(EnvDTEProject vsProject, NuGetProject nuGetProject)
        {
            if (vsProject == null)
            {
                throw new ArgumentNullException(nameof(vsProject));
            }

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

            // Fire and forget. Emit the events.
            Task.Run(() => EmitNuGetProjectAsync(vsProject, nuGetProject));
        }
		public Task ExecuteNuGetProjectActionsAsync (
			NuGetProject nuGetProject,
			IEnumerable<NuGetProjectAction> nuGetProjectActions,
			INuGetProjectContext nuGetProjectContext,
			CancellationToken token)
		{
			ExecutedNuGetProject = nuGetProject;
			ExecutedActions = nuGetProjectActions.ToList ();
			ExecutedProjectContext = nuGetProjectContext;
			ExecutedCancellationToken = token;

			BeforeExecuteAction ();

			return Task.FromResult (0);
		}
        public BuildIntegratedProjectAction(NuGetProject project,
            PackageIdentity packageIdentity,
            NuGetProjectActionType nuGetProjectActionType,
            LockFile originalLockFile,
            RestoreResultPair restoreResultPair,
            IReadOnlyList<SourceRepository> sources,
            IReadOnlyList<NuGetProjectAction> originalActions,
            BuildIntegratedInstallationContext installationContext,
            VersionRange versionRange)
            : base(packageIdentity, nuGetProjectActionType, project, sourceRepository: null, versionRange)
        {
            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

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

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

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

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

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

            OriginalLockFile = originalLockFile;
            RestoreResult = restoreResultPair.Result;
            RestoreResultPair = restoreResultPair;
            Sources = sources;
            OriginalActions = originalActions;
            InstallationContext = installationContext;
        }
        public NuGetProject CreateNuGetProject(DotNetProject project, INuGetProjectContext context)
        {
            Runtime.AssertMainThread();

            var nugetAwareProject = project as INuGetAwareProject;

            if (nugetAwareProject != null)
            {
                return(nugetAwareProject.CreateNuGetProject());
            }

            NuGetProject dotNetCoreProject = DotNetCoreNuGetProject.Create(project);

            if (dotNetCoreProject != null)
            {
                return(dotNetCoreProject);
            }

            NuGetProject packageReferenceProject = PackageReferenceNuGetProject.Create(project);

            if (packageReferenceProject != null)
            {
                return(packageReferenceProject);
            }

            var projectSystem = new MonoDevelopMSBuildNuGetProjectSystem(project, context);

            string projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(project.BaseDirectory, project.Name);

            if (File.Exists(projectJsonPath))
            {
                return(new ProjectJsonBuildIntegratedNuGetProject(
                           projectJsonPath,
                           project.FileName,
                           project,
                           settings));
            }

            string baseDirectory = GetBaseDirectory(project);
            string folderNuGetProjectFullPath = PackagesFolderPathUtility.GetPackagesFolderPath(baseDirectory, settings);

            string packagesConfigFolderPath = project.BaseDirectory;

            return(new MonoDevelopMSBuildNuGetProject(
                       projectSystem,
                       folderNuGetProjectFullPath,
                       packagesConfigFolderPath));
        }
Ejemplo n.º 27
0
        public UninstallNuGetPackageAction(
            IMonoDevelopSolutionManager solutionManager,
            IDotNetProject dotNetProject,
            INuGetProjectContext projectContext,
            INuGetPackageManager packageManager,
            IPackageManagementEvents packageManagementEvents)
        {
            this.dotNetProject           = dotNetProject;
            this.context                 = projectContext;
            this.packageManager          = packageManager;
            this.packageManagementEvents = packageManagementEvents;

            IsErrorWhenPackageNotInstalled = true;

            project = solutionManager.GetNuGetProject(dotNetProject);
        }
Ejemplo n.º 28
0
        public Task <NuGetProject> GetNuGetProjectAsync(string nuGetProjectSafeName)
        {
            GetSolutionManager();

            NuGetProject project = null;

            var dotNetProject = IdeApp.ProjectOperations.CurrentSelectedSolution?.FindProjectByName(nuGetProjectSafeName) as DotNetProject;

            if (dotNetProject != null)
            {
                var factory = new ConsoleHostNuGetProjectFactory(solutionManager.Settings);
                project = factory.CreateNuGetProject(dotNetProject);
            }

            return(Task.FromResult(project));
        }
Ejemplo n.º 29
0
        private static NuGetProjectKind GetProjectKind(NuGetProject nugetProject)
        {
            // Order matters
            NuGetProjectKind projectKind = NuGetProjectKind.Unknown;

            if (nugetProject is BuildIntegratedNuGetProject)
            {
                projectKind = NuGetProjectKind.PackageReference;
            }
            else if (nugetProject is MSBuildNuGetProject)
            {
                projectKind = NuGetProjectKind.PackagesConfig;
            }

            return(projectKind);
        }
        /// <summary>
        /// Uninstall package by Id
        /// </summary>
        /// <param name="project"></param>
        /// <param name="packageId"></param>
        /// <param name="uninstallContext"></param>
        /// <param name="projectContext"></param>
        /// <param name="isPreview"></param>
        /// <returns></returns>
        protected async Task UninstallPackageByIdAsync(NuGetProject project, string packageId, UninstallationContext uninstallContext, INuGetProjectContext projectContext, bool isPreview)
        {
            var actions = await PackageManager.PreviewUninstallPackageAsync(project, packageId, uninstallContext, projectContext, CancellationToken.None);

            if (isPreview)
            {
                PreviewNuGetPackageActions(actions);
            }
            else
            {
                await PackageManager.ExecuteNuGetProjectActionsAsync(project, actions, projectContext, NullSourceCacheContext.Instance, CancellationToken.None);

                // Refresh Manager UI if needed
                RefreshUI(actions);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Get update package identity when -Version is specified.
        /// </summary>
        /// <param name="project"></param>
        /// <param name="installedPackage"></param>
        /// <returns></returns>
        private PackageIdentity GetUpdatePackageIdentityWhenVersionSpecified(NuGetProject project, PackageReference installedPackage)
        {
            PackageIdentity update = null;

            // If Highest/HighestMinor/HighestPatch/Lowest is given after -version switch
            if (IsVersionEnum)
            {
                update = GetPackageUpdate(installedPackage, project, _allowPrerelease, false, null, true, _updateVersionEnum);
            }
            // If a NuGetVersion format is given after -version switch
            else
            {
                update = GetPackageUpdate(installedPackage, project, _allowPrerelease, false, Version);
            }
            return(update);
        }
Ejemplo n.º 32
0
        public async Task OpenReadmeFiles(
            NuGetProject nuGetProject,
            IEnumerable <PackageIdentity> packages,
            INuGetProjectContext nuGetProjectContext,
            CancellationToken token)
        {
            var executionContext = nuGetProjectContext.ExecutionContext;

            if (executionContext != null)
            {
                foreach (var package in packages)
                {
                    await OpenReadmeFiles(nuGetProject, package, executionContext, token);
                }
            }
        }
            public void VerifySuccess(NuGetProject nugetProject)
            {
                // Arrange
                var result = new DownloadResourceResult(Stream.Null, PackageReader.Object);

                // Act & Assert
                Target.EnsurePackageCompatibility(
                    nugetProject,
                    PackageIdentityA,
                    result);

                PackageReader.Verify(x => x.GetMinClientVersion(), Times.Never);
                PackageReader.Verify(x => x.GetPackageTypes(), Times.Never);
                NuspecReader.Verify(x => x.GetMinClientVersion(), Times.Once);
                NuspecReader.Verify(x => x.GetPackageTypes(), Times.Once);
            }
Ejemplo n.º 34
0
        private static void EnsurePackageCompatibility(
            NuGetProject nuGetProject,
            PackageIdentity packageIdentity,
            NuspecReader nuspecReader)
        {
            // Validate that the current version of NuGet satisfies the minVersion attribute specified in the .nuspec
            MinClientVersionUtility.VerifyMinClientVersion(nuspecReader);

            // Validate the package type. There must be zero package types or exactly one package
            // type that is one of the recognized package types.
            var packageTypes   = nuspecReader.GetPackageTypes();
            var identityString = $"{packageIdentity.Id} {packageIdentity.Version.ToNormalizedString()}";

            if (packageTypes.Count > 1)
            {
                throw new PackagingException(string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.MultiplePackageTypesNotSupported,
                                                 identityString));
            }
            else if (packageTypes.Count == 1)
            {
                var packageType       = packageTypes[0];
                var packageTypeString = packageType.Name;
                if (packageType.Version != PackageType.EmptyVersion)
                {
                    packageTypeString += " " + packageType.Version;
                }

                var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);

                if (packageType == PackageType.Legacy ||   // Added for "quirks mode", but not yet fully implemented.
                    packageType == PackageType.Dependency) // A package explicitly stated as a dependency.
                {
                    // These types are always acceptable.
                }
                else
                {
                    throw new PackagingException(string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.UnsupportedPackageType,
                                                     identityString,
                                                     packageTypeString,
                                                     projectName));
                }
            }
        }
        /// <summary>
        /// Marks the packages to be reinstalled on the projects' packages.config
        /// </summary>
        public static async Task MarkPackagesForReinstallation(NuGetProject project, IList <PackageIdentity> packagesToBeReinstalled)
        {
            Debug.Assert(project != null);
            Debug.Assert(packagesToBeReinstalled != null);

            var installedPackageReferences         = (await project.GetInstalledPackagesAsync(CancellationToken.None)).ToList();
            var packageReferencesToUpdateReinstall = new Dictionary <Packaging.PackageReference, Packaging.PackageReference>();

            if (installedPackageReferences != null && installedPackageReferences.Any())
            {
                foreach (var packageReference in installedPackageReferences)
                {
                    bool markForReinstall = packagesToBeReinstalled.Any(p => p.Equals(packageReference.PackageIdentity));

                    // Determine if requireReinstallation attribute needs to be updated.
                    if (packageReference.RequireReinstallation ^ markForReinstall)
                    {
                        var newPackageReference = new Packaging.PackageReference(packageReference.PackageIdentity, packageReference.TargetFramework,
                                                                                 packageReference.IsUserInstalled, packageReference.IsDevelopmentDependency, markForReinstall);

                        packageReferencesToUpdateReinstall.Add(packageReference, newPackageReference);
                    }
                }

                var projectFullPath        = project.GetMetadata <string>(NuGetProjectMetadataKeys.FullPath);
                var packagesConfigFullPath = Path.Combine(projectFullPath ?? string.Empty, ProjectManagement.Constants.PackageReferenceFile);

                // Create new file or overwrite existing file
                if (File.Exists(packagesConfigFullPath))
                {
                    try
                    {
                        using (var writer = new PackagesConfigWriter(packagesConfigFullPath, createNew: false))
                        {
                            foreach (var entry in packageReferencesToUpdateReinstall)
                            {
                                writer.UpdatePackageEntry(entry.Key, entry.Value);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.WriteErrorToActivityLog(ex);
                    }
                }
            }
        }
Ejemplo n.º 36
0
        public async Task <InstalledPackagesResult> GetInstalledPackagesAsync(Guid projectId, CancellationToken cancellationToken)
        {
            try
            {
                // Just in case we're on the UI thread, switch to background thread. Very low cost (does not schedule new task) if already on background thread.
                await TaskScheduler.Default;

                NuGetProject project = await _solutionManager.GetNuGetProjectAsync(projectId.ToString());

                if (project == null)
                {
                    return(NuGetContractsFactory.CreateInstalledPackagesResult(InstalledPackageResultStatus.ProjectNotReady, packages: null));
                }

                InstalledPackageResultStatus status;
                IReadOnlyCollection <NuGetInstalledPackage> installedPackages;

                switch (project)
                {
                case BuildIntegratedNuGetProject packageReferenceProject:
                    (status, installedPackages) = await GetInstalledPackagesAsync(packageReferenceProject, cancellationToken);

                    break;

                case MSBuildNuGetProject packagesConfigProject:
                    (status, installedPackages) = await GetInstalledPackagesAsync(packagesConfigProject, cancellationToken);

                    break;

                default:
                    (status, installedPackages) = await GetInstalledPackagesAsync(project, cancellationToken);

                    break;
                }

                return(NuGetContractsFactory.CreateInstalledPackagesResult(status, installedPackages));
            }
            catch (Exception exception)
            {
                var extraProperties = new Dictionary <string, object>();
                extraProperties["projectId"] = projectId.ToString();
                await _telemetryProvider.PostFaultAsync(exception, typeof(NuGetProjectService).FullName, extraProperties : extraProperties);

                throw;
            }
        }
Ejemplo n.º 37
0
            public async Task VerifySuccessAsync(NuGetProject nugetProject)
            {
                // Arrange
                var result = new DownloadResourceResult(Stream.Null, PackageReader.Object, string.Empty);

                // Act & Assert
                await Target.EnsurePackageCompatibilityAsync(
                    nugetProject,
                    PackageIdentityA,
                    result,
                    CancellationToken.None);

                PackageReader.Verify(x => x.GetMinClientVersion(), Times.Never);
                PackageReader.Verify(x => x.GetPackageTypes(), Times.Never);
                NuspecReader.Verify(x => x.GetMinClientVersion(), Times.Once);
                NuspecReader.Verify(x => x.GetPackageTypes(), Times.Once);
            }
Ejemplo n.º 38
0
        public UpdateNuGetPackageAction(
            IMonoDevelopSolutionManager solutionManager,
            IDotNetProject dotNetProject,
            INuGetProjectContext projectContext,
            INuGetPackageManager packageManager,
            IPackageManagementEvents packageManagementEvents)
        {
            this.dotNetProject           = dotNetProject;
            this.context                 = projectContext;
            this.packageManager          = packageManager;
            this.packageManagementEvents = packageManagementEvents;

            project = solutionManager.GetNuGetProject(dotNetProject);

            sourceRepositoryProvider = solutionManager.CreateSourceRepositoryProvider();
            primarySources           = sourceRepositoryProvider.GetRepositories().ToList();
        }
		public UpdateNuGetPackageAction (
			IMonoDevelopSolutionManager solutionManager,
			IDotNetProject dotNetProject,
			INuGetProjectContext projectContext,
			INuGetPackageManager packageManager,
			IPackageManagementEvents packageManagementEvents)
		{
			this.dotNetProject = dotNetProject;
			this.context = projectContext;
			this.packageManager = packageManager;
			this.packageManagementEvents = packageManagementEvents;

			project = solutionManager.GetNuGetProject (dotNetProject);

			sourceRepositoryProvider = solutionManager.CreateSourceRepositoryProvider ();
			primarySources = sourceRepositoryProvider.GetRepositories ().ToList ();
		}
 public Task <IEnumerable <NuGetProjectAction> > PreviewUpdatePackagesAsync(
     NuGetProject nuGetProject,
     ResolutionContext resolutionContext,
     INuGetProjectContext nuGetProjectContext,
     IEnumerable <SourceRepository> primarySources,
     IEnumerable <SourceRepository> secondarySources,
     CancellationToken token)
 {
     return(packageManager.PreviewUpdatePackagesAsync(
                new [] { nuGetProject },
                resolutionContext,
                nuGetProjectContext,
                primarySources,
                secondarySources,
                token
                ));
 }
		public RestoreNuGetPackagesInProjectAction (
			DotNetProject project,
			NuGetProject nugetProject,
			IMonoDevelopSolutionManager solutionManager)
		{
			this.project = project;
			this.nugetProject = nugetProject;
			this.solutionManager = solutionManager;

			packageManagementEvents = PackageManagementServices.PackageManagementEvents;

			restoreManager = new PackageRestoreManager (
				solutionManager.CreateSourceRepositoryProvider (),
				solutionManager.Settings,
				solutionManager
			);
		}
Ejemplo n.º 42
0
        /// <summary>
        /// If the project is non-xproj and has no xproj references it may fallback to v1.
        /// </summary>
        public static async Task <int> GetLockFileVersion(
            NuGetProject project,
            ExternalProjectReferenceContext referenceContext)
        {
            var lockFileVersion = LockFileFormat.Version;

            var buildProject = project as BuildIntegratedNuGetProject;

            if (buildProject != null)
            {
                var references = await buildProject.GetProjectReferenceClosureAsync(referenceContext);

                lockFileVersion = LockFileUtilities.GetLockFileVersion(references);
            }

            return(lockFileVersion);
        }
 public Task <ResolvedPackage> GetLatestVersionAsync(
     string packageId,
     NuGetProject project,
     ResolutionContext resolutionContext,
     IEnumerable <SourceRepository> sources,
     ILogger log,
     CancellationToken token)
 {
     return(NuGetPackageManager.GetLatestVersionAsync(
                packageId,
                project,
                resolutionContext,
                sources,
                log,
                token
                ));
 }
        /// <summary>
        /// Normalize package Id input against server metadata for project K, which is case-sensitive.
        /// </summary>
        /// <param name="project"></param>
        protected void NormalizePackageId(NuGetProject project)
        {
            if (!(project is ProjectKNuGetProjectBase))
            {
                return;
            }

            var metadata = NuGetUIThreadHelper.JoinableTaskFactory.Run(() => GetPackagesFromRemoteSourceAsync(Id, includePrerelease: true));

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

            // note that we're assuming that package id is the same for all versions.
            Id = metadata.First().Identity.Id;
        }
Ejemplo n.º 45
0
        public Task <NuGetVersion> GetLatestVersionAsync(
            string packageId,
            NuGetProject project,
            ResolutionContext resolutionContext,
            IEnumerable <SourceRepository> sources,
            ILogger log,
            CancellationToken token)
        {
            GetLatestVersionPackageId         = packageId;
            GetLatestVersionProject           = project;
            GetLatestVersionResolutionContext = resolutionContext;
            GetLatestVersionSources           = sources.ToList();
            GetLatestVersionLogger            = log;
            GetLatestVersionCancellationToken = token;

            return(Task.FromResult(LatestVersion));
        }
        public RestoreNuGetPackagesInProjectAction(
            DotNetProject project,
            NuGetProject nugetProject,
            IMonoDevelopSolutionManager solutionManager)
        {
            this.project         = project;
            this.nugetProject    = nugetProject;
            this.solutionManager = solutionManager;

            packageManagementEvents = PackageManagementServices.PackageManagementEvents;

            restoreManager = new PackageRestoreManager(
                solutionManager.CreateSourceRepositoryProvider(),
                solutionManager.Settings,
                solutionManager
                );
        }
        public PreviewResult(
            NuGetProject target,
            IEnumerable<PackageIdentity> added,
            IEnumerable<PackageIdentity> deleted,
            IEnumerable<UpdatePreviewResult> updated)
        {
            string s = null;
            if (target.TryGetMetadata<string>(NuGetProjectMetadataKeys.Name, out s))
            {
                Name = s;
            }
            else
            {
                Name = "Unknown Project";
            }

            Added = added;
            Deleted = deleted;
            Updated = updated;
        }
        private void CreatePackageManagerControl()
        {
            _container = Initialize();

            this.Title = "NuGet Standalone UI";
            Height = 800;
            Width = 1000;
            
            var repositoryProvider = new SourceRepositoryProvider(_settings, Repository.Provider.GetVisualStudio());
            var settings = new DefaultSettings();

            var testSolutionManager = new TestSolutionManager(@"c:\temp\test");
            
            var projectA = testSolutionManager.AddNewMSBuildProject("projectA");
            var projectB = testSolutionManager.AddNewMSBuildProject("projectB");
            //var projectC = testSolutionManager.AddProjectKProject("projectK");

            var projects = new NuGetProject[] { projectA, projectB };            

            var packageRestoreManager = new PackageRestoreManager(repositoryProvider, settings, testSolutionManager);
            var contextFactory = new StandaloneUIContextFactory(
                repositoryProvider, 
                testSolutionManager, 
                settings, 
                packageRestoreManager: packageRestoreManager,
                optionsPage: null);
            var context = contextFactory.Create(@"c:\temp\test\settings.txt", projects);
            var uiController = _uiServiceFactory.Create(
                context,
                new NuGetUIProjectContext(new StandaloneUILogger(_textBox, _scrollViewer), _sourceControlManagerProvider, _commonOperations));

            PackageManagerModel model = new PackageManagerModel(uiController, context);
            model.SolutionName = "test solution";
            _packageManagerControl = new PackageManagerControl(model, _settings);
            layoutGrid.Children.Add(_packageManagerControl);
        }
		public Task<PackageRestoreResult> RestoreMissingPackagesAsync (
			string solutionDirectory,
			NuGetProject nuGetProject,
			INuGetProjectContext nuGetProjectContext,
			CancellationToken token)
		{
			RestoreMissingPackagesSolutionDirectory = solutionDirectory;
			RestoreMissingPackagesProject = nuGetProject;
			RestoreMissingPackagesProjectContext = nuGetProjectContext;
			RestoreMissingPackagesCancellationToken = token;

			BeforeRestoreMissingPackagesAsync ();

			return Task.FromResult (RestoreResult);
		}
		public Task<PackageRestoreResult> RestoreMissingPackagesAsync (
			string solutionDirectory,
			NuGetProject nuGetProject,
			INuGetProjectContext nuGetProjectContext,
			CancellationToken token)
		{
			return restoreManager.RestoreMissingPackagesAsync (
				solutionDirectory,
				nuGetProject,
				nuGetProjectContext,
				token
			);
		}
        /// <summary>
        /// Gives the preview as a list of NuGetProjectActions that will be performed to install <param name="packageIdentity"></param> into <param name="nuGetProject"></param>
        /// <param name="resolutionContext"></param> and <param name="nuGetProjectContext"></param> are used in the process
        /// </summary>
        public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
            ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext,
            SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token)
        {
            if (nuGetProject is ProjectManagement.Projects.ProjectKNuGetProjectBase)
            {
                var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySourceRepository);
                return new NuGetProjectAction[] { action };
            }

            var primarySources = new List<SourceRepository>() { primarySourceRepository };
            return await PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext,
                nuGetProjectContext, primarySources, secondarySources, token);
        }
        public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
            ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext,
            IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources,
            CancellationToken token)
        {
            if(nuGetProject == null)
            {
                throw new ArgumentNullException("nuGetProject");
            }

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

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

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

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

            if (secondarySources == null)
            {
                secondarySources = SourceRepositoryProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled);
            }

            if(!primarySources.Any())
            {
                throw new ArgumentException("primarySources");
            }

            if(packageIdentity.Version == null)
            {
                throw new ArgumentNullException("packageIdentity.Version");
            }

            // TODO: BUGBUG: HACK: Multiple primary repositories is mainly intended for nuget.exe at the moment
            // The following special case for ProjectK is not correct, if they used nuget.exe
            // and multiple repositories in the -Source switch
            if (nuGetProject is ProjectManagement.Projects.ProjectKNuGetProjectBase)
            {
                var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySources.First());
                return new NuGetProjectAction[] { action };
            }

            var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);
            var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity);
            if(oldListOfInstalledPackages.Any(p => p.Equals(packageIdentity)))
            {
                string projectName;
                nuGetProject.TryGetMetadata<string>(NuGetProjectMetadataKeys.Name, out projectName);
                throw new InvalidOperationException(String.Format(NuGet.ProjectManagement.Strings.PackageAlreadyExistsInProject, packageIdentity, projectName ?? String.Empty));
            }

            List<NuGetProjectAction> nuGetProjectActions = new List<NuGetProjectAction>();
            // TODO: these sources should be ordered
            // TODO: search in only the active source but allow dependencies to come from other sources?

            var effectiveSources = GetEffectiveSources(primarySources, secondarySources);
            
            if (resolutionContext.DependencyBehavior != DependencyBehavior.Ignore)
            {
                try
                {
                    bool downgradeAllowed = false;
                    var packageTargetsForResolver = new HashSet<PackageIdentity>(oldListOfInstalledPackages, PackageIdentity.Comparer);
                    // Note: resolver needs all the installed packages as targets too. And, metadata should be gathered for the installed packages as well
                    var installedPackageWithSameId = packageTargetsForResolver.Where(p => p.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if(installedPackageWithSameId != null)
                    {
                        packageTargetsForResolver.Remove(installedPackageWithSameId);
                        if(installedPackageWithSameId.Version > packageIdentity.Version)
                        {
                            // Looks like the installed package is of higher version than one being installed. So, we take it that downgrade is allowed
                            downgradeAllowed = true;
                        }
                    }
                    packageTargetsForResolver.Add(packageIdentity);

                    // Step-1 : Get metadata resources using gatherer
                    var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
                    nuGetProjectContext.Log(MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, targetFramework);

                    var primaryPackages = new List<PackageIdentity>() { packageIdentity };

                    // If any targets are prerelease we should gather with prerelease on and filter afterwards
                    bool includePrereleaseInGather = resolutionContext.IncludePrerelease || (packageTargetsForResolver.Any(p => (p.HasVersion && p.Version.IsPrerelease)));
                    ResolutionContext contextForGather = new ResolutionContext(resolutionContext.DependencyBehavior, includePrereleaseInGather, resolutionContext.IncludeUnlisted);

                    var availablePackageDependencyInfoWithSourceSet = await ResolverGather.GatherPackageDependencyInfo(contextForGather,
                        primaryPackages,
                        packageTargetsForResolver,
                        targetFramework,
                        primarySources,
                        effectiveSources,
                        token);

                    if (!availablePackageDependencyInfoWithSourceSet.Any())
                    {
                        throw new InvalidOperationException(String.Format(Strings.UnableToGatherDependencyInfo, packageIdentity));
                    }

                    // Prune the results down to only what we would allow to be installed

                    // Keep only the target package we are trying to install for that Id
                    IEnumerable<SourceDependencyInfo> prunedAvailablePackages = PrunePackageTree.RemoveAllVersionsForIdExcept(availablePackageDependencyInfoWithSourceSet, packageIdentity);

                    if (!resolutionContext.IncludePrerelease)
                    {
                        prunedAvailablePackages = PrunePackageTree.PrunePreleaseForStableTargets(prunedAvailablePackages, packageTargetsForResolver);
                    }

                    // Remove versions that do not satisfy 'allowedVersions' attribute in packages.config, if any
                    prunedAvailablePackages = PrunePackageTree.PruneDisallowedVersions(prunedAvailablePackages, projectInstalledPackageReferences);

                    // TODO: prune down level packages?

                    // Step-2 : Call IPackageResolver.Resolve to get new list of installed packages
                    // TODO: Consider using IPackageResolver once it is extensible
                    var packageResolver = new PackageResolver(resolutionContext.DependencyBehavior);
                    nuGetProjectContext.Log(MessageLevel.Info, Strings.AttemptingToResolveDependencies, packageIdentity, resolutionContext.DependencyBehavior);

                    // Note: resolver prefers installed package versions if the satisfy the dependency version constraints
                    // So, since we want an exact version of a package, create a new list of installed packages where the packageIdentity being installed
                    // is present after removing the one with the same id
                    var preferredPackageReferences = new List<PackageReference>(projectInstalledPackageReferences.Where(pr =>
                        !pr.PackageIdentity.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)));
                    preferredPackageReferences.Add(new PackageReference(packageIdentity, targetFramework));

                    IEnumerable<PackageIdentity> newListOfInstalledPackages = packageResolver.Resolve(packageTargetsForResolver,
                        prunedAvailablePackages,
                        preferredPackageReferences,
                        token);
                    if (newListOfInstalledPackages == null)
                    {
                        throw new InvalidOperationException(String.Format(Strings.UnableToResolveDependencyInfo, packageIdentity, resolutionContext.DependencyBehavior));
                    }

                    // Step-3 : Get the list of nuGetProjectActions to perform, install/uninstall on the nugetproject
                    // based on newPackages obtained in Step-2 and project.GetInstalledPackages                    

                    nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvingActionsToInstallPackage, packageIdentity);
                    var newPackagesToUninstall = new List<PackageIdentity>();
                    foreach(var oldInstalledPackage in oldListOfInstalledPackages)
                    {
                        var newPackageWithSameId = newListOfInstalledPackages
                            .Where(np => oldInstalledPackage.Id.Equals(np.Id, StringComparison.OrdinalIgnoreCase) &&
                            !oldInstalledPackage.Version.Equals(np.Version)).FirstOrDefault();

                        if(newPackageWithSameId != null)
                        {
                            if(!downgradeAllowed && oldInstalledPackage.Version > newPackageWithSameId.Version)
                            {
                                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.NewerVersionAlreadyReferenced, newPackageWithSameId.Id));
                            }
                            newPackagesToUninstall.Add(oldInstalledPackage);
                        }
                    }
                    var newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p));

                    foreach (PackageIdentity newPackageToUninstall in newPackagesToUninstall)
                    {
                        nuGetProjectActions.Add(NuGetProjectAction.CreateUninstallProjectAction(newPackageToUninstall));
                    }

                    var comparer = PackageIdentity.Comparer;

                    foreach (PackageIdentity newPackageToInstall in newPackagesToInstall)
                    {
                        // find the package match based on identity
                        SourceDependencyInfo sourceDepInfo = prunedAvailablePackages.Where(p => comparer.Equals(p, newPackageToInstall)).SingleOrDefault();

                        if (sourceDepInfo == null)
                        {
                            // this really should never happen
                            throw new InvalidOperationException(String.Format(Strings.PackageNotFound, packageIdentity));
                        }

                        nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(newPackageToInstall, sourceDepInfo.Source));
                    }
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                catch (AggregateException aggregateEx)
                {
                    throw new InvalidOperationException(aggregateEx.Message, aggregateEx);
                }
                catch (Exception ex)
                {
                    if (String.IsNullOrEmpty(ex.Message))
                    {
                        throw new InvalidOperationException(String.Format(Strings.PackageCouldNotBeInstalled, packageIdentity), ex);
                    }
                    else
                    {
                        throw new InvalidOperationException(ex.Message, ex);
                    }
                }
            }
            else
            {
                var sourceRepository = await GetSourceRepository(packageIdentity, effectiveSources);
                nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity, sourceRepository));
            }

            nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvedActionsToInstallPackage, packageIdentity);
            return nuGetProjectActions;
        }
        /// <summary>
        /// Gives the preview as a list of NuGetProjectActions that will be performed to uninstall <param name="packageId"></param> into <param name="nuGetProject"></param>
        /// <param name="uninstallationContext"></param> and <param name="nuGetProjectContext"></param> are used in the process
        /// </summary>
        public async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
            UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (nuGetProject == null)
            {
                throw new ArgumentNullException("nuGetProject");
            }

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

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

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

            // Step-1: Get the packageIdentity corresponding to packageId and check if it exists to be uninstalled
            var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token);
            PackageReference packageReference = installedPackages
                .Where(pr => pr.PackageIdentity.Equals(packageIdentity)).FirstOrDefault();
            if (packageReference == null || packageReference.PackageIdentity == null)
            {
                throw new ArgumentException(String.Format(Strings.PackageToBeUninstalledCouldNotBeFound,
                    packageIdentity.Id, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)));
            }

            return await PreviewUninstallPackageAsyncPrivate(nuGetProject, packageReference, uninstallationContext, nuGetProjectContext, token);
        }
        /// <summary>
        /// Executes the list of <param name="nuGetProjectActions"></param> on <param name="nuGetProject"></param>, which is likely obtained by calling into PreviewInstallPackageAsync
        /// <param name="nuGetProjectContext"></param> is used in the process
        /// </summary>
        public async Task ExecuteNuGetProjectActionsAsync(NuGetProject nuGetProject, IEnumerable<NuGetProjectAction> nuGetProjectActions,
            INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (nuGetProject == null)
            {
                throw new ArgumentNullException("nuGetProject");
            }

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

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

            Exception executeNuGetProjectActionsException = null;
            Stack<NuGetProjectAction> executedNuGetProjectActions = new Stack<NuGetProjectAction>();
            HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted = new HashSet<PackageIdentity>(PackageIdentity.Comparer);
            try
            {
                await nuGetProject.PreProcessAsync(nuGetProjectContext, token);
                foreach (NuGetProjectAction nuGetProjectAction in nuGetProjectActions)
                {
                    executedNuGetProjectActions.Push(nuGetProjectAction);
                    if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall)
                    {
                        await ExecuteUninstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
                    }
                    else
                    {
                        using (var targetPackageStream = new MemoryStream())
                        {
                            await PackageDownloader.GetPackageStream(nuGetProjectAction.SourceRepository, nuGetProjectAction.PackageIdentity, targetPackageStream, token);
                            await ExecuteInstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, targetPackageStream, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
                        }
                    }

                    string toFromString = nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Install ? Strings.To : Strings.From;
                    nuGetProjectContext.Log(MessageLevel.Info, Strings.SuccessfullyExecutedPackageAction,
                        nuGetProjectAction.NuGetProjectActionType.ToString().ToLowerInvariant(), nuGetProjectAction.PackageIdentity.ToString(), toFromString + " " + nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name));
                }
                await nuGetProject.PostProcessAsync(nuGetProjectContext, token);

                await OpenReadmeFile(nuGetProjectContext, token);
            }
            catch (Exception ex)
            {
                executeNuGetProjectActionsException = ex;
            }

            if(executeNuGetProjectActionsException != null)
            {
                await Rollback(nuGetProject, executedNuGetProjectActions, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
            }

            // Delete the package directories as the last step, so that, if an uninstall had to be rolled back, we can just use the package file on the directory
            // Also, always perform deletion of package directories, even in a rollback, so that there are no stale package directories
            foreach(var packageWithDirectoryToBeDeleted in packageWithDirectoriesToBeDeleted)
            {
                await DeletePackage(packageWithDirectoryToBeDeleted, nuGetProjectContext, token);
            }

            // Clear direct install
            SetDirectInstall(null, nuGetProjectContext);

            if(executeNuGetProjectActionsException != null)
            {
                throw executeNuGetProjectActionsException;
            }
        }
 public string GetDisplayName(NuGetProject nuGetProject, VSSolutionManager solutionManager)
 {
     string safeName = solutionManager.GetNuGetProjectSafeName(nuGetProject);
     Project project = solutionManager.GetDTEProject(safeName);
     return EnvDTEProjectUtility.GetDisplayName(project);
 }       
Ejemplo n.º 56
0
 public NuGetJsonProject(NuGetProject project)
 {
     Dependencies = project.RawDependencies;
     PackagesDirectory = project.PackagesDirectory;
     Frameworks = project.Frameworks;
 }
 /// <summary>
 /// Installs the latest version of the given <param name="packageId"></param> to NuGetProject <param name="nuGetProject"></param>
 /// <param name="resolutionContext"></param> and <param name="nuGetProjectContext"></param> are used in the process
 /// </summary>
 public async Task InstallPackageAsync(NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext,
     INuGetProjectContext nuGetProjectContext, SourceRepository primarySourceRepository,
     IEnumerable<SourceRepository> secondarySources, CancellationToken token)
 {
     await InstallPackageAsync(nuGetProject, packageId, resolutionContext, nuGetProjectContext,
         new List<SourceRepository>() { primarySourceRepository }, secondarySources, token);
 }
 public string GetDisplayName(NuGetProject nuGetProject)
 {
     VSSolutionManager solutionManager = (VSSolutionManager)_solutionManager;
     return GetDisplayName(nuGetProject, solutionManager);
 }      
		public string GetNuGetProjectSafeName (NuGetProject nuGetProject)
		{
			throw new NotImplementedException ();
		}
        private async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsyncPrivate(NuGetProject nuGetProject, PackageReference packageReference,
            UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if(SolutionManager == null)
            {
                throw new InvalidOperationException(Strings.SolutionManagerNotAvailableForUninstall);
            }

            if (nuGetProject is ProjectManagement.Projects.ProjectKNuGetProjectBase)
            {
                var action = NuGetProjectAction.CreateUninstallProjectAction(packageReference.PackageIdentity);
                return new NuGetProjectAction[] { action };
            }

            // Step-1 : Get the metadata resources from "packages" folder or custom repository path
            var packageIdentity = packageReference.PackageIdentity;
            var packageReferenceTargetFramework = packageReference.TargetFramework;
            nuGetProjectContext.Log(MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, packageReferenceTargetFramework);

            // TODO: IncludePrerelease is a big question mark
            var installedPackageIdentities = (await nuGetProject.GetInstalledPackagesAsync(token)).Select(pr => pr.PackageIdentity);
            var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolder(installedPackageIdentities,
                packageReferenceTargetFramework, includePrerelease: true);

            nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvingActionsToUninstallPackage, packageIdentity);
            // Step-2 : Determine if the package can be uninstalled based on the metadata resources
            var packagesToBeUninstalled = UninstallResolver.GetPackagesToBeUninstalled(packageIdentity, dependencyInfoFromPackagesFolder, installedPackageIdentities, uninstallationContext);

            var nuGetProjectActions = packagesToBeUninstalled.Select(p => NuGetProjectAction.CreateUninstallProjectAction(p));

            nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvedActionsToUninstallPackage, packageIdentity);
            return nuGetProjectActions;
        }