コード例 #1
0
        private async Task PerformActionAsync(
            INuGetUI uiService,
            UserAction userAction,
            NuGetOperationType operationType,
            ResolveActionsAsync resolveActionsAsync,
            CancellationToken cancellationToken)
        {
            IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

            using (INuGetProjectManagerService projectManagerService = await serviceBroker.GetProxyAsync <INuGetProjectManagerService>(
                       NuGetServices.ProjectManagerService,
                       cancellationToken: cancellationToken))
            {
                Assumes.NotNull(projectManagerService);

                await projectManagerService.BeginOperationAsync(cancellationToken);

                try
                {
                    await PerformActionImplAsync(
                        serviceBroker,
                        projectManagerService,
                        uiService,
                        resolveActionsAsync,
                        operationType,
                        userAction,
                        cancellationToken);
                }
                finally
                {
                    await projectManagerService.EndOperationAsync(cancellationToken);
                }
            }
        }
コード例 #2
0
ファイル: NuGetUI.cs プロジェクト: sohaib928/NuGet.Client
        public async Task UpgradeProjectsToPackageReferenceAsync(IEnumerable <IProjectContextInfo> msBuildProjects)
        {
            if (msBuildProjects == null)
            {
                throw new ArgumentNullException(nameof(msBuildProjects));
            }

            List <IProjectContextInfo> projects = Projects.ToList();

            IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

            using (INuGetProjectUpgraderService projectUpgrader = await serviceBroker.GetProxyAsync <INuGetProjectUpgraderService>(
                       NuGetServices.ProjectUpgraderService,
                       cancellationToken: CancellationToken.None))
            {
                Assumes.NotNull(projectUpgrader);

                foreach (IProjectContextInfo project in msBuildProjects)
                {
                    IProjectContextInfo newProject = await projectUpgrader.UpgradeProjectToPackageReferenceAsync(
                        project.ProjectId,
                        CancellationToken.None);

                    if (newProject != null)
                    {
                        projects.Remove(project);
                        projects.Add(newProject);
                    }
                }
            }

            Projects = projects;
        }
コード例 #3
0
        public static async ValueTask <NuGetUIContext> CreateAsync(
            ISourceRepositoryProvider sourceRepositoryProvider,
            ISettings settings,
            IVsSolutionManager solutionManager,
            IPackageRestoreManager packageRestoreManager,
            IOptionsPageActivator optionsPageActivator,
            IUserSettingsManager userSettingsManager,
            IDeleteOnRestartManager deleteOnRestartManager,
            IEnumerable <IVsPackageManagerProvider> packageManagerProviders,
            INuGetLockService lockService,
            CancellationToken cancellationToken)
        {
            Assumes.NotNull(sourceRepositoryProvider);
            Assumes.NotNull(settings);
            Assumes.NotNull(solutionManager);
            Assumes.NotNull(packageRestoreManager);
            Assumes.NotNull(optionsPageActivator);
            Assumes.NotNull(userSettingsManager);
            Assumes.NotNull(deleteOnRestartManager);
            Assumes.NotNull(packageManagerProviders);
            Assumes.NotNull(lockService);

            cancellationToken.ThrowIfCancellationRequested();

            IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

            var solutionManagerServiceWrapper = new NuGetSolutionManagerServiceWrapper();
            var solutionManagerService        = await GetSolutionManagerServiceAsync(serviceBroker, cancellationToken);

            // The initial Swap(...) should return a null implementation of the interface that does not require disposal.
            // However, there's no harm in following form.
            using (solutionManagerServiceWrapper.Swap(solutionManagerService))
            {
            }

            var packageManager = new NuGetPackageManager(
                sourceRepositoryProvider,
                settings,
                solutionManager,
                deleteOnRestartManager);

            var actionEngine = new UIActionEngine(
                sourceRepositoryProvider,
                packageManager,
                lockService);

            return(new NuGetUIContext(
                       sourceRepositoryProvider,
                       serviceBroker,
                       solutionManager,
                       solutionManagerServiceWrapper,
                       packageManager,
                       actionEngine,
                       packageRestoreManager,
                       optionsPageActivator,
                       userSettingsManager,
                       packageManagerProviders));
        }
コード例 #4
0
        /// <summary>
        /// Perform the multi-package update action.
        /// </summary>
        /// <remarks>This needs to be called from a background thread. It may hang on the UI thread.</remarks>
        public async Task PerformUpdateAsync(
            INuGetUI uiService,
            List <PackageIdentity> packagesToUpdate,
            CancellationToken cancellationToken)
        {
            IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

            using (INuGetProjectManagerService projectManagerService = await serviceBroker.GetProxyAsync <INuGetProjectManagerService>(
                       NuGetServices.ProjectManagerService,
                       cancellationToken: cancellationToken))
            {
                Assumes.NotNull(projectManagerService);

                await PerformActionAsync(
                    uiService,
                    userAction : null,
                    NuGetOperationType.Update,
                    (projectManagerService) =>
                    ResolveActionsForUpdateAsync(projectManagerService, uiService, packagesToUpdate, cancellationToken),
                    cancellationToken);
            }
        }
