Beispiel #1
0
        public async Task<IEnumerable<PackageAction>> ResolveActionsAsync(
            PackageIdentity packageIdentity,
            PackageActionType operation,
            InstallationTarget target)
        {
            // Construct the Action Resolver
            var oldResolver = new OldResolver();
            if (Logger != null)
            {
                oldResolver.Logger = new ShimLogger(Logger);
            }

            // Apply context settings
            ApplyContext(oldResolver);

            var packageManager = target.GetRequiredFeature<IPackageManager>();

            var nullProjectManager = new NullProjectManager(
                new CoreInteropPackageManager(
                    packageManager.LocalRepository,
                    _dependencyResolver,
                    new CoreInteropSourceRepository(_source)));

            oldResolver.AddOperation(
                MapNewToOldActionType(operation),
                await CreateVirtualPackage(packageIdentity.Id, packageIdentity.Version),
                nullProjectManager);

            // Resolve actions!
            var actions = await Task.Factory.StartNew(() => oldResolver.ResolveActions());

            // Convert the actions
            var converted =
                from action in actions
                select new PackageAction(
                    MapOldToNewActionType(action.ActionType),
                    new PackageIdentity(
                        action.Package.Id,
                        new NuGetVersion(
                            action.Package.Version.Version,
                            action.Package.Version.SpecialVersion)),
                    UnwrapPackage(action.Package),
                    target,
                    _source,
                    packageIdentity);

            // Identify update operations so we can mark them as such.
            foreach (var group in converted.GroupBy(c => c.PackageIdentity.Id))
            {
                var installs = group.Where(p => p.ActionType == PackageActionType.Install).ToList();
                var uninstalls = group.Where(p => p.ActionType == PackageActionType.Uninstall).ToList();
                if (installs.Count > 0 && uninstalls.Count > 0)
                {
                    var maxInstall = installs.OrderByDescending(a => a.PackageIdentity.Version).First();
                    maxInstall.IsUpdate = true;
                }
            }

            return converted;
        }
Beispiel #2
0
        public void UninstallPackage(Project project, string packageId, bool removeDependencies)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (String.IsNullOrEmpty(packageId))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"));
            }

            IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(_packageRepository, useFallbackForDependencies: false);
            IProjectManager projectManager = packageManager.GetProjectManager(project);

            EventHandler<PackageOperationEventArgs> packageReferenceRemovingHandler = (sender, e) =>
            {
                _scriptExecutor.Execute(
                    e.InstallPath,
                    PowerShellScripts.Uninstall,
                    e.Package,
                    project,
                    projectManager.GetTargetFrameworkForPackage(packageId),
                    NullLogger.Instance);
            };

            try
            {
                projectManager.PackageReferenceRemoving += packageReferenceRemovingHandler;                

                // Locate the package to uninstall
                IPackage package = packageManager.LocatePackageToUninstall(
                    projectManager,
                    packageId,
                    version: null);

                // resolve actions
                var resolver = new ActionResolver()
                {
                    RemoveDependencies = removeDependencies
                };
                resolver.AddOperation(PackageAction.Uninstall, package, projectManager);
                var actions = resolver.ResolveActions();

                // execute actions
                var actionExecutor = new ActionExecutor();
                actionExecutor.Execute(actions);
            }
            finally
            {
                projectManager.PackageReferenceRemoving -= packageReferenceRemovingHandler;
            }
        }
Beispiel #3
0
        private void ApplyContext(OldResolver resolver)
        {
            resolver.AllowPrereleaseVersions = _context.AllowPrerelease;
            resolver.ForceRemove             = _context.ForceRemove;
            resolver.RemoveDependencies      = _context.RemoveDependencies;

            if (_context.DependencyBehavior == DependencyBehavior.Ignore)
            {
                resolver.IgnoreDependencies = true;
            }
            else
            {
                resolver.DependencyVersion = MapDependencyBehavior(_context.DependencyBehavior);
            }
        }
Beispiel #4
0
        protected override void ProcessRecordCore()
        {
            if (!SolutionManager.IsSolutionOpen)
            {
                // terminating
                ErrorHandler.ThrowSolutionNotOpenTerminatingError();
            }

            // Locate the package to uninstall
            IPackage package = PackageManager.LocatePackageToUninstall(
                ProjectManager,
                Id,
                Version);

            // resolve actions
            var resolver = new ActionResolver()
            {
                Logger = this,
                ForceRemove = Force.IsPresent,
                RemoveDependencies = RemoveDependencies.IsPresent
            };
            resolver.AddOperation(
                PackageAction.Uninstall,
                package,
                ProjectManager);

            var actions = resolver.ResolveActions();
            if (WhatIf)
            {
                foreach (var operation in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, operation);
                }

                return;
            }

            // execute actions
            var actionExecutor = new ActionExecutor()
            {
                Logger = this
            };
            actionExecutor.Execute(actions);
        }
        private void InstallPackage(string id, MockVsPackageManager2 packageManager)
        {   
            var projectManager = packageManager.GetProjectManager(packageManager.SolutionManager.GetProject("default"));

            // Resolve the package to install
            IPackage package = PackageRepositoryHelper.ResolvePackage(
                packageManager.SourceRepository,
                packageManager.LocalRepository,
                id,
                version: null,
                allowPrereleaseVersions: false);

            // Resolve operations
            var resolver = new ActionResolver();
            resolver.AddOperation(PackageAction.Install, package, projectManager);
            var actions = resolver.ResolveActions();

            var actionExecutor = new ActionExecutor();
            actionExecutor.Execute(actions);
        }
