Exemple #1
0
        public void PreferAsyncMethod_Ok(string actionName)
        {
            ActionResolver resolver = new ActionResolver();

            Assert.NotNull(resolver.Resolve(typeof(IContract2), actionName));
            Assert.Equal(nameof(IContract2.MethodAsync), resolver.Resolve(typeof (IContract2), actionName).Name);
        }
        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);
            }
        }
Exemple #3
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);
        }
        public void PreferAsyncMethod_Ok(string actionName)
        {
            ActionResolver resolver = new ActionResolver();

            Assert.NotNull(resolver.Resolve(typeof(IContract2), actionName));
            Assert.Equal(nameof(IContract2.MethodAsync), resolver.Resolve(typeof(IContract2), actionName).Name);
        }
        public void Resolve_Ok(string actionName)
        {
            var contract = BoltFramework.GetContract(typeof(IContract1));

            ActionResolver resolver = new ActionResolver();

            Assert.NotNull(resolver.Resolve(typeof(IContract1), actionName));
        }
Exemple #6
0
        public async Task <IEnumerable <PackageAction> > ResolveActionsAsync(IExecutionLogger logger)
        {
            var model  = (DetailControlModel)DataContext;
            var action = model.SelectedAction == Resx.Resources.Action_Uninstall ?
                         PackageActionType.Uninstall :
                         PackageActionType.Install;

            // Create resolver
            var repo = Control.CreateActiveRepository();

            if (action == PackageActionType.Uninstall)
            {
                // for uninstall, use local repo
                repo = Control.Target.TryGetFeature <SourceRepository>();
            }
            if (repo == null)
            {
                throw new InvalidOperationException(Resx.Resources.Error_NoActiveRepository);
            }

            var dependencyResolutionRepo = Control.CreateAggregateSourceRepository();
            var resolver = new ActionResolver(
                repo,
                dependencyResolutionRepo,
                new ResolutionContext()
            {
                DependencyBehavior = model.Options.SelectedDependencyBehavior.Behavior,
                AllowPrerelease    = Control.IncludePrerelease,
                ForceRemove        = model.Options.ForceRemove,
                RemoveDependencies = model.Options.RemoveDependencies
            });

            resolver.Logger = logger;

            IEnumerable <Project> targetProjects;
            var solutionModel = DataContext as PackageSolutionDetailControlModel;

            if (solutionModel != null)
            {
                targetProjects = solutionModel.Projects
                                 .Where(p => p.Selected)
                                 .Select(p => p.Project);
            }
            else
            {
                var project = Control.Target as Project;
                targetProjects = new[] { project };
                Debug.Assert(project != null);
            }

            return(await resolver.ResolveActionsAsync(
                       new PackageIdentity(model.Id, model.SelectedVersion.Version),
                       action,
                       targetProjects,
                       Control.Target.OwnerSolution));
        }
Exemple #7
0
    public void Init()
    {
        GameActionResolver = GameObject.FindGameObjectWithTag("actionResolver").GetComponent<ActionResolver>();

        //Initialize the state dictionary in memory
        StateDictionary = new Dictionary<Enums.GameStates, State_Base>();

        StateDictionary.Add(Enums.GameStates.gamestate_waitingForCommand, new State_WaitingForCommand());
        StateDictionary.Add(Enums.GameStates.gamestate_SelectActionMenu, new State_ActionSelectMenu());

        CurrentState = StateDictionary[Enums.GameStates.gamestate_waitingForCommand];
    }
Exemple #8
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;
            }
        }
Exemple #9
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);
            }
        }
        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);
        }
Exemple #11
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);
        }
Exemple #12
0
        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);
        }
        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();
            }
        }
Exemple #14
0
        /*
         * protected override void ExecuteCommand(IProjectManager projectManager, PackageItem item, IVsPackageManager activePackageManager, IList<PackageOperation> operations)
         * {
         *  activePackageManager.UpdatePackages(
         *      projectManager,
         *      new[] { item.PackageIdentity },
         *      operations,
         *      updateDependencies: true,
         *      allowPrereleaseVersions: IncludePrerelease,
         *      logger: this);
         * } */

        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);
        }
Exemple #15
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);
                }
            }
        }
        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);
        }
Exemple #17
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);
        }
        internal void InstallPackages(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;

            bool allowPrerelease = Prerelease;
            var  resolver        = new ActionResolver()
            {
                AllowPrereleaseVersions = allowPrerelease
            };
            var installPackageUtility = new InstallPackageUtility(resolver)
            {
                AllowPrereleaseVersions = allowPrerelease,
                Safe = Safe
            };

            var operations            = installPackageUtility.ResolveActionsForInstallPackage(Id.FirstOrDefault(), Version, new[] { projectManager }, false);
            var userOperationExecutor = new ActionExecutor();

            userOperationExecutor.Execute(operations);
        }
        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);
            }
        }
Exemple #20
0
        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(NuGet.PackageAction.Install, package, projectManager);
            var actions = resolver.ResolveActions();

            var executor = new ActionExecutor();

            executor.Execute(actions);
        }
Exemple #21
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);
        }
        private async Task InstallPackage(
            IFileSystem installPathFileSystem,
            string packageId,
            NuGetVersion version)
        {
            if (version == null)
            {
                NoCache = true;
            }
            var packageManager = CreatePackageManager(installPathFileSystem, useSideBySidePaths: true);

            // BUGBUG: When adding support for 'AllowMultipleVersions', remember to add PackageInstallNeeded method

            JObject packageMetadata;

            if (version == null)
            {
                packageMetadata = await SourceRepositoryHelper.GetLatestVersionMetadata(SourceRepository, packageId, prerelease : Prerelease);

                version = NuGetVersion.Parse(packageMetadata["version"].ToString());
            }
            else
            {
                packageMetadata = await SourceRepository.GetPackageMetadata(packageId, version);
            }

            if (packageMetadata == null)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture,
                                        NuGet.Resources.NuGetResources.UnknownPackageSpecificVersion, packageId, version));
            }

            var actionResolver = new ActionResolver(
                SourceRepository,
                SourceRepository,
                new ResolutionContext()
            {
                AllowPrerelease    = Prerelease,
                DependencyBehavior = DependencyBehavior,
            });

            var packageActions = await actionResolver.ResolveActionsAsync(new PackageIdentity(packageId, version),
                                                                          PackageActionType.Install,
                                                                          new FilesystemInstallationTarget(packageManager));

            if (Verbosity == NuGet.Verbosity.Detailed)
            {
                Console.WriteLine("Actions returned by resolver");
                foreach (var action in packageActions)
                {
                    Console.WriteLine(action.ActionType.ToString() + "-" + action.PackageIdentity.ToString());
                }
            }

            packageActions = packageActions.Where(a => a.ActionType == PackageActionType.Download || a.ActionType == PackageActionType.Purge);

            if (Verbosity == NuGet.Verbosity.Detailed)
            {
                Console.WriteLine("After reducing actions to just Download and Purge");
                foreach (var action in packageActions)
                {
                    Console.WriteLine(action.ActionType.ToString() + "-" + action.PackageIdentity.ToString());
                }
            }

            var actionExecutor = new ActionExecutor();

            actionExecutor.ExecuteActions(packageActions, Console);
        }
Exemple #23
0
        internal void UpdatePackages(IPackageRepository localRepository,
                                     IFileSystem sharedRepositoryFileSystem,
                                     ISharedPackageRepository sharedPackageRepository,
                                     IPackageRepository sourceRepository,
                                     IPackageConstraintProvider constraintProvider,
                                     IPackagePathResolver pathResolver,
                                     IProjectSystem projectSystem)
        {
            var packageManager = new PackageManager(sourceRepository, pathResolver, sharedRepositoryFileSystem, sharedPackageRepository);

            var projectManager = new ProjectManager(packageManager, pathResolver, projectSystem, 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 = projectSystem.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);
                            }
                        }
                    }
                }
            }
        }
Exemple #24
0
 public void Init_SessionAction_ProperActionResolved(string actionName)
 {
     ActionResolver resolver = new ActionResolver();
     Assert.Equal(BoltFramework.SessionMetadata.Resolve(typeof(IContract1)).InitSession.Action, resolver.Resolve(typeof(IContract1), actionName));
 }
        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);
        }
 protected override void Initialize()
 {
     this.action = ActionResolver.Get(this.Property, this.Attribute.ActionString);
 }
Exemple #27
0
        public void Resolve_Ok(string actionName)
        {
            ActionResolver resolver = new ActionResolver();

            Assert.NotNull(resolver.Resolve(typeof (IContract1), actionName));
        }
        /// <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;
        }
        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());
                }
            }
        }
 public InstallPackageUtility(ActionResolver resolver)
 {
     Resolver = resolver;
     Logger   = NullLogger.Instance;
 }
        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;
                }
            }
        }
        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);
        }
Exemple #33
0
 public void DestroySessionAction_ProperActionResolved(string actionName)
 {
     ActionResolver resolver = new ActionResolver();
     Assert.Equal(BoltFramework.GetSessionDescriptor(typeof(IContract1)).DestroySession, resolver.Resolve(typeof(IContract1), actionName));
 }
Exemple #34
0
 public UpdateUtility(ActionResolver resolver)
 {
     Resolver = resolver;
     Logger   = NullLogger.Instance;
 }
        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);
        }