コード例 #5
0
        public ConsoleContainer()
        {
            InitializeComponent();

            ThreadHelper.JoinableTaskFactory.StartOnIdle(
                async() =>
            {
                await System.Threading.Tasks.Task.Run(
                    async() =>
                {
                    IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

                    _solutionManager = await serviceBroker.GetProxyAsync <INuGetSolutionManagerService>(
                        NuGetServices.SolutionManagerService,
                        cancellationToken: CancellationToken.None);

                    Assumes.NotNull(_solutionManager);

                    var productUpdateService   = ServiceLocator.GetInstance <IProductUpdateService>();
                    var packageRestoreManager  = ServiceLocator.GetInstance <IPackageRestoreManager>();
                    var deleteOnRestartManager = ServiceLocator.GetInstance <IDeleteOnRestartManager>();
                    var shell = ServiceLocator.GetGlobalService <SVsShell, IVsShell4>();

                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    RootLayout.Children.Add(new ProductUpdateBar(productUpdateService));
                    RootLayout.Children.Add(new PackageRestoreBar(_solutionManager, packageRestoreManager));
                    RootLayout.Children.Add(new RestartRequestBar(deleteOnRestartManager, shell));
                });
            }, VsTaskRunContext.UIThreadIdlePriority);

            // Set DynamicResource binding in code
            // The reason we can't set it in XAML is that the VsBrushes class come from either
            // Microsoft.VisualStudio.Shell.10 or Microsoft.VisualStudio.Shell.11 assembly,
            // depending on whether NuGet runs inside VS10 or VS11.
            InitializeText.SetResourceReference(TextBlock.ForegroundProperty, VsBrushes.WindowTextKey);
        }
        internal static async Task <string> DoUpgradeAsync(
            INuGetUIContext context,
            INuGetUI uiService,
            IProjectContextInfo project,
            IEnumerable <NuGetProjectUpgradeDependencyItem> upgradeDependencyItems,
            IEnumerable <PackageIdentity> notFoundPackages,
            IProgress <ProgressDialogData> progress,
            CancellationToken token)
        {
            var startTime     = DateTimeOffset.Now;
            var packagesCount = 0;
            var status        = NuGetOperationStatus.Succeeded;

            var upgradeInformationTelemetryEvent = new UpgradeInformationTelemetryEvent();

            using (var telemetry = TelemetryActivity.Create(upgradeInformationTelemetryEvent))
            {
                try
                {
                    // 0. Fail if any package was not found
                    if (notFoundPackages.Any())
                    {
                        status = NuGetOperationStatus.Failed;
                        var notFoundPackageIds = string.Join(",", notFoundPackages.Select(t => t.Id));
                        uiService.ProjectContext.Log(MessageLevel.Error, string.Format(CultureInfo.CurrentCulture, Resources.Migrator_PackageNotFound, notFoundPackageIds));
                        return(null);
                    }

                    IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

                    using (INuGetProjectUpgraderService projectUpgrader = await serviceBroker.GetProxyAsync <INuGetProjectUpgraderService>(
                               NuGetServices.ProjectUpgraderService,
                               token))
                    {
                        Assumes.NotNull(projectUpgrader);

                        string backupPath;

                        // 1. Backup files (csproj and packages.config) that will change
                        try
                        {
                            backupPath = await projectUpgrader.BackupProjectAsync(project.ProjectId, token);
                        }
                        catch (Exception ex)
                        {
                            status = NuGetOperationStatus.Failed;

                            uiService.ShowError(ex);
                            uiService.ProjectContext.Log(
                                MessageLevel.Info,
                                string.Format(CultureInfo.CurrentCulture, Resources.Upgrader_BackupFailed));

                            return(null);
                        }

                        // 2. Uninstall all packages currently in packages.config
                        var progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Uninstalling);
                        progress.Report(progressData);

                        // Don't uninstall packages we couldn't find - that will just fail
                        PackageIdentity[] packagesToUninstall = upgradeDependencyItems.Select(d => d.Identity)
                                                                .Where(p => !notFoundPackages.Contains(p))
                                                                .ToArray();

                        try
                        {
                            await projectUpgrader.UninstallPackagesAsync(project.ProjectId, packagesToUninstall, token);
                        }
                        catch (Exception ex)
                        {
                            status = NuGetOperationStatus.Failed;
                            // log error message
                            uiService.ShowError(ex);
                            uiService.ProjectContext.Log(MessageLevel.Info,
                                                         string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_UninstallFailed));

                            return(null);
                        }

                        // Reload the project, and get a reference to the reloaded project
                        await projectUpgrader.SaveProjectAsync(project.ProjectId, token);

                        IProjectContextInfo upgradedProject = await projectUpgrader.UpgradeProjectToPackageReferenceAsync(
                            project.ProjectId,
                            token);

                        // Ensure we use the updated project for installing, and don't display preview or license acceptance windows.
                        context.Projects = new[] { upgradedProject };
                        var nuGetUI = (NuGetUI)uiService;
                        nuGetUI.Projects             = new[] { upgradedProject };
                        nuGetUI.DisplayPreviewWindow = false;

                        // 4. Install the requested packages
                        var ideExecutionContext = uiService.ProjectContext.ExecutionContext as IDEExecutionContext;
                        if (ideExecutionContext != null)
                        {
                            await ideExecutionContext.SaveExpandedNodeStates(context.SolutionManager);
                        }

                        progressData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage, Resources.NuGetUpgrade_Progress_Installing);
                        progress.Report(progressData);

                        List <PackageIdentity> packagesToInstall = GetPackagesToInstall(upgradeDependencyItems).ToList();
                        packagesCount = packagesToInstall.Count;

                        try
                        {
                            await projectUpgrader.InstallPackagesAsync(
                                project.ProjectId,
                                packagesToInstall,
                                token);

                            if (ideExecutionContext != null)
                            {
                                await ideExecutionContext.CollapseAllNodes(context.SolutionManager);
                            }

                            return(backupPath);
                        }
                        catch (Exception ex)
                        {
                            status = NuGetOperationStatus.Failed;

                            uiService.ShowError(ex);
                            uiService.ProjectContext.Log(MessageLevel.Info,
                                                         string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_InstallFailed, backupPath));
                            uiService.ProjectContext.Log(MessageLevel.Info,
                                                         string.Format(CultureInfo.CurrentCulture, Resources.Upgrade_RevertSteps, "https://aka.ms/nugetupgraderevertv1"));

                            return(null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    status = NuGetOperationStatus.Failed;
                    uiService.ShowError(ex);
                    return(null);
                }
                finally
                {
                    IEnumerable <string> projectIds = await ProjectUtility.GetSortedProjectIdsAsync(uiService.Projects, token);

                    upgradeInformationTelemetryEvent.SetResult(projectIds, status, packagesCount);
                }
            }
        }