Beispiel #6
0
        public Task RestoreMissingPackages()
        {
            TaskScheduler uiScheduler;
            try
            {
                uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            }
            catch (InvalidOperationException)
            {
                // this exception occurs during unit tests
                uiScheduler = TaskScheduler.Default;
            }

            Task task = Task.Factory.StartNew(() =>
            {
                IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManagerWithAllPackageSources();
                IPackageRepository localRepository = packageManager.LocalRepository;
                var projectReferences = GetAllPackageReferences(packageManager);
                foreach (var reference in projectReferences)
                {
                    if (!localRepository.Exists(reference.Id, reference.Version))
                    {
                        // Resolve the package to install
                        IPackage package = PackageRepositoryHelper.ResolvePackage(
                            packageManager.SourceRepository,
                            packageManager.LocalRepository,
                            reference.Id,
                            reference.Version,
                            allowPrereleaseVersions: true);

                        // Resolve actions
                        var resolver = new ActionResolver()
                        {
                            Logger = packageManager.Logger,
                            DependencyVersion = packageManager.DependencyVersion,
                            IgnoreDependencies = true,
                            AllowPrereleaseVersions = true
                        };
                        resolver.AddOperation(PackageAction.Install, package, new NullProjectManager(packageManager));
                        var actions = resolver.ResolveActions();

                        // Execute actions
                        var actionExecutor = new ActionExecutor()
                        {
                            Logger = packageManager.Logger
                        };
                        actionExecutor.Execute(actions);
                    }
                }
            });

            task.ContinueWith(originalTask =>
            {
                if (originalTask.IsFaulted)
                {
                    ExceptionHelper.WriteToActivityLog(originalTask.Exception);
                }
                else
                {
                    // we don't allow canceling
                    Debug.Assert(!originalTask.IsCanceled);

                    // after we're done with restoring packages, do the check again
                    CheckForMissingPackages();
                }
            }, uiScheduler);

            return task;
        }
Beispiel #7
0
 public UpdateUtility(ActionResolver resolver)
 {
     Resolver = resolver;
     Logger = NullLogger.Instance;
 }
        private bool UninstallSolutionPackage(IPackage package)
        {
            CheckDependentPackages(package, LocalRepository, targetFramework: null);
            bool? result = AskRemoveDependency(
                package,
                new[] { LocalRepository },
                new FrameworkName[] { null });

            if (result == null)
            {
                // user presses Cancel
                return false;
            }

            ShowProgressWindow();
            try
            {
                RegisterPackageOperationEvents(PackageManager, null);
                
                // resolve actions
                var resolver = new ActionResolver()
                {
                    Logger = this,
                    ForceRemove = false,
                    RemoveDependencies = (bool)result
                };
                resolver.AddOperation(
                    PackageAction.Uninstall,
                    package,
                    new NullProjectManager(PackageManager));
                var actions = resolver.ResolveActions();

                // execute actions
                var actionExecutor = new ActionExecutor()
                {
                    Logger = this
                };
                actionExecutor.Execute(actions);
            }
            finally
            {
                UnregisterPackageOperationEvents(PackageManager, null);
            }
            return true;
        }
Beispiel #9
0
        public async Task<IEnumerable<PackageAction>> ResolveActionsAsync(
            PackageIdentity packageIdentity,
            PackageActionType operation,
            IEnumerable<Project> targetedProjects,
            Solution solution)
        {
            // Construct the Action Resolver
            var resolver = new OldResolver();
            if (Logger != null)
            {
                resolver.Logger = new ShimLogger(Logger);
            }

            // Apply context settings
            ApplyContext(resolver);

            // Add the operation request(s)
            NuGetTraceSources.ActionResolver.Verbose("resolving", "Resolving {0} of {1} {2}", operation.ToString(), packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            foreach (var project in targetedProjects)
            {
                resolver.AddOperation(
                    MapNewToOldActionType(operation),
                    await CreateVirtualPackage(packageIdentity.Id, packageIdentity.Version),
                    new CoreInteropProjectManager(project, _source, _dependencyResolver));
            }

            // Resolve actions!
            var actions = await Task.Factory.StartNew(() => resolver.ResolveActions());

            // Convert the actions
            var converted =
                from action in actions
                let projectAction = action as PackageProjectAction
                select new PackageAction(
                    MapOldToNewActionType(action.ActionType),
                    new PackageIdentity(
                        action.Package.Id,
                        new NuGetVersion(
                            action.Package.Version.Version,
                            action.Package.Version.SpecialVersion)),
                    UnwrapPackage(action.Package),
                    (projectAction != null ?
                        FindProject(targetedProjects, projectAction.ProjectManager.Project.ProjectName) :
                        (InstallationTarget)solution),
                    _source,
                    packageIdentity);

            // Identify update operations so we can mark them as such.
            foreach (var group in converted.GroupBy(c => c.PackageIdentity.Id))
            {
                var installs = group.Where(p => p.ActionType == PackageActionType.Install).ToList();
                var uninstalls = group.Where(p => p.ActionType == PackageActionType.Uninstall).ToList();
                if (installs.Count > 0 && uninstalls.Count > 0)
                {
                    var maxInstall = installs.OrderByDescending(a => a.PackageIdentity.Version).First();
                    maxInstall.IsUpdate = true;
                }
            }

            return converted;
        }
Beispiel #10
0
 // Resolve actions to update all packages in all projects.
 private IEnumerable<Resolver.PackageAction> ResolveActionsForUpdateAll(IVsPackageManager activePackageManager)
 {
     var resolver = new ActionResolver()
     {
         Logger = this,
         AllowPrereleaseVersions = IncludePrerelease,
         DependencyVersion = activePackageManager.DependencyVersion
     };
     var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease);
     foreach (Project project in _solutionManager.GetProjects())
     {
         IProjectManager projectManager = activePackageManager.GetProjectManager(project);
         foreach (var package in allPackages)
         {
             // Update if an older version package is installed in the project
             var localPackge = projectManager.LocalRepository.FindPackage(package.Id);
             if (localPackge != null && localPackge.Version < package.Version)
             {
                 resolver.AddOperation(PackageAction.Install, package, projectManager);
             }
         }
     }
     var actions = resolver.ResolveActions();
     return actions;
 }
