int IVsSolutionEventsProjectUpgrade.OnAfterUpgradeProject(IVsHierarchy pHierarchy, uint fUpgradeFlag, string bstrCopyLocation, SYSTEMTIME stUpgradeTime, IVsUpgradeLogger pLogger) { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Debug.Assert(pHierarchy != null); Project upgradedProject = VsHierarchyUtility.GetProjectFromHierarchy(pHierarchy); var upgradedNuGetProject = EnvDTEProjectUtility.GetNuGetProject(upgradedProject, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(upgradedNuGetProject)) { IList <PackageIdentity> packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(upgradedNuGetProject); if (packagesToBeReinstalled.Any()) { pLogger.LogMessage((int)__VSUL_ERRORLEVEL.VSUL_ERROR, upgradedProject.Name, upgradedProject.Name, String.Format(CultureInfo.CurrentCulture, Resources.ProjectUpgradeAndRetargetErrorMessage, String.Join(", ", packagesToBeReinstalled.Select(p => p.Id)))); } } }); return(VSConstants.S_OK); }
int IVsTrackProjectRetargetingEvents.OnRetargetingAfterChange(string projRef, IVsHierarchy pAfterChangeHier, string fromTargetFramework, string toTargetFramework) { NuGetProject retargetedProject = null; NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _errorListProvider.Tasks.Clear(); var project = VsHierarchyUtility.GetProjectFromHierarchy(pAfterChangeHier); retargetedProject = EnvDTEProjectUtility.GetNuGetProject(project, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(retargetedProject)) { var packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(retargetedProject); if (packagesToBeReinstalled.Any()) { ShowRetargetingErrorTask(packagesToBeReinstalled.Select(p => p.Id), pAfterChangeHier, TaskErrorCategory.Error, TaskPriority.High); } ProjectRetargetingUtility.MarkPackagesForReinstallation(retargetedProject, packagesToBeReinstalled); } }); #if !VS14 if (retargetedProject != null && retargetedProject is LegacyCSProjPackageReferenceProject) { // trigger solution restore and don't wait for it to be complete and hold the UI thread System.Threading.Tasks.Task.Run(() => _solutionRestoreWorker.Value.ScheduleRestoreAsync(SolutionRestoreRequest.ByMenu(), CancellationToken.None)); } #endif return(VSConstants.S_OK); }
public static async Task <bool> IsNuGetProjectUpgradeableAsync(NuGetProject nuGetProject, Project envDTEProject = null) { ThreadHelper.ThrowIfNotOnUIThread(); if (nuGetProject == null && envDTEProject == null) { return(false); } if (nuGetProject == null) { var solutionManager = ServiceLocator.GetInstance <IVsSolutionManager>(); var projectSafeName = await EnvDTEProjectInfoUtility.GetCustomUniqueNameAsync(envDTEProject); nuGetProject = await solutionManager.GetNuGetProjectAsync(projectSafeName); if (nuGetProject == null) { return(false); } } if (!nuGetProject.ProjectServices.Capabilities.SupportsPackageReferences) { return(false); } var msBuildNuGetProject = nuGetProject as MSBuildNuGetProject; if (msBuildNuGetProject == null || !msBuildNuGetProject.PackagesConfigNuGetProject.PackagesConfigExists()) { return(false); } if (envDTEProject == null) { var vsmsBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem as VsMSBuildProjectSystem; if (vsmsBuildNuGetProjectSystem == null) { return(false); } envDTEProject = vsmsBuildNuGetProjectSystem.VsProjectAdapter.Project; } if (!EnvDTEProjectUtility.IsSupported(envDTEProject)) { return(false); } var projectGuids = VsHierarchyUtility.GetProjectTypeGuids(envDTEProject); if (projectGuids.Any(t => UnupgradeableProjectTypes.Contains(t))) { return(false); } // Project is supported language, and not an unsupported type return(UpgradeableProjectTypes.Contains(envDTEProject.Kind) && projectGuids.All(projectTypeGuid => !SupportedProjectTypes.IsUnsupported(projectTypeGuid))); }
int IVsTrackBatchRetargetingEvents.OnBatchRetargetingEnd() { NuGetProject nuGetProject = null; NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _errorListProvider.Tasks.Clear(); if (_platformRetargetingProject != null) { try { var project = _dte.Solution.Item(_platformRetargetingProject); if (project != null) { nuGetProject = EnvDTEProjectUtility.GetNuGetProject(project, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(nuGetProject)) { var frameworkName = EnvDTEProjectUtility.GetTargetFrameworkString(project); if (NETCore451.Equals(frameworkName, StringComparison.OrdinalIgnoreCase) || Windows81.Equals(frameworkName, StringComparison.OrdinalIgnoreCase)) { IList <PackageIdentity> packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(nuGetProject); if (packagesToBeReinstalled.Count > 0) { // By asserting that NuGet is in use, we are also asserting that NuGet.VisualStudio.dll is already loaded // Hence, it is okay to call project.ToVsHierarchy() Debug.Assert(ProjectRetargetingUtility.IsNuGetInUse(project)); IVsHierarchy projectHierarchy = VsHierarchyUtility.ToVsHierarchy(project); ShowRetargetingErrorTask(packagesToBeReinstalled.Select(p => p.Id), projectHierarchy, TaskErrorCategory.Error, TaskPriority.High); } ProjectRetargetingUtility.MarkPackagesForReinstallation(nuGetProject, packagesToBeReinstalled); } } } } catch (ArgumentException) { // If the solution does not contain a project named '_platformRetargetingProject', it will throw ArgumentException } _platformRetargetingProject = null; } }); #if !VS14 if (nuGetProject != null && nuGetProject is LegacyCSProjPackageReferenceProject) { // trigger solution restore and don't wait for it to be complete and hold the UI thread System.Threading.Tasks.Task.Run(() => _solutionRestoreWorker.Value.ScheduleRestoreAsync(SolutionRestoreRequest.ByMenu(), CancellationToken.None)); } #endif return(VSConstants.S_OK); }
private async Task <IVsWindowFrame> CreateNewWindowFrameAsync(Project project) { ThreadHelper.ThrowIfNotOnUIThread(); var vsProject = VsHierarchyUtility.ToVsHierarchy(project); var documentName = project.FullName; // Find existing hierarchy and item id of the document window if it's // already registered. var rdt = await GetServiceAsync(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; Assumes.Present(rdt); IVsHierarchy hier; uint itemId; var docData = IntPtr.Zero; int hr; try { uint cookie; hr = rdt.FindAndLockDocument( (uint)_VSRDTFLAGS.RDT_NoLock, documentName, out hier, out itemId, out docData, out cookie); if (hr != VSConstants.S_OK) { // the docuemnt window is not registered yet. So use the project as the // hierarchy. hier = vsProject; itemId = (uint)VSConstants.VSITEMID.Root; } } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); docData = IntPtr.Zero; } } // Create the doc window using the hiearchy & item id. return(await CreateDocWindowAsync(project, documentName, hier, itemId)); }
int IVsTrackBatchRetargetingEvents.OnBatchRetargetingEnd() { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _errorListProvider.Tasks.Clear(); if (_platformRetargetingProject != null) { try { var project = _dte.Solution.Item(_platformRetargetingProject); if (project != null) { var nuGetProject = EnvDTEProjectUtility.GetNuGetProject(project, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(nuGetProject)) { var frameworkName = EnvDTEProjectUtility.GetTargetFrameworkString(project); if (NETCore451.Equals(frameworkName, StringComparison.OrdinalIgnoreCase) || Windows81.Equals(frameworkName, StringComparison.OrdinalIgnoreCase)) { IList <PackageIdentity> packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(nuGetProject); if (packagesToBeReinstalled.Count > 0) { // By asserting that NuGet is in use, we are also asserting that NuGet.VisualStudio.dll is already loaded // Hence, it is okay to call project.ToVsHierarchy() Debug.Assert(ProjectRetargetingUtility.IsNuGetInUse(project)); IVsHierarchy projectHierarchy = VsHierarchyUtility.ToVsHierarchy(project); ShowRetargetingErrorTask(packagesToBeReinstalled.Select(p => p.Id), projectHierarchy, TaskErrorCategory.Error, TaskPriority.High); } ProjectRetargetingUtility.MarkPackagesForReinstallation(nuGetProject, packagesToBeReinstalled); } } } } catch (ArgumentException) { // If the solution does not contain a project named '_platformRetargetingProject', it will throw ArgumentException } _platformRetargetingProject = null; } }); return(VSConstants.S_OK); }
private void ShowWarningsForPackageReinstallation(Solution solution) { Debug.Assert(solution != null); foreach (Project project in solution.Projects) { var nuGetProject = EnvDTEProjectUtility.GetNuGetProject(project, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(nuGetProject)) { var packageReferencesToBeReinstalled = ProjectRetargetingUtility.GetPackageReferencesMarkedForReinstallation(nuGetProject); if (packageReferencesToBeReinstalled.Count > 0) { Debug.Assert(ProjectRetargetingUtility.IsNuGetInUse(project)); var projectHierarchy = VsHierarchyUtility.ToVsHierarchy(project); ShowRetargetingErrorTask(packageReferencesToBeReinstalled.Select(p => p.PackageIdentity.Id), projectHierarchy, TaskErrorCategory.Warning, TaskPriority.Normal); } } } }
private IVsWindowFrame CreateNewWindowFrame(Project project) { var vsProject = VsHierarchyUtility.ToVsHierarchy(project); var documentName = project.UniqueName; // Find existing hierarchy and item id of the document window if it's // already registered. var rdt = (IVsRunningDocumentTable)GetService(typeof(IVsRunningDocumentTable)); IVsHierarchy hier; uint itemId; IntPtr docData = IntPtr.Zero; int hr; try { uint cookie; hr = rdt.FindAndLockDocument( (uint)_VSRDTFLAGS.RDT_NoLock, documentName, out hier, out itemId, out docData, out cookie); if (hr != VSConstants.S_OK) { // the docuemnt window is not registered yet. So use the project as the // hierarchy. hier = (IVsHierarchy)vsProject; itemId = (uint)VSConstants.VSITEMID.Root; } } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); docData = IntPtr.Zero; } } // Create the doc window using the hiearchy & item id. return(CreateDocWindow(project, documentName, hier, itemId)); }
int IVsTrackProjectRetargetingEvents.OnRetargetingAfterChange(string projRef, IVsHierarchy pAfterChangeHier, string fromTargetFramework, string toTargetFramework) { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _errorListProvider.Tasks.Clear(); var project = VsHierarchyUtility.GetProjectFromHierarchy(pAfterChangeHier); var retargetedProject = EnvDTEProjectUtility.GetNuGetProject(project, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(retargetedProject)) { var packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(retargetedProject); if (packagesToBeReinstalled.Any()) { ShowRetargetingErrorTask(packagesToBeReinstalled.Select(p => p.Id), pAfterChangeHier, TaskErrorCategory.Error, TaskPriority.High); } ProjectRetargetingUtility.MarkPackagesForReinstallation(retargetedProject, packagesToBeReinstalled); } }); return(VSConstants.S_OK); }
private async Task EmitNuGetProjectAsync(EnvDTEProject vsProject, NuGetProject nuGetProject) { // Get the project details. var projectUniqueName = nuGetProject.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName); var projectId = Guid.Empty; try { projectId = await ThreadHelper.JoinableTaskFactory.RunAsync(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Get the project ID. var vsHierarchyItem = VsHierarchyUtility.GetHierarchyItemForProject(vsProject); Guid id; if (!vsHierarchyItem.TryGetProjectId(out id)) { id = Guid.Empty; } return(id); }); } catch (Exception ex) { var message = $"Failed to get project name or project ID. Exception:" + Environment.NewLine + ex.ToString(); ActivityLog.LogWarning(ExceptionHelper.LogEntrySource, message); Debug.Fail(message); return; } // Emit the project information. try { var projectType = NuGetProjectType.Unknown; if (nuGetProject is MSBuildNuGetProject) { projectType = NuGetProjectType.PackagesConfig; } else if (nuGetProject is BuildIntegratedNuGetProject) { projectType = NuGetProjectType.UwpProjectJson; } else if (nuGetProject is ProjectKNuGetProjectBase) { projectType = NuGetProjectType.XProjProjectJson; } var projectInformation = new ProjectInformation( NuGetVersion.Value, projectId, projectType); _nuGetTelemetryService.EmitProjectInformation(projectInformation); } catch (Exception ex) { var message = $"Failed to emit project information for project '{projectUniqueName}'. Exception:" + Environment.NewLine + ex.ToString(); ActivityLog.LogWarning(ExceptionHelper.LogEntrySource, message); Debug.Fail(message); } // Emit the project dependency statistics. try { var installedPackages = await nuGetProject.GetInstalledPackagesAsync(CancellationToken.None); var installedPackagesCount = installedPackages.Count(); var projectDependencyStatistics = new ProjectDependencyStatistics( NuGetVersion.Value, projectId, installedPackagesCount); _nuGetTelemetryService.EmitProjectDependencyStatistics(projectDependencyStatistics); } catch (Exception ex) { var message = $"Failed to emit project dependency statistics for project '{projectUniqueName}'. Exception:" + Environment.NewLine + ex.ToString(); ActivityLog.LogWarning(message, ExceptionHelper.LogEntrySource); Debug.Fail(message); } }
/// <summary> /// Internal install method. All installs from the VS API and template wizard end up here. /// </summary> internal async Task InstallInternalAsync( Project project, List <PackageIdentity> packages, ISourceRepositoryProvider repoProvider, VSAPIProjectContext projectContext, bool includePrerelease, bool ignoreDependencies, CancellationToken token) { // Go off the UI thread. This may be called from the UI thread. Only switch to the UI thread where necessary // This method installs multiple packages and can likely take more than a few secs // So, go off the UI thread explicitly to improve responsiveness await TaskScheduler.Default; var gatherCache = new GatherCache(); var sources = repoProvider.GetRepositories().ToList(); // store expanded node state var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(); try { var depBehavior = ignoreDependencies ? DependencyBehavior.Ignore : DependencyBehavior.Lowest; var packageManager = CreatePackageManager(repoProvider); // find the project var nuGetProject = await _solutionManager.GetOrCreateProjectAsync(project, projectContext); var packageManagementFormat = new PackageManagementFormat(_settings); // 1 means PackageReference var preferPackageReference = packageManagementFormat.SelectedPackageManagementFormat == 1; // Check if default package format is set to `PackageReference` and project has no // package installed yet then upgrade it to `PackageReference` based project. if (preferPackageReference && (nuGetProject is MSBuildNuGetProject) && !(await nuGetProject.GetInstalledPackagesAsync(token)).Any() && await NuGetProjectUpgradeUtility.IsNuGetProjectUpgradeableAsync(nuGetProject, project, needsAPackagesConfig: false)) { nuGetProject = await _solutionManager.UpgradeProjectToPackageReferenceAsync(nuGetProject); } // install the package foreach (var package in packages) { var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); // Check if the package is already installed if (package.Version != null && PackageServiceUtilities.IsPackageInList(installedPackageReferences, package.Id, package.Version)) { continue; } // Perform the install await InstallInternalCoreAsync( packageManager, gatherCache, nuGetProject, package, sources, projectContext, includePrerelease, ignoreDependencies, token); } } finally { // collapse nodes await VsHierarchyUtility.CollapseAllNodesAsync(expandedNodes); } }