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); } } } }
int IVsTrackBatchRetargetingEvents.OnBatchRetargetingBegin() { NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var project = EnvDTEProjectUtility.GetActiveProject(_vsMonitorSelection); if (project != null) { _platformRetargetingProject = null; var frameworkName = EnvDTEProjectUtility.GetTargetFrameworkString(project); if (NETCore45.Equals(frameworkName, StringComparison.OrdinalIgnoreCase) || Windows80.Equals(frameworkName, StringComparison.OrdinalIgnoreCase)) { _platformRetargetingProject = project.UniqueName; } } }); return(VSConstants.S_OK); }
/// <summary> /// Finds the NuGetProject from a DTE project /// </summary> public static NuGetProject GetProject(ISolutionManager solutionManager, Project project, VSAPIProjectContext projectContext = null) { if (solutionManager == null) { throw new ArgumentNullException("solution"); } var projectSafeName = EnvDTEProjectUtility.GetCustomUniqueName(project); NuGetProject nuGetProject = solutionManager.GetNuGetProject(projectSafeName); var settings = ServiceLocator.GetInstance <ISettings>(); // if the project does not exist in the solution (this is true for new templates) create it manually if (nuGetProject == null) { VSNuGetProjectFactory factory = new VSNuGetProjectFactory(() => PackagesFolderPathUtility.GetPackagesFolderPath(solutionManager, settings)); nuGetProject = factory.CreateNuGetProject(project, projectContext); } return(nuGetProject); }
public static bool IsFileExistsInProject(string projectUniqueName, string filePath) { return(ThreadHelper.JoinableTaskFactory.Run( async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var dte = ServiceLocator.GetDTE(); foreach (EnvDTE.Project project in dte.Solution.Projects) { var solutionProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(project); if (!string.IsNullOrEmpty(solutionProjectPath) && PathUtility.GetStringComparerBasedOnOS().Equals(solutionProjectPath, projectUniqueName)) { return await EnvDTEProjectUtility.ContainsFile(project, filePath); } } return false; })); }
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<IVsWindowFrame> CreateDocWindowAsync( Project project, string documentName, IVsHierarchy hier, uint itemId) { uint windowFlags = (uint)_VSRDTFLAGS.RDT_DontAddToMRU | (uint)_VSRDTFLAGS.RDT_DontSaveAs; var solutionManager = ServiceLocator.GetInstance<ISolutionManager>(); if (!solutionManager.IsSolutionAvailable) { throw new InvalidOperationException(Strings.SolutionIsNotSaved); } var nugetProject = solutionManager.GetNuGetProject(EnvDTEProjectUtility.GetCustomUniqueName(project)); // If we failed to generate a cache entry in the solution manager something went wrong. if (nugetProject == null) { throw new InvalidOperationException( string.Format(Resources.ProjectHasAnInvalidNuGetConfiguration, project.Name)); } // load packages.config. This makes sure that an exception will get thrown if there // are problems with packages.config, such as duplicate packages. When an exception // is thrown, an error dialog will pop up and this doc window will not be created. var installedPackages = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None); var uiContextFactory = ServiceLocator.GetInstance<INuGetUIContextFactory>(); var uiContext = uiContextFactory.Create(this, new[] { nugetProject }); var uiFactory = ServiceLocator.GetInstance<INuGetUIFactory>(); var uiController = uiFactory.Create(uiContext, _uiProjectContext); var model = new PackageManagerModel(uiController, uiContext, isSolution: false, editorFactoryGuid: GuidList.guidNuGetEditorType); var vsWindowSearchHostfactory = ServiceLocator.GetGlobalService<SVsWindowSearchHostFactory, IVsWindowSearchHostFactory>(); var vsShell = ServiceLocator.GetGlobalService<SVsShell, IVsShell4>(); var control = new PackageManagerControl(model, Settings, vsWindowSearchHostfactory, vsShell, _outputConsoleLogger); var windowPane = new PackageManagerWindowPane(control); var guidEditorType = GuidList.guidNuGetEditorType; var guidCommandUI = Guid.Empty; var caption = String.Format( CultureInfo.CurrentCulture, Resx.Label_NuGetWindowCaption, project.Name); IVsWindowFrame windowFrame; IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); IntPtr ppunkDocView = IntPtr.Zero; IntPtr ppunkDocData = IntPtr.Zero; int hr = 0; try { ppunkDocView = Marshal.GetIUnknownForObject(windowPane); ppunkDocData = Marshal.GetIUnknownForObject(model); hr = uiShell.CreateDocumentWindow( windowFlags, documentName, (IVsUIHierarchy)hier, itemId, ppunkDocView, ppunkDocData, ref guidEditorType, null, ref guidCommandUI, null, caption, string.Empty, null, out windowFrame); } finally { if (ppunkDocView != IntPtr.Zero) { Marshal.Release(ppunkDocData); } if (ppunkDocData != IntPtr.Zero) { Marshal.Release(ppunkDocView); } } ErrorHandler.ThrowOnFailure(hr); return windowFrame; }
public void InstallPackagesFromRegistryRepository(string keyName, bool isPreUnzipped, bool skipAssemblyReferences, bool ignoreDependencies, Project project, IDictionary <string, string> packageVersions) { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(keyName)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (packageVersions == null || !packageVersions.Any()) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(packageVersions)); } try { RunJTFWithCorrectContext(project, async() => { // HACK !!! : This is a hack for PCL projects which send isPreUnzipped = true, but their package source // (located at C:\Program Files (x86)\Microsoft SDKs\NuGetPackages) follows the V3 // folder version format. if (isPreUnzipped) { var isProjectJsonProject = await EnvDTEProjectUtility.HasBuildIntegratedConfig(project); isPreUnzipped = isProjectJsonProject ? false : isPreUnzipped; } // create a repository provider with only the registry repository var repoProvider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider); repoProvider.AddFromRegistry(keyName, isPreUnzipped); var toInstall = GetIdentitiesFromDict(packageVersions); // Skip assembly references and disable binding redirections should be done together var disableBindingRedirects = skipAssemblyReferences; var projectContext = new VSAPIProjectContext(skipAssemblyReferences, disableBindingRedirects) { PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(_settings, NullLogger.Instance), NullLogger.Instance) }; await InstallInternalAsync( project, toInstall, repoProvider, projectContext, includePrerelease: false, ignoreDependencies: ignoreDependencies, token: CancellationToken.None); }); } catch (Exception exception) { _telemetryProvider.PostFault(exception, typeof(VsPackageInstaller).FullName); throw; } }
/// <summary> /// Return all projects in the solution matching the provided names. Wildcards are supported. /// This method will automatically generate error records for non-wildcarded project names that /// are not found. /// </summary> /// <param name="projectNames">An array of project names that may or may not include wildcards.</param> /// <returns>Projects matching the project name(s) provided.</returns> protected IEnumerable <Project> GetProjectsByName(string[] projectNames) { var allValidProjectNames = GetAllValidProjectNames().ToList(); var allDteProjects = EnvDTESolutionUtility.GetAllEnvDTEProjects(DTE); foreach (string projectName in projectNames) { // if ctrl+c hit, leave immediately if (Stopping) { break; } // Treat every name as a wildcard; results in simpler code var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase); var matches = from s in allValidProjectNames where pattern.IsMatch(s) select VsSolutionManager.GetNuGetProject(s); int count = 0; foreach (var project in matches) { if (project != null) { count++; string name = project.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName); Project dteProject = allDteProjects .Where(p => StringComparer.OrdinalIgnoreCase.Equals(EnvDTEProjectUtility.GetCustomUniqueName(p), name)) .FirstOrDefault(); yield return(dteProject); } } // We only emit non-terminating error record if a non-wildcarded name was not found. // This is consistent with built-in cmdlets that support wildcarded search. // A search with a wildcard that returns nothing should not be considered an error. if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName)) { ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false); } } }
/// <summary> /// Get default project in the type of EnvDTE.Project, to keep PowerShell scripts backward-compatbility. /// </summary> /// <returns></returns> protected Project GetDefaultProject() { string customUniqueName = string.Empty; Project defaultDTEProject = null; NuGetProject defaultNuGetProject = VsSolutionManager.DefaultNuGetProject; // Solution may be open without a project in it. Then defaultNuGetProject is null. if (defaultNuGetProject != null) { customUniqueName = defaultNuGetProject.GetMetadata <string>(NuGetProjectMetadataKeys.UniqueName); } // Get all DTE projects in the solution and compare by CustomUnique names, especially for projects under solution folders. IEnumerable <Project> allDTEProjects = EnvDTESolutionUtility.GetAllEnvDTEProjects(DTE); if (allDTEProjects != null) { defaultDTEProject = allDTEProjects.Where(p => StringComparer.OrdinalIgnoreCase.Equals(EnvDTEProjectUtility.GetCustomUniqueName(p), customUniqueName)).FirstOrDefault(); } return(defaultDTEProject); }
/// <summary> /// Installs one or more packages into the specified project. /// </summary> /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param> /// <param name="project">The target project for installation.</param> /// <param name="configuration"> /// The packages to install, where to install them from, and additional options for /// their installation. /// </param> /// <param name="repositorySettings">The repository settings for the packages being installed.</param> /// <param name="warningHandler"> /// An action that accepts a warning message and presents it to the user, allowing /// execution to continue. /// </param> /// <param name="errorHandler"> /// An action that accepts an error message and presents it to the user, allowing /// execution to continue. /// </param> internal async Task PerformPackageInstallAsync( IVsPackageInstaller packageInstaller, Project project, PreinstalledPackageConfiguration configuration, Action <string> warningHandler, Action <string> errorHandler) { ThreadHelper.ThrowIfNotOnUIThread(); string repositoryPath = configuration.RepositoryPath; var repositorySource = new Configuration.PackageSource(repositoryPath); var failedPackageErrors = new List <string>(); // find the project var defaultProjectContext = new VSAPIProjectContext(); var nuGetProject = await PackageManagementHelpers.GetProjectAsync(_solutionManager, project, defaultProjectContext); // For BuildIntegratedNuGetProject, nuget will ignore preunzipped configuration. var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject; var repository = (buildIntegratedProject == null && configuration.IsPreunzipped) ? _sourceProvider.CreateRepository(repositorySource, FeedType.FileSystemUnzipped) : _sourceProvider.CreateRepository(repositorySource); var repoProvider = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider); repoProvider.AddFromSource(repository); var packageManager = _installer.CreatePackageManager(repoProvider); var gatherCache = new GatherCache(); var sources = repoProvider.GetRepositories().ToList(); // store expanded node state var expandedNodes = await VsHierarchyUtility.GetAllExpandedNodesAsync(_solutionManager); try { foreach (var package in configuration.Packages) { var packageIdentity = new PackageIdentity(package.Id, package.Version); // Does the project already have this package installed? if (_packageServices.IsPackageInstalled(project, package.Id)) { // If so, is it the right version? if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString())) { // No? Raise a warning (likely written to the Output window) and ignore this package. warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version)); } // Yes? Just silently ignore this package! } else { try { if (InfoHandler != null) { InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version)); } // Skip assembly references and disable binding redirections should be done together bool disableBindingRedirects = package.SkipAssemblyReferences; var projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects); // Old templates have hardcoded non-normalized paths projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true; // This runs from the UI thread await _installer.InstallInternalCoreAsync( packageManager, gatherCache, nuGetProject, packageIdentity, sources, projectContext, includePrerelease : false, ignoreDependencies : package.IgnoreDependencies, token : CancellationToken.None); } catch (InvalidOperationException exception) { failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message); } catch (AggregateException aggregateEx) { var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault(); if (ex is InvalidOperationException) { failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message); } else { throw; } } } } if (failedPackageErrors.Any()) { var errorString = new StringBuilder(); errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath); errorString.AppendLine(); errorString.AppendLine(); errorString.Append(String.Join(Environment.NewLine, failedPackageErrors)); errorHandler(errorString.ToString()); } // RepositorySettings = null in unit tests if (EnvDTEProjectUtility.IsWebSite(project)) { CreateRefreshFilesInBin( project, repositoryPath, configuration.Packages.Where(p => p.SkipAssemblyReferences)); CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages); } } finally { // collapse nodes await VsHierarchyUtility.CollapseAllNodesAsync(_solutionManager, expandedNodes); } }
public static string GetCustomUniqueName(PSObject psObject) { return(EnvDTEProjectUtility.GetCustomUniqueName((EnvDTE.Project)psObject.BaseObject)); }
/// <summary> /// Installs one or more packages into the specified project. /// </summary> /// <param name="packageInstaller">The package installer service that performs the actual package installation.</param> /// <param name="project">The target project for installation.</param> /// <param name="configuration">The packages to install, where to install them from, and additional options for their installation.</param> /// <param name="repositorySettings">The repository settings for the packages being installed.</param> /// <param name="warningHandler">An action that accepts a warning message and presents it to the user, allowing execution to continue.</param> /// <param name="errorHandler">An action that accepts an error message and presents it to the user, allowing execution to continue.</param> internal void PerformPackageInstall( IVsPackageInstaller packageInstaller, Project project, PreinstalledPackageConfiguration configuration, Action <string> warningHandler, Action <string> errorHandler) { string repositoryPath = configuration.RepositoryPath; var failedPackageErrors = new List <string>(); LegacyNuGet.IPackageRepository repository = configuration.IsPreunzipped ? (LegacyNuGet.IPackageRepository) new LegacyNuGet.UnzippedPackageRepository(repositoryPath) : (LegacyNuGet.IPackageRepository) new LegacyNuGet.LocalPackageRepository(repositoryPath); PreinstalledRepositoryProvider repos = new PreinstalledRepositoryProvider(errorHandler, _sourceProvider); repos.AddFromRepository(repository); // store expanded node state IDictionary <string, ISet <VsHierarchyItem> > expandedNodes = VsHierarchyHelper.GetAllExpandedNodes(_solutionManager); foreach (var package in configuration.Packages) { // Does the project already have this package installed? if (_packageServices.IsPackageInstalled(project, package.Id)) { // If so, is it the right version? if (!_packageServices.IsPackageInstalledEx(project, package.Id, package.Version.ToNormalizedString())) { // No? Raise a warning (likely written to the Output window) and ignore this package. warningHandler(String.Format(VsResources.PreinstalledPackages_VersionConflict, package.Id, package.Version)); } // Yes? Just silently ignore this package! } else { try { if (InfoHandler != null) { InfoHandler(String.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_PackageInstallStatus, package.Id, package.Version)); } List <PackageIdentity> toInstall = new List <PackageIdentity>(); toInstall.Add(new PackageIdentity(package.Id, package.Version)); // Skip assembly references and disable binding redirections should be done together bool disableBindingRedirects = package.SkipAssemblyReferences; VSAPIProjectContext projectContext = new VSAPIProjectContext(package.SkipAssemblyReferences, disableBindingRedirects); // Old templates have hardcoded non-normalized paths projectContext.PackageExtractionContext.UseLegacyPackageInstallPath = true; // This runs from the UI thread PackageManagementHelpers.RunSync(async() => await _installer.InstallInternal(project, toInstall, repos, projectContext, package.IgnoreDependencies, CancellationToken.None)); } catch (InvalidOperationException exception) { failedPackageErrors.Add(package.Id + "." + package.Version + " : " + exception.Message); } catch (AggregateException aggregateEx) { var ex = aggregateEx.Flatten().InnerExceptions.FirstOrDefault(); if (ex is InvalidOperationException) { failedPackageErrors.Add(package.Id + "." + package.Version + " : " + ex.Message); } else { throw; } } } } if (failedPackageErrors.Any()) { var errorString = new StringBuilder(); errorString.AppendFormat(VsResources.PreinstalledPackages_FailedToInstallPackage, repositoryPath); errorString.AppendLine(); errorString.AppendLine(); errorString.Append(String.Join(Environment.NewLine, failedPackageErrors)); errorHandler(errorString.ToString()); } // RepositorySettings = null in unit tests if (EnvDTEProjectUtility.IsWebSite(project)) { CreateRefreshFilesInBin( project, repositoryPath, configuration.Packages.Where(p => p.SkipAssemblyReferences)); CopyNativeBinariesToBin(project, repositoryPath, configuration.Packages); } // collapse nodes VsHierarchyHelper.CollapseAllNodes(_solutionManager, expandedNodes); }