Пример #1
0
        public IEnumerable <IVsPackageMetadata> GetInstalledPackages()
        {
            var packageManager = _packageManagerFactory.CreatePackageManager();

            return(from package in packageManager.LocalRepository.GetPackages()
                   select new VsPackageMetadata(package, packageManager.PathResolver.GetInstallPath(package)));
        }
Пример #2
0
        private void OnProjectAdded(object sender, ProjectEventArgs e)
        {
            if (IsCurrentSolutionEnabledForRestore)
            {
                EnablePackageRestore(e.Project, _packageManagerFactory.CreatePackageManager());
            }

            CheckForMissingPackages();
        }
Пример #3
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;
                    packageManager.InstallPackage(
                        projectManager,
                        packageId,
                        version,
                        ignoreDependencies,
                        allowPrereleaseVersions: true,
                        skipAssemblyReferences: skipAssemblyReferences,
                        logger: NullLogger.Instance);
                }
                finally
                {
                    packageManager.BindingRedirectEnabled = oldBindingRedirectValue;
                    projectManager.PackageReferenceAdded -= addedHandler;
                    packageManager.PackageInstalled      -= installedHandler;
                }
            }
        }
        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;
                packageManager.UninstallPackage(projectManager, packageId, version: null, forceRemove: false, removeDependencies: removeDependencies);
            }
            finally
            {
                projectManager.PackageReferenceRemoving -= packageReferenceRemovingHandler;
            }
        }
Пример #5
0
        private void ExecuteInitScripts()
        {
            if (!String.IsNullOrEmpty(_solutionManager.SolutionDirectory))
            {
                try {
                    var packageManager  = (VsPackageManager)_packageManagerFactory.CreatePackageManager();
                    var localRepository = packageManager.LocalRepository;

                    // invoke init.ps1 files in the order of package dependency.
                    // if A -> B, we invoke B's init.ps1 before A's.

                    var sorter         = new PackageSorter();
                    var sortedPackages = sorter.GetPackagesByDependencyOrder(localRepository);

                    foreach (var package in sortedPackages)
                    {
                        string installPath = packageManager.PathResolver.GetInstallPath(package);

                        AddPathToEnvironment(Path.Combine(installPath, "tools"));
                        Runspace.ExecuteScript(installPath, "tools\\init.ps1", package);
                    }
                }
                catch (Exception ex) {
                    // if execution of Init scripts fails, do not let it crash our console
                    ReportError(ex);

                    ExceptionHelper.WriteToActivityLog(ex);
                }
            }
        }
Пример #6
0
        internal void InstallPackage(IPackageRepository repository, Project project, string packageId, Version version, bool ignoreDependencies)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(repository);
            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, NullLogger.Instance);
            };

            try {
                projectManager.PackageReferenceAdded += addedHandler;
                packageManager.PackageInstalled      += installedHandler;

                packageManager.InstallPackage(projectManager, packageId, version, ignoreDependencies, NullLogger.Instance);
            }
            finally {
                projectManager.PackageReferenceAdded -= addedHandler;
                packageManager.PackageInstalled      -= installedHandler;
            }
        }
Пример #7
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.CreatePackageManager();
                IPackageRepository localRepository = packageManager.LocalRepository;
                var projectReferences = GetAllPackageReferences(packageManager);
                foreach (var reference in projectReferences)
                {
                    if (!localRepository.Exists(reference.Id, reference.Version))
                    {
                        packageManager.InstallPackage(reference.Id, reference.Version, ignoreDependencies: true, allowPrereleaseVersions: true);
                    }
                }
            });

            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);
        }
Пример #8
0
 protected internal virtual IVsPackageManager GetActivePackageManager()
 {
     if (SelectedNode == null)
     {
         return(null);
     }
     else if (SelectedNode.IsSearchResultsNode)
     {
         PackagesSearchNode searchNode = (PackagesSearchNode)SelectedNode;
         SimpleTreeNode     baseNode   = (SimpleTreeNode)searchNode.BaseNode;
         return(_packageManagerFactory.CreatePackageManager(baseNode.Repository, useFallbackForDependencies: true));
     }
     else
     {
         var selectedNode = SelectedNode as SimpleTreeNode;
         return((selectedNode != null) ? _packageManagerFactory.CreatePackageManager(selectedNode.Repository, useFallbackForDependencies: true) : null);
     }
 }
Пример #9
0
        protected internal override IVsPackageManager GetActivePackageManager()
        {
            if (_recentPackageManager == null)
            {
                var repository = _packageSourceProvider.GetAggregate(_packageRepositoryFactory, ignoreFailingRepositories: true);
                _recentPackageManager = _packageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: false);
            }

            return(_recentPackageManager);
        }