コード例 #7
0
        internal async Task InitializeOnActivatedAsync(CancellationToken cancellationToken)
        {
            try
            {
                if (_initialized)
                {
                    return;
                }

                _initialized = true;

                var remoteBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

#pragma warning disable ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
                _nugetSourcesService = await remoteBroker.GetProxyAsync <INuGetSourcesService>(NuGetServices.SourceProviderService, cancellationToken : cancellationToken);

#pragma warning restore ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
                Assumes.NotNull(_nugetSourcesService);

                // get packages sources
                _originalPackageSources = await _nugetSourcesService.GetPackageSourcesAsync(cancellationToken);

                // packageSources and machineWidePackageSources are deep cloned when created, no need to worry about re-querying for sources to diff changes
                var allPackageSources         = _originalPackageSources;
                var packageSources            = allPackageSources.Where(ps => !ps.IsMachineWide).ToList();
                var machineWidePackageSources = allPackageSources.Where(ps => ps.IsMachineWide).ToList();
                //_activeSource = _packageSourceProvider.ActivePackageSource;

                // bind to the package sources, excluding Aggregate
                _packageSources = new BindingSource(packageSources.Select(ps => ps.Clone()).ToList(), null);
                _packageSources.CurrentChanged  += OnSelectedPackageSourceChanged;
                PackageSourcesListBox.GotFocus  += PackageSourcesListBox_GotFocus;
                PackageSourcesListBox.DataSource = _packageSources;

                if (machineWidePackageSources.Count > 0)
                {
                    _machineWidepackageSources = new BindingSource(machineWidePackageSources.Select(ps => ps.Clone()).ToList(), null);
                    _machineWidepackageSources.CurrentChanged  += OnSelectedMachineWidePackageSourceChanged;
                    MachineWidePackageSourcesListBox.GotFocus  += MachineWidePackageSourcesListBox_GotFocus;
                    MachineWidePackageSourcesListBox.DataSource = _machineWidepackageSources;
                }
                else
                {
                    MachineWidePackageSourcesListBox.Visible = MachineWideSourcesLabel.Visible = false;
                }

                OnSelectedPackageSourceChanged(null, EventArgs.Empty);
            }
            // Thrown during creating or saving NuGet.Config.
            catch (NuGetConfigurationException ex)
            {
                MessageHelper.ShowErrorMessage(ex.Message, Resources.ErrorDialogBoxTitle);
            }
            // Thrown if no nuget.config found.
            catch (InvalidOperationException ex)
            {
                MessageHelper.ShowErrorMessage(ex.Message, Resources.ErrorDialogBoxTitle);
            }
            catch (UnauthorizedAccessException)
            {
                MessageHelper.ShowErrorMessage(Resources.ShowError_ConfigUnauthorizedAccess, Resources.ErrorDialogBoxTitle);
            }
            // Unknown exception.
            catch (Exception ex)
            {
                MessageHelper.ShowErrorMessage(Resources.ShowError_SettingActivatedFailed, Resources.ErrorDialogBoxTitle);
                ActivityLog.LogError(NuGetUI.LogEntrySource, ex.ToString());
            }
        }
 internal CachingIServiceBrokerProvider()
 {
     _serviceBroker = new AsyncLazy <IServiceBroker>(
         () => BrokeredServicesUtilities.GetRemoteServiceBrokerAsync().AsTask(),
         NuGetUIThreadHelper.JoinableTaskFactory);
 }