Beispiel #11
0
        private void ReinstallPackage(
            string id, IProjectManager projectManager, 
            ReinstallInfo reinstallInfo,
            ActionResolver resolver)
        {
            // find the package version installed in this project
            IPackage existingPackage = projectManager.LocalRepository.FindPackage(id);
            if (existingPackage == null)
            {
                return;
            }

            bool packageExistInSource;
            if (!reinstallInfo.VersionsChecked.TryGetValue(existingPackage.Version, out packageExistInSource))
            {
                // version has not been checked, so check it here
                packageExistInSource = PackageManager.SourceRepository.Exists(id, existingPackage.Version);

                // mark the version as checked so that we don't have to check again if we
                // encounter another project with the same version.
                reinstallInfo.VersionsChecked[existingPackage.Version] = packageExistInSource;
            }

            if (packageExistInSource)
            {
                resolver.AddOperation(PackageAction.Uninstall, existingPackage, projectManager);

                var packageFromSource = PackageManager.SourceRepository.FindPackage(id, existingPackage.Version);
                resolver.AddOperation(PackageAction.Install, packageFromSource, projectManager);
            }
            else
            {
                Log(
                    MessageLevel.Warning,
                    VsResources.PackageRestoreSkipForProject,
                    existingPackage.GetFullName(),
                    projectManager.Project.ProjectName);
            }
        }
Beispiel #12
0
        private void ReinstallOnePackage(string id, IEnumerable<IProjectManager> projectManagers)
        {
            List<Resolver.PackageAction> actions = new List<Resolver.PackageAction>();
            var projectNameSpecified = !String.IsNullOrEmpty(ProjectName);
            var oldPackage = projectNameSpecified ?
                UpdateUtility.FindPackageToUpdate(
                    id, version: null, 
                    packageManager: PackageManager,
                    projectManager: projectManagers.First()) :
                UpdateUtility.FindPackageToUpdate(
                    id, version: null, 
                    packageManager: PackageManager,
                    projectManagers: projectManagers, 
                    logger: this);

            if (oldPackage.Item2 == null)
            {
                // we're reinstalling a solution level package
                Log(MessageLevel.Info, VsResources.ReinstallSolutionPackage, oldPackage.Item1);
                if (PackageManager.SourceRepository.Exists(oldPackage.Item1))
                {
                    var resolver = new ActionResolver()
                    {
                        ForceRemove = true
                    };
                    resolver.AddOperation(PackageAction.Uninstall, oldPackage.Item1, new NullProjectManager(PackageManager));

                    var packageFromSource = PackageManager.SourceRepository.FindPackage(
                        oldPackage.Item1.Id,
                        oldPackage.Item1.Version);
                    resolver.AddOperation(PackageAction.Install, packageFromSource, new NullProjectManager(PackageManager));
                    actions.AddRange(resolver.ResolveActions());
                }
                else
                {
                    Log(
                        MessageLevel.Warning,
                        VsResources.PackageRestoreSkipForSolution,
                        oldPackage.Item1.GetFullName());
                }
            }
            else
            {
                var reinstallInfo = new ReinstallInfo(Enumerable.Empty<VirtualProjectManager>());
                var resolver = new ActionResolver()
                {
                    ForceRemove = true
                };
                foreach (var projectManager in projectManagers)
                {
                    ReinstallPackage(id, projectManager, reinstallInfo, resolver);
                }

                actions.AddRange(resolver.ResolveActions());
            }

            if (WhatIf)
            {
                foreach (var action in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, action);
                }

                return;
            }

            var executor = new ActionExecutor()
            {
                Logger = this,
                PackageOperationEventListener = this,
                CatchProjectOperationException = true
            };
            executor.Execute(actions);
        }
Beispiel #13
0
        private void ReinstallAllPackagesInProject(IProjectManager projectManager, ActionResolver resolver)
        {
            var packages = projectManager.LocalRepository.GetPackages().ToList();

            // Uninstall all packages
            var packagesToInstall = new List<IPackage>();
            foreach (var package in packages)
            {
                var packageFromSource = projectManager.PackageManager.SourceRepository.FindPackage(
                    package.Id,
                    package.Version);

                if (packageFromSource != null)
                {
                    resolver.AddOperation(PackageAction.Uninstall, package, projectManager);
                    packagesToInstall.Add(packageFromSource);
                }
                else
                {
                    Log(
                        MessageLevel.Warning,
                        VsResources.PackageRestoreSkipForProject,
                        package.GetFullName(),
                        projectManager.Project.ProjectName);
                }
            }

            foreach (var package in packagesToInstall)
            {
                resolver.AddOperation(PackageAction.Install, package, projectManager);
            }
        }