Пример #10
0
        protected internal override IVsPackageManager GetActivePackageManager()
        {
            if (_recentPackageManager == null)
            {
                var repository = _packageRepositoryFactory.CreateRepository(_aggregateSource);
                _recentPackageManager = _packageManagerFactory.CreatePackageManager(repository);
            }

            return(_recentPackageManager);
        }
Пример #11
0
        public void RestorePackages(Project project)
        {
            string packageReferenceFileFullPath;
            Tuple <string, string> packageReferenceFiles = VsUtility.GetPackageReferenceFileFullPaths(project);

            if (File.Exists(packageReferenceFiles.Item1))
            {
                packageReferenceFileFullPath = packageReferenceFiles.Item1;
            }
            else if (File.Exists(packageReferenceFiles.Item2))
            {
                packageReferenceFileFullPath = packageReferenceFiles.Item2;
            }
            else
            {
                return;
            }

            var packageReferenceFile = new PackageReferenceFile(packageReferenceFileFullPath);
            var packages             = packageReferenceFile.GetPackageReferences().ToList();

            if (packages.Count == 0)
            {
                return;
            }

            var repoSettings = ServiceLocator.GetInstance <IRepositorySettings>();
            var fileSystem   = new PhysicalFileSystem(repoSettings.RepositoryPath);
            var activePackageSourceRepository = ServiceLocator.GetInstance <IPackageRepository>();
            var repository = new AggregateRepository(new[] { MachineCache.Default, activePackageSourceRepository });
            IVsPackageManagerFactory packageManagerFactory = ServiceLocator.GetInstance <IVsPackageManagerFactory>();
            var packageManager = packageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: false);

            foreach (var package in packages)
            {
                if (IsPackageInstalled(fileSystem, package.Id, package.Version))
                {
                    continue;
                }

                using (packageManager.SourceRepository.StartOperation(RepositoryOperationNames.Restore, package.Id, package.Version.ToString()))
                {
                    var resolvedPackage = PackageHelper.ResolvePackage(
                        packageManager.SourceRepository, package.Id, package.Version);
                    NuGet.Common.PackageExtractor.InstallPackage(packageManager, resolvedPackage);
                }
            }
        }
        /// <summary>
        /// Restores the given package into the packages folder represented by 'fileSystem'.
        /// </summary>
        /// <param name="package">The package to be restored.</param>
        private void RestorePackage(PackageReference package)
        {
            WriteLine(VerbosityLevel.Normal, Resources.RestoringPackage, package);

            // during package restore, use local cache as the primary source, other sources
            // as secondary source.
            IVsPackageManagerFactory packageManagerFactory = ServiceLocator.GetInstance <IVsPackageManagerFactory>();
            var allSources     = packageManagerFactory.CreatePackageManagerWithAllPackageSources().SourceRepository;
            var repository     = new AggregateRepository(new[] { MachineCache.Default, allSources });
            var packageManager = packageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: false);

            using (packageManager.SourceRepository.StartOperation(RepositoryOperationNames.Restore, package.Id, package.Version.ToString()))
            {
                var resolvedPackage = PackageHelper.ResolvePackage(
                    packageManager.SourceRepository, package.Id, package.Version);
                NuGet.Common.PackageExtractor.InstallPackage(packageManager, resolvedPackage);
                WriteLine(VerbosityLevel.Normal, Resources.PackageRestored, resolvedPackage);
            }
        }
        internal static IPackageRepository GetLocalRepository(IVsPackageManagerFactory packageManagerFactory)
        {
            if (packageManagerFactory == null)
            {
                throw new ArgumentNullException("packageManagerFactory");
            }

            IPackageRepository localRepository = null;

            try
            {
                var packageManager = packageManagerFactory.CreatePackageManager();
                if (packageManager != null)
                {
                    localRepository = packageManager.LocalRepository;
                }
            }
            catch (InvalidOperationException)
            {
                localRepository = null;
            }
            return(localRepository);
        }