コード例 #9
0
        public async Task UpgradeNuGetProjectAsync(INuGetUI uiService, IProjectContextInfo project)
        {
            Assumes.NotNull(uiService);
            Assumes.NotNull(project);

            INuGetUIContext context = uiService.UIContext;
            // Restore the project before proceeding
            string solutionDirectory = await context.SolutionManagerService.GetSolutionDirectoryAsync(CancellationToken.None);

            await context.PackageRestoreManager.RestoreMissingPackagesInSolutionAsync(
                solutionDirectory,
                uiService.ProjectContext,
                new LoggerAdapter(uiService.ProjectContext),
                CancellationToken.None);

            IServiceBroker serviceBroker = await BrokeredServicesUtilities.GetRemoteServiceBrokerAsync();

            NuGetProjectUpgradeWindowModel upgradeInformationWindowModel;

            using (INuGetProjectManagerService projectManager = await serviceBroker.GetProxyAsync <INuGetProjectManagerService>(
                       NuGetServices.ProjectManagerService,
                       CancellationToken.None))
            {
                Assumes.NotNull(projectManager);

                IReadOnlyCollection <PackageDependencyInfo> packagesDependencyInfo = await projectManager.GetInstalledPackagesDependencyInfoAsync(
                    project.ProjectId,
                    includeUnresolved : true,
                    CancellationToken.None);

                upgradeInformationWindowModel = await NuGetProjectUpgradeWindowModel.CreateAsync(
                    project,
                    packagesDependencyInfo.ToList(),
                    CancellationToken.None);
            }

            var result = uiService.ShowNuGetUpgradeWindow(upgradeInformationWindowModel);

            if (!result)
            {
                // raise upgrade telemetry event with Cancelled status
                var packagesCount = upgradeInformationWindowModel.UpgradeDependencyItems.Count;

                var upgradeTelemetryEvent       = new UpgradeInformationTelemetryEvent();
                IEnumerable <string> projectIds = await ProjectUtility.GetSortedProjectIdsAsync(uiService.Projects, CancellationToken.None);

                upgradeTelemetryEvent.SetResult(
                    projectIds,
                    NuGetOperationStatus.Cancelled,
                    packagesCount);

                TelemetryActivity.EmitTelemetryEvent(upgradeTelemetryEvent);

                return;
            }

            var    progressDialogData = new ProgressDialogData(Resources.NuGetUpgrade_WaitMessage);
            string projectName        = await project.GetUniqueNameOrNameAsync(CancellationToken.None);

            string backupPath;

            var windowTitle = string.Format(
                CultureInfo.CurrentCulture,
                Resources.WindowTitle_NuGetMigrator,
                projectName);

            using (IModalProgressDialogSession progressDialogSession = await context.StartModalProgressDialogAsync(windowTitle, progressDialogData, uiService))
            {
                backupPath = await PackagesConfigToPackageReferenceMigrator.DoUpgradeAsync(
                    context,
                    uiService,
                    project,
                    upgradeInformationWindowModel.UpgradeDependencyItems,
                    upgradeInformationWindowModel.NotFoundPackages,
                    progressDialogSession.Progress,
                    progressDialogSession.UserCancellationToken);
            }

            if (!string.IsNullOrEmpty(backupPath))
            {
                string htmlLogFile = GenerateUpgradeReport(projectName, backupPath, upgradeInformationWindowModel);

                Process process = null;
                try
                {
                    process = Process.Start(htmlLogFile);
                }
                catch { }
            }
        }