Beispiel #14
0
        private void ReinstallAllPackages(IEnumerable<IProjectManager> projectManagers)
        {
            var packages = PackageManager.LocalRepository.GetPackages().ToList();
            var solutionLevelPackages = packages.Where(p => !PackageManager.IsProjectLevel(p));

            var resolver = new ActionResolver()
            {
                ForceRemove = true
            };

            // reinstall solution level packages
            foreach (var package in solutionLevelPackages)
            {
                resolver.AddOperation(PackageAction.Uninstall, package, new NullProjectManager(PackageManager));                
                var packageFromSource = PackageManager.SourceRepository.FindPackage(
                    package.Id,
                    package.Version);
                resolver.AddOperation(PackageAction.Install, packageFromSource, new NullProjectManager(PackageManager));
            }

            // Reinstall packages in projects
            foreach (var projectManager in projectManagers)
            {
                ReinstallAllPackagesInProject(projectManager, resolver);
            }

            var actions = resolver.ResolveActions();
            if (WhatIf)
            {
                foreach (var action in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, action);
                }

                return;
            }

            var executor = new ActionExecutor()
            {
                Logger = this,
                PackageOperationEventListener = this,
                CatchProjectOperationException = true
            };
            executor.Execute(actions);
        }
Beispiel #15
0
        protected override void ProcessRecordCore()
        {
            if (!SolutionManager.IsSolutionOpen)
            {
                // terminating
                ErrorHandler.ThrowSolutionNotOpenTerminatingError();
            }

            try
            {
                SubscribeToProgressEvents();
                if (PackageManager != null)
                {
                    _resolver = new ActionResolver()
                    {
                        Logger = this,
                        DependencyVersion = PackageManager.DependencyVersion,
                        IgnoreDependencies = IgnoreDependencies,
                        AllowPrereleaseVersions = IncludePrerelease.IsPresent,
                        ForceRemove = true
                    };

                    _actionExecutor = new ActionExecutor()
                    {
                        Logger = this,
                        PackageOperationEventListener = this,
                        CatchProjectOperationException = true
                    };
            
                    if (Reinstall)
                    {
                        PerformReinstalls();
                    }
                    else
                    {
                        PerformUpdates(ProjectManager);
                    }
                    _hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source, _packageSourceProvider);
                }
            }
            finally
            {
                UnsubscribeFromProgressEvents();
            }
        }
Beispiel #16
0
        protected void UninstallPackageFromProject(Project project, PackageItem item, bool removeDependencies)
        {
            IProjectManager projectManager = null;
            try
            {
                projectManager = PackageManager.GetProjectManager(project);
                // make sure the package is installed in this project before proceeding
                if (projectManager.LocalRepository.Exists(item.PackageIdentity))
                {
                    RegisterPackageOperationEvents(PackageManager, projectManager);
                    
                    // Locate the package to uninstall
                    IPackage package = PackageManager.LocatePackageToUninstall(
                        projectManager,
                        item.Id,
                        version: null);

                    // resolve operations
                    var resolver = new ActionResolver()
                    {
                        Logger = this,
                        ForceRemove = false,
                        RemoveDependencies = removeDependencies
                    };
                    resolver.AddOperation(PackageAction.Uninstall, package, projectManager);
                    var actions = resolver.ResolveActions();

                    // execute operations
                    var actionExecutor = new ActionExecutor()
                    {
                        Logger = this
                    };
                    actionExecutor.Execute(actions);
                }
            }
            finally
            {
                if (projectManager != null)
                {
                    UnregisterPackageOperationEvents(PackageManager, projectManager);
                }
            }
        }
Beispiel #17
0
 private IEnumerable<Resolver.PackageAction> ResolveActionsForUpdateAll(IVsPackageManager activePackageManager, IProjectManager projectManager)
 {
     var resolver = new ActionResolver()
     {
         Logger = this,
         AllowPrereleaseVersions = IncludePrerelease,
         DependencyVersion = activePackageManager.DependencyVersion
     };
     var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease);
     foreach (var package in allPackages)
     {
         resolver.AddOperation(PackageAction.Install, package, projectManager);
     }
     var actions = resolver.ResolveActions();
     return actions;
 }
Beispiel #18
0
        protected override bool ExecuteCore(PackageItem item)
        {
            IVsPackageManager activePackageManager = GetActivePackageManager();
            Debug.Assert(activePackageManager != null);

            using (activePackageManager.SourceRepository.StartOperation(OperationName, item.Id, item.Version))
            {
                ShowProgressWindow();

                // Resolve operations
                var resolver = new ActionResolver()
                {
                    Logger = this,
                    DependencyVersion = activePackageManager.DependencyVersion,
                    IgnoreDependencies = false,
                    AllowPrereleaseVersions = IncludePrerelease
                };
                var projectManager = activePackageManager.GetProjectManager(_project);
                projectManager.Logger = this;
                resolver.AddOperation(PackageAction.Install, item.PackageIdentity, projectManager);
                var actions = resolver.ResolveActions();

                // show license agreeement
                bool acceptLicense = ShowLicenseAgreement(actions);
                if (!acceptLicense)
                {
                    return false;
                }

                // execute operations
                try
                {
                    RegisterPackageOperationEvents(activePackageManager, projectManager);

                    var actionExecutor = new ActionExecutor()
                    {
                        Logger = this
                    };
                    actionExecutor.Execute(actions);
                }
                finally
                {
                    UnregisterPackageOperationEvents(activePackageManager, projectManager);
                }

                return true;
            }
        }