Пример #14
0
        private void SetupProviders(Project activeProject,
                                    DTE dte,
                                    IVsPackageManagerFactory packageManagerFactory,
                                    IPackageRepositoryFactory packageRepositoryFactory,
                                    IPackageSourceProvider packageSourceProvider,
                                    ProviderServices providerServices,
                                    IPackageRepository recentPackagesRepository,
                                    IHttpClientEvents httpClientEvents,
                                    ISolutionManager solutionManager,
                                    IPackageRestoreManager packageRestoreManager)
        {

            // This package manager is not used for installing from a remote source, and therefore does not need a fallback repository for resolving dependencies
            IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager(ServiceLocator.GetInstance<IPackageRepository>(), useFallbackForDependencies: false);

            IPackageRepository localRepository;

            // we need different sets of providers depending on whether the dialog is open for solution or a project
            OnlineProvider onlineProvider;
            InstalledProvider installedProvider;
            UpdatesProvider updatesProvider;
            OnlineProvider recentProvider;

            if (activeProject == null)
            {
                Title = String.Format(
                    CultureInfo.CurrentUICulture,
                    NuGet.Dialog.Resources.Dialog_Title,
                    dte.Solution.GetName() + ".sln");

                localRepository = packageManager.LocalRepository;

                onlineProvider = new SolutionOnlineProvider(
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                installedProvider = new SolutionInstalledProvider(
                    packageManager,
                    localRepository,
                    Resources,
                    providerServices,
                    httpClientEvents,
                    solutionManager,
                    packageRestoreManager);

                updatesProvider = new SolutionUpdatesProvider(
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                recentProvider = new SolutionRecentProvider(
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageManagerFactory,
                    recentPackagesRepository,
                    packageSourceProvider,
                    providerServices,
                    httpClientEvents,
                    solutionManager);
            }
            else
            {
                IProjectManager projectManager = packageManager.GetProjectManager(activeProject);
                localRepository = projectManager.LocalRepository;

                Title = String.Format(
                    CultureInfo.CurrentUICulture,
                    NuGet.Dialog.Resources.Dialog_Title,
                    activeProject.GetDisplayName());

                onlineProvider = new OnlineProvider(
                    activeProject,
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                installedProvider = new InstalledProvider(
                    packageManager,
                    activeProject,
                    localRepository,
                    Resources,
                    providerServices,
                    httpClientEvents,
                    solutionManager,
                    packageRestoreManager);

                updatesProvider = new UpdatesProvider(
                    activeProject,
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                recentProvider = new RecentProvider(
                    activeProject,
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageManagerFactory,
                    recentPackagesRepository,
                    packageSourceProvider,
                    providerServices,
                    httpClientEvents,
                    solutionManager);
            }

            explorer.Providers.Add(installedProvider);
            explorer.Providers.Add(onlineProvider);
            explorer.Providers.Add(updatesProvider);
            explorer.Providers.Add(recentProvider);

            installedProvider.IncludePrerelease =
                onlineProvider.IncludePrerelease =
                updatesProvider.IncludePrerelease =
                recentProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages;

            // retrieve the selected provider from the settings
            int selectedProvider = Math.Min(3, _providerSettings.SelectedProvider);
            explorer.SelectedProvider = explorer.Providers[selectedProvider];
        }
Пример #15
0
        private void SetupProviders(Project activeProject,
                                    DTE dte,
                                    IVsPackageManagerFactory packageManagerFactory,
                                    IPackageRepositoryFactory packageRepositoryFactory,
                                    IPackageSourceProvider packageSourceProvider,
                                    ProviderServices providerServices,
                                    IHttpClientEvents httpClientEvents,
                                    ISolutionManager solutionManager,
                                    IPackageRestoreManager packageRestoreManager,
                                    RestartRequestBar restartRequestBar)
        {
            // This package manager is not used for installing from a remote source, and therefore does not need a fallback repository for resolving dependencies
            IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager(ServiceLocator.GetInstance <IPackageRepository>(), useFallbackForDependencies: false);

            IPackageRepository localRepository;

            // we need different sets of providers depending on whether the dialog is open for solution or a project
            OnlineProvider    onlineProvider;
            InstalledProvider installedProvider;
            UpdatesProvider   updatesProvider;

            if (activeProject == null)
            {
                Title = String.Format(
                    CultureInfo.CurrentUICulture,
                    NuGet.Dialog.Resources.Dialog_Title,
                    dte.Solution.GetName() + ".sln");

                localRepository = packageManager.LocalRepository;

                onlineProvider = new SolutionOnlineProvider(
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                installedProvider = new SolutionInstalledProvider(
                    packageManager,
                    localRepository,
                    Resources,
                    providerServices,
                    httpClientEvents,
                    solutionManager,
                    packageRestoreManager);

                updatesProvider = new SolutionUpdatesProvider(
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);
            }
            else
            {
                IProjectManager projectManager = packageManager.GetProjectManager(activeProject);
                localRepository = projectManager.LocalRepository;

                Title = String.Format(
                    CultureInfo.CurrentUICulture,
                    NuGet.Dialog.Resources.Dialog_Title,
                    activeProject.GetDisplayName());

                onlineProvider = new OnlineProvider(
                    activeProject,
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);

                installedProvider = new InstalledProvider(
                    packageManager,
                    activeProject,
                    localRepository,
                    Resources,
                    providerServices,
                    httpClientEvents,
                    solutionManager,
                    packageRestoreManager);

                updatesProvider = new UpdatesProvider(
                    activeProject,
                    localRepository,
                    Resources,
                    packageRepositoryFactory,
                    packageSourceProvider,
                    packageManagerFactory,
                    providerServices,
                    httpClientEvents,
                    solutionManager);
            }

            explorer.Providers.Add(installedProvider);
            explorer.Providers.Add(onlineProvider);
            explorer.Providers.Add(updatesProvider);

            installedProvider.IncludePrerelease       =
                onlineProvider.IncludePrerelease      =
                    updatesProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages;

            installedProvider.ExecuteCompletedCallback       =
                onlineProvider.ExecuteCompletedCallback      =
                    updatesProvider.ExecuteCompletedCallback = restartRequestBar.CheckForUnsuccessfulUninstall;

            Loaded += (o, e) => restartRequestBar.CheckForUnsuccessfulUninstall();
        }
Пример #16
0
        private void SetupProviders(DTE dte,
                                    IVsPackageManagerFactory packageManagerFactory,
                                    IPackageRepositoryFactory packageRepositoryFactory,
                                    IPackageSourceProvider packageSourceProvider,
                                    ProviderServices providerServices,
                                    IPackageRepository recentPackagesRepository,
                                    IHttpClientEvents httpClientEvents)
        {
            IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager();
            Project           activeProject  = dte.GetActiveProject();

            // Create a cached project manager so that checking for installed packages is fast
            IProjectManager projectManager = packageManager.GetProjectManager(activeProject);

            var recentProvider = new RecentProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageManagerFactory,
                recentPackagesRepository,
                packageSourceProvider,
                providerServices,
                httpClientEvents);


            var updatesProvider = new UpdatesProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageSourceProvider,
                packageManagerFactory,
                providerServices,
                httpClientEvents);

            var onlineProvider = new OnlineProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageSourceProvider,
                packageManagerFactory,
                providerServices,
                httpClientEvents);

            var installedProvider = new InstalledProvider(
                packageManager,
                activeProject,
                projectManager,
                Resources,
                providerServices,
                httpClientEvents);

            explorer.Providers.Add(installedProvider);
            explorer.Providers.Add(onlineProvider);
            explorer.Providers.Add(updatesProvider);
            explorer.Providers.Add(recentProvider);

            // retrieve the selected provider from the settings
            int selectedProvider = Math.Min(3, _selectedProviderSettings.SelectedProvider);

            explorer.SelectedProvider = explorer.Providers[selectedProvider];
        }
Пример #17
0
        private void SetupProviders(DTE dte,
            IVsPackageManagerFactory packageManagerFactory,
            IPackageRepositoryFactory packageRepositoryFactory,
            IPackageSourceProvider packageSourceProvider,
            ProviderServices providerServices,
            IPackageRepository recentPackagesRepository,
            IHttpClientEvents httpClientEvents)
        {
            IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager();
            Project activeProject = dte.GetActiveProject();

            // Create a cached project manager so that checking for installed packages is fast
            IProjectManager projectManager = packageManager.GetProjectManager(activeProject);

            var recentProvider = new RecentProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageManagerFactory,
                recentPackagesRepository,
                packageSourceProvider,
                providerServices,
                httpClientEvents);

            var updatesProvider = new UpdatesProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageSourceProvider,
                packageManagerFactory,
                providerServices,
                httpClientEvents);

            var onlineProvider = new OnlineProvider(
                activeProject,
                projectManager,
                Resources,
                packageRepositoryFactory,
                packageSourceProvider,
                packageManagerFactory,
                providerServices,
                httpClientEvents);

            var installedProvider = new InstalledProvider(
                packageManager,
                activeProject,
                projectManager,
                Resources,
                providerServices,
                httpClientEvents);

            explorer.Providers.Add(installedProvider);
            explorer.Providers.Add(onlineProvider);
            explorer.Providers.Add(updatesProvider);
            explorer.Providers.Add(recentProvider);

            // retrieve the selected provider from the settings
            int selectedProvider = Math.Min(3, _selectedProviderSettings.SelectedProvider);
            explorer.SelectedProvider = explorer.Providers[selectedProvider];
        }
Пример #18
0
        internal static IPackageRepository GetLocalRepository(IVsPackageManagerFactory packageManagerFactory)
        {
            if (packageManagerFactory == null)
            {
                throw new ArgumentNullException("packageManagerFactory");
            }

            IPackageRepository localRepository = null;
            try
            {
                var packageManager = packageManagerFactory.CreatePackageManager();
                if (packageManager != null)
                {
                    localRepository = packageManager.LocalRepository;
                }
            }
            catch (InvalidOperationException)
            {
                localRepository = null;
            }
            return localRepository;
        }
        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;
                }
            }
        }