Beispiel #19
0
        private void ApplyContext(OldResolver resolver)
        {
            resolver.AllowPrereleaseVersions = _context.AllowPrerelease;
            resolver.ForceRemove = _context.ForceRemove;
            resolver.RemoveDependencies = _context.RemoveDependencies;

            if (_context.DependencyBehavior == DependencyBehavior.Ignore)
            {
                resolver.IgnoreDependencies = true;
            }
            else
            {
                resolver.DependencyVersion = MapDependencyBehavior(_context.DependencyBehavior);
            }
        }
Beispiel #20
0
        private void InstallPackage(IVsPackageManager packageManager)
        {
            if (packageManager == null)
            {
                return;
            }
            
            // Locate the package to install
            IPackage package = PackageRepositoryHelper.ResolvePackage(
                packageManager.SourceRepository,
                packageManager.LocalRepository,
                Id,
                Version,
                IncludePrerelease.IsPresent);

            // Resolve actions
            var resolver = new ActionResolver()
            {
                Logger = this,
                IgnoreDependencies = IgnoreDependencies,
                DependencyVersion = packageManager.DependencyVersion,
                AllowPrereleaseVersions = IncludePrerelease.IsPresent
            };
            resolver.AddOperation(PackageAction.Install, package, ProjectManager);
            var actions = resolver.ResolveActions();

            if (WhatIf)
            {
                foreach (var action in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, action);
                }

                return;
            }

            var executor = new ActionExecutor()
            {
                Logger = this
            };
            executor.Execute(actions);
        }
        protected override void ProcessRecordCore()
        {
            if (!SolutionManager.IsSolutionOpen)
            {
                // terminating
                ErrorHandler.ThrowSolutionNotOpenTerminatingError();
            }

            // Locate the package to uninstall
            IPackage package = PackageManager.LocatePackageToUninstall(
                ProjectManager,
                Id,
                Version);

#if VS14
            var nugetAwareProject = ProjectManager == null ?
                null :
                ProjectManager.Project as INuGetPackageManager;
            if (nugetAwareProject != null)
            {
                var args = new Dictionary<string, object>();
                args["WhatIf"] = WhatIf;
                args["SourceRepository"] = PackageManager.SourceRepository;
                args["SharedRepository"] = PackageManager.LocalRepository;

                using (var cts = new CancellationTokenSource())
                {
                    var task = nugetAwareProject.UninstallPackageAsync(
                        new NuGetPackageMoniker
                        {
                            Id = package.Id,
                            Version = package.Version.ToString()
                        },
                        args,
                        logger: null,
                        progress: null,
                        cancellationToken: cts.Token);
                    task.Wait();
                    return;
                }
            }
#endif

            // resolve actions
            var resolver = new ActionResolver()
            {
                Logger = this,
                ForceRemove = Force.IsPresent,
                RemoveDependencies = RemoveDependencies.IsPresent
            };
            resolver.AddOperation(
                PackageAction.Uninstall,
                package,
                ProjectManager);

            var actions = resolver.ResolveActions();
            if (WhatIf)
            {
                foreach (var operation in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, operation);
                }

                return;
            }

            // execute actions
            var actionExecutor = new ActionExecutor()
            {
                Logger = this
            };
            actionExecutor.Execute(actions);
        }
Beispiel #22
0
        static void Install(
           string id,
           IProjectManager projectManager)
        {
            var resolver = new ActionResolver();

            // Resolve the package to install
            IPackage package = PackageRepositoryHelper.ResolvePackage(
                projectManager.PackageManager.SourceRepository,
                projectManager.PackageManager.LocalRepository,
                id,
                null,
                resolver.AllowPrereleaseVersions);

            // Resolve actions
            resolver.AddOperation(PackageAction.Install, package, projectManager);
            var actions = resolver.ResolveActions();

            var actionExecutor = new ActionExecutor();
            actionExecutor.Execute(actions);
        }
Beispiel #23
0
        internal void UpdatePackages(IPackageRepository localRepository,
                                     IFileSystem sharedRepositoryFileSystem,
                                     ISharedPackageRepository sharedPackageRepository,
                                     IPackageRepository sourceRepository,
                                     IPackageConstraintProvider constraintProvider,
                                     IPackagePathResolver pathResolver,
                                     IProjectSystem project)
        {
            var packageManager = new PackageManager(sourceRepository, pathResolver, sharedRepositoryFileSystem, sharedPackageRepository);

            var projectManager = new ProjectManager(packageManager, pathResolver, project, localRepository)
                                 {
                                     ConstraintProvider = constraintProvider
                                 };

            // Fix for work item 2411: When updating packages, we did not add packages to the shared package repository. 
            // Consequently, when querying the package reference repository, we would have package references with no backing package files in
            // the shared repository. This would cause the reference repository to skip the package assuming that the entry is invalid.
            projectManager.PackageReferenceAdded += (sender, eventArgs) =>
            {
                PackageExtractor.InstallPackage(packageManager, eventArgs.Package);
            };

            projectManager.Logger = project.Logger = this;

            foreach (var package in GetPackages(localRepository))
            {
                if (localRepository.Exists(package.Id))
                {
                    using (sourceRepository.StartOperation(RepositoryOperationNames.Update, package.Id, mainPackageVersion: null))
                    {
                        try
                        {
                            // If the user explicitly allows prerelease or if the package being updated is prerelease we'll include prerelease versions in our list of packages
                            // being considered for an update.
                            bool allowPrerelease = Prerelease || !package.IsReleaseVersion();
                            var resolver = new ActionResolver()
                            {
                                AllowPrereleaseVersions = allowPrerelease
                            };
                            var updateUtility = new UpdateUtility(resolver)
                            {
                                AllowPrereleaseVersions = allowPrerelease,
                                Safe = Safe
                            };

                            var operations = updateUtility.ResolveActionsForUpdate(package.Id, null, new[] { projectManager }, false);
                            var userOperationExecutor = new ActionExecutor();
                            userOperationExecutor.Execute(operations);
                        }
                        catch (InvalidOperationException e)
                        {
                            if (Console.Verbosity == NuGet.Verbosity.Detailed)
                            {
                                Console.WriteWarning(e.ToString());
                            }
                            else
                            {
                                Console.WriteWarning(e.Message);
                            }
                        }
                    }
                }
            }
        }
Beispiel #24
0
        private void Uninstall(string id, IPackageManager packageManager, IProjectManager projectManager)
        {
            // Locate the package to uninstall
            IPackage package = packageManager.LocatePackageToUninstall(
                projectManager,
                id,
                version: null);

            // resolve actions
            var resolver = new ActionResolver();
            resolver.AddOperation(PackageAction.Uninstall, package, projectManager);
            var actions = resolver.ResolveActions();

            // execute actions
            var actionExecutor = new ActionExecutor();
            actionExecutor.Execute(actions);
        }
Beispiel #25
0
        public async Task <IEnumerable <PackageAction> > ResolveActionsAsync(
            PackageIdentity packageIdentity,
            PackageActionType operation,
            IEnumerable <Project> targetedProjects,
            Solution solution)
        {
            // Construct the Action Resolver
            var resolver = new OldResolver();

            if (Logger != null)
            {
                resolver.Logger = new ShimLogger(Logger);
            }

            // Apply context settings
            ApplyContext(resolver);

            // Add the operation request(s)
            NuGetTraceSources.ActionResolver.Verbose("resolving", "Resolving {0} of {1} {2}", operation.ToString(), packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
            foreach (var project in targetedProjects)
            {
                resolver.AddOperation(
                    MapNewToOldActionType(operation),
                    await CreateVirtualPackage(packageIdentity.Id, packageIdentity.Version),
                    new CoreInteropProjectManager(project, _source, _dependencyResolver));
            }

            // Resolve actions!
            var actions = await Task.Factory.StartNew(() => resolver.ResolveActions());

            // Convert the actions
            var converted =
                from action in actions
                let projectAction = action as PackageProjectAction
                                    select new PackageAction(
                    MapOldToNewActionType(action.ActionType),
                    new PackageIdentity(
                        action.Package.Id,
                        new NuGetVersion(
                            action.Package.Version.Version,
                            action.Package.Version.SpecialVersion)),
                    UnwrapPackage(action.Package),
                    (projectAction != null ?
                     FindProject(targetedProjects, projectAction.ProjectManager.Project.ProjectName) :
                     (InstallationTarget)solution),
                    _source,
                    packageIdentity);

            // Identify update operations so we can mark them as such.
            foreach (var group in converted.GroupBy(c => c.PackageIdentity.Id))
            {
                var installs   = group.Where(p => p.ActionType == PackageActionType.Install).ToList();
                var uninstalls = group.Where(p => p.ActionType == PackageActionType.Uninstall).ToList();
                if (installs.Count > 0 && uninstalls.Count > 0)
                {
                    var maxInstall = installs.OrderByDescending(a => a.PackageIdentity.Version).First();
                    maxInstall.IsUpdate = true;
                }
            }

            return(converted);
        }
Beispiel #26
0
        private void InstallPackage(
            IFileSystem fileSystem,
            string packageId,
            SemanticVersion version)
        {
            if (version == null)
            {
                NoCache = true;
            }
            var packageManager = CreatePackageManager(fileSystem, AllowMultipleVersions);

            if (!PackageInstallNeeded(packageManager, packageId, version))
            {
                Console.WriteLine(LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"), packageId);
                return;
            }

            if (version == null)
            {
                var latestVersion = GetLastestPackageVersion(
                    packageManager.SourceRepository, 
                    packageId, 
                    allowPrereleaseVersions: Prerelease);
                if (latestVersion != null)
                {
                    version = latestVersion.Version;
                }
            }

            using (packageManager.SourceRepository.StartOperation(
                RepositoryOperationNames.Install, 
                packageId, 
                version == null ? null : version.ToString()))
            {
                var resolver = new ActionResolver()
                {
                    Logger = Console,
                    AllowPrereleaseVersions = Prerelease
                };

                // Resolve the package to install
                IPackage package = PackageRepositoryHelper.ResolvePackage(
                    packageManager.SourceRepository,
                    packageManager.LocalRepository,
                    packageId,
                    version,
                    Prerelease);

                // Resolve operations. Note that we only care about AddToPackagesFolder actions
                resolver.AddOperation(
                    PackageAction.Install, 
                    package, 
                    new NullProjectManager(packageManager));                
                var actions = resolver.ResolveActions()
                    .Where(action => action.ActionType == PackageActionType.AddToPackagesFolder);

                if (actions.Any())
                {
                    var executor = new ActionExecutor()
                    {
                        Logger = Console
                    };
                    executor.Execute(actions);
                }
                else if (packageManager.LocalRepository.Exists(package))
                {
                    // If the package wasn't installed by our set of operations, notify the user.
                    Console.Log(
                        MessageLevel.Info, 
                        NuGet.Resources.NuGetResources.Log_PackageAlreadyInstalled, 
                        package.GetFullName());
                }
            }
        }
Beispiel #27
0
        public async Task <IEnumerable <PackageAction> > ResolveActionsAsync(
            PackageIdentity packageIdentity,
            PackageActionType operation,
            InstallationTarget target)
        {
            // Construct the Action Resolver
            var oldResolver = new OldResolver();

            if (Logger != null)
            {
                oldResolver.Logger = new ShimLogger(Logger);
            }

            // Apply context settings
            ApplyContext(oldResolver);

            var packageManager = target.GetRequiredFeature <IPackageManager>();

            var nullProjectManager = new NullProjectManager(
                new CoreInteropPackageManager(
                    packageManager.LocalRepository,
                    _dependencyResolver,
                    new CoreInteropSourceRepository(_source)));

            oldResolver.AddOperation(
                MapNewToOldActionType(operation),
                await CreateVirtualPackage(packageIdentity.Id, packageIdentity.Version),
                nullProjectManager);

            // Resolve actions!
            var actions = await Task.Factory.StartNew(() => oldResolver.ResolveActions());

            // Convert the actions
            var converted =
                from action in actions
                select new PackageAction(
                    MapOldToNewActionType(action.ActionType),
                    new PackageIdentity(
                        action.Package.Id,
                        new NuGetVersion(
                            action.Package.Version.Version,
                            action.Package.Version.SpecialVersion)),
                    UnwrapPackage(action.Package),
                    target,
                    _source,
                    packageIdentity);

            // Identify update operations so we can mark them as such.
            foreach (var group in converted.GroupBy(c => c.PackageIdentity.Id))
            {
                var installs   = group.Where(p => p.ActionType == PackageActionType.Install).ToList();
                var uninstalls = group.Where(p => p.ActionType == PackageActionType.Uninstall).ToList();
                if (installs.Count > 0 && uninstalls.Count > 0)
                {
                    var maxInstall = installs.OrderByDescending(a => a.PackageIdentity.Version).First();
                    maxInstall.IsUpdate = true;
                }
            }

            return(converted);
        }
Beispiel #28
0
        /// <summary>
        /// Returns true if package install is needed.
        /// Package install is not needed if 
        /// - AllowMultipleVersions is false;
        /// - there is an existing package, and its version is newer than or equal to the 
        /// package to be installed.
        /// </summary>
        /// <param name="packageManager">The pacakge manager.</param>
        /// <param name="packageId">The id of the package to install.</param>
        /// <param name="version">The version of the package to install.</param>
        /// <returns>True if package install is neede; otherwise, false.</returns>
        private bool PackageInstallNeeded(
            IPackageManager packageManager,
            string packageId,
            SemanticVersion version)
        {
            if (AllowMultipleVersions)
            {
                return true;
            }

            var installedPackage = packageManager.LocalRepository.FindPackage(packageId);
            if (installedPackage == null)
            {
                return true;
            }

            if (version == null)
            {
                // need to query the source repository to get the version to be installed.
                IPackage package = packageManager.SourceRepository.FindPackage(
                    packageId, 
                    version,
                    NullConstraintProvider.Instance,
                    allowPrereleaseVersions: Prerelease, 
                    allowUnlisted: false);
                if (package == null)
                {
                    return false;
                }

                version = package.Version;
            }

            if (installedPackage.Version >= version)
            {
                // If the installed pacakge has newer version, no install is needed.
                return false;
            }

            // install is needed. In this case, uninstall the existing pacakge.
            var resolver = new ActionResolver()
            {
                Logger = packageManager.Logger,
                RemoveDependencies = true,
                ForceRemove = false
            };

            var projectManager = new NullProjectManager(packageManager);
            foreach (var package in packageManager.LocalRepository.GetPackages())
            {
                projectManager.LocalRepository.AddPackage(package);
            }
            resolver.AddOperation(
                PackageAction.Uninstall,
                installedPackage, 
                projectManager);
            var projectActions = resolver.ResolveActions();
            
            // because the projectManager's LocalRepository is not a PackageReferenceRepository,
            // the packages in the packages folder are not referenced. Thus, the resolved actions
            // are all PackageProjectActions. We need to create packages folder actions
            // from those PackageProjectActions.
            var solutionActions = new List<Resolver.PackageSolutionAction>();
            foreach (var action in projectActions)
            {
                var projectAction = action as PackageProjectAction;
                if (projectAction == null)
                {
                    continue;
                }

                var solutioAction = projectAction.ActionType == PackageActionType.Install ?
                    PackageActionType.AddToPackagesFolder :
                    PackageActionType.DeleteFromPackagesFolder;
                solutionActions.Add(new PackageSolutionAction(
                    solutioAction,                    
                    projectAction.Package,
                    packageManager));
            }

            var userOperationExecutor = new ActionExecutor()
            {
                Logger = packageManager.Logger
            };
            userOperationExecutor.Execute(solutionActions);
            return true;
        }
Beispiel #29
0
        internal void InstallPackage(IPackageRepository repository, Project project, string packageId, SemanticVersion version, bool ignoreDependencies, bool skipAssemblyReferences)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

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

            using (_vsCommonOperations.SaveSolutionExplorerNodeStates(_solutionManager))
            {
                IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(repository,
                                                                                               useFallbackForDependencies: false);
                IProjectManager projectManager = packageManager.GetProjectManager(project);

                EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) =>
                                                                               {
                                                                                   _scriptExecutor.ExecuteInitScript(
                                                                                       e.InstallPath, e.Package,
                                                                                       NullLogger.Instance);
                                                                               };

                EventHandler<PackageOperationEventArgs> addedHandler = (sender, e) =>
                                                                           {
                                                                               _scriptExecutor.ExecuteScript(
                                                                                   e.InstallPath,
                                                                                   PowerShellScripts.Install,
                                                                                   e.Package,
                                                                                   project,
                                                                                   project.GetTargetFrameworkName(),
                                                                                   NullLogger.Instance);
                                                                           };

                bool oldBindingRedirectValue = packageManager.BindingRedirectEnabled;
                try
                {
                    projectManager.PackageReferenceAdded += addedHandler;
                    packageManager.PackageInstalled += installedHandler;
                    // if skipping assembly references, disable binding redirects too.
                    packageManager.BindingRedirectEnabled = !skipAssemblyReferences;

                    // locate the package to install
                    IPackage package = PackageRepositoryHelper.ResolvePackage(
                        packageManager.SourceRepository,
                        packageManager.LocalRepository,
                        packageId,
                        version,
                        allowPrereleaseVersions: true);

                    if (skipAssemblyReferences)
                    {
                        package = new SkipAssemblyReferencesPackage(package);
                    }

                    // resolve actions
                    var resolver = new ActionResolver()
                    {
                        Logger = NullLogger.Instance,
                        DependencyVersion = packageManager.DependencyVersion,
                        IgnoreDependencies = ignoreDependencies,
                        AllowPrereleaseVersions = true
                    };
                    resolver.AddOperation(PackageAction.Install, package, projectManager);
                    var actions = resolver.ResolveActions();

                    // execute actions
                    var actionExecutor = new ActionExecutor();
                    actionExecutor.Execute(actions);
                }
                finally
                {
                    packageManager.BindingRedirectEnabled = oldBindingRedirectValue;
                    projectManager.PackageReferenceAdded -= addedHandler;
                    packageManager.PackageInstalled -= installedHandler;
                }
            }
        }
        private void InstallPackage(IVsPackageManager packageManager)
        {
            if (packageManager == null)
            {
                return;
            }

            // Locate the package to install
            IPackage package = PackageRepositoryHelper.ResolvePackage(
                packageManager.SourceRepository,
                packageManager.LocalRepository,
                Id,
                Version,
                IncludePrerelease.IsPresent);

#if VS14
            var nugetAwareProject = ProjectManager.Project as INuGetPackageManager;
            if (nugetAwareProject != null)
            {
                var args = new Dictionary<string, object>();
                args["DependencyVersion"] = DependencyVersion;
                args["IgnoreDependencies"] = IgnoreDependencies;
                args["WhatIf"] = WhatIf;

                using (var cts = new CancellationTokenSource())
                {
                    var packageSupportedFrameworks = package.GetSupportedFrameworks();
                    var projectFrameworks = nugetAwareProject.GetSupportedFrameworksAsync(cts.Token).Result;
                    args["Frameworks"] = projectFrameworks.Where(
                        projectFramework =>
                            NuGet.VersionUtility.IsCompatible(
                                projectFramework,
                                packageSupportedFrameworks)).ToArray();
                    var task = nugetAwareProject.InstallPackageAsync(
                        new NuGetPackageMoniker
                        {
                            Id = package.Id,
                            Version = package.Version.ToString()
                        },
                        args,
                        logger: null,
                        progress: null,
                        cancellationToken: cts.Token);
                    task.Wait();
                    return;
                }
            }
#endif
            // Resolve actions
            var resolver = new ActionResolver()
            {
                Logger = this,
                IgnoreDependencies = IgnoreDependencies,
                DependencyVersion = packageManager.DependencyVersion,
                AllowPrereleaseVersions = IncludePrerelease.IsPresent
            };
            resolver.AddOperation(PackageAction.Install, package, ProjectManager);
            var actions = resolver.ResolveActions();

            if (WhatIf)
            {
                foreach (var action in actions)
                {
                    Log(MessageLevel.Info, Resources.Log_OperationWhatIf, action);
                }

                return;
            }

            var executor = new ActionExecutor()
            {
                Logger = this
            };
            executor.Execute(actions);
        }