private async Task <bool> IsPackagesConfigBasedProjectAsync() { ThreadHelper.ThrowIfNotOnUIThread(); var dteProject = EnvDTEProjectInfoUtility.GetActiveProject(VsMonitorSelection); var uniqueName = EnvDTEProjectInfoUtility.GetUniqueName(dteProject); var nuGetProject = await SolutionManager.Value.GetNuGetProjectAsync(uniqueName); if (nuGetProject == null) { return(false); } var msBuildNuGetProject = nuGetProject as MSBuildNuGetProject; if (msBuildNuGetProject == null || !msBuildNuGetProject.PackagesConfigNuGetProject.PackagesConfigExists()) { return(false); } return(true); }
public static IVsProjectBuildSystem GetVsProjectBuildSystem(EnvDTE.Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return(NuGetUIThreadHelper.JoinableTaskFactory.Run(async() => { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Get the vs solution IVsSolution solution = ServiceLocator.GetInstance <IVsSolution>(); IVsHierarchy hierarchy; var hr = solution.GetProjectOfUniqueName(EnvDTEProjectInfoUtility.GetUniqueName(project), out hierarchy); if (hr != VSConstants.S_OK) { Marshal.ThrowExceptionForHR(hr); } return hierarchy as IVsProjectBuildSystem; })); }
private async Task <IVsWindowFrame> CreateDocWindowAsync( Project project, string documentName, IVsHierarchy hier, uint itemId) { ThreadHelper.ThrowIfNotOnUIThread(); var windowFlags = (uint)_VSRDTFLAGS.RDT_DontAddToMRU | (uint)_VSRDTFLAGS.RDT_DontSaveAs; if (!await SolutionManager.Value.IsSolutionAvailableAsync()) { throw new InvalidOperationException(Resources.SolutionIsNotSaved); } var uniqueName = EnvDTEProjectInfoUtility.GetUniqueName(project); var nugetProject = await SolutionManager.Value.GetNuGetProjectAsync(uniqueName); // 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 uiController = UIFactory.Value.Create(nugetProject); var model = new PackageManagerModel( uiController, isSolution: false, editorFactoryGuid: GuidList.guidNuGetEditorType); var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory; var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4; var control = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger.Value); 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; var uiShell = await GetServiceAsync(typeof(SVsUIShell)) as IVsUIShell; var ppunkDocView = IntPtr.Zero; var ppunkDocData = IntPtr.Zero; var 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); if (windowFrame != null) { WindowFrameHelper.AddF1HelpKeyword(windowFrame, keywordValue: F1KeywordValuePmUI); } } finally { if (ppunkDocView != IntPtr.Zero) { Marshal.Release(ppunkDocData); } if (ppunkDocData != IntPtr.Zero) { Marshal.Release(ppunkDocView); } } ErrorHandler.ThrowOnFailure(hr); return(windowFrame); }
// 'parentItem' can be either a Project or ProjectItem private static async Task <EnvDTE.ProjectItem> GetOrCreateFolderAsync( EnvDTE.Project envDTEProject, object parentItem, string fullPath, string folderRelativePath, string folderName, bool createIfNotExists) { Debug.Assert(ThreadHelper.CheckAccess()); if (parentItem == null) { return(null); } EnvDTE.ProjectItem subFolder; EnvDTE.ProjectItems envDTEProjectItems = GetProjectItems(parentItem); if (TryGetFolder(envDTEProjectItems, folderName, out subFolder)) { // Get the sub folder return(subFolder); } if (createIfNotExists) { // The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that // does not belong to the project will throw. To work around that, we have to manually include // it into our project. if (EnvDTEProjectInfoUtility.IsJavaScriptProject(envDTEProject) && Directory.Exists(fullPath)) { bool succeeded = await IncludeExistingFolderToProjectAsync(envDTEProject, folderRelativePath); if (succeeded) { // IMPORTANT: after including the folder into project, we need to get // a new EnvDTEProjecItems snapshot from the parent item. Otherwise, reusing // the old snapshot from above won't have access to the added folder. envDTEProjectItems = GetProjectItems(parentItem); if (TryGetFolder(envDTEProjectItems, folderName, out subFolder)) { // Get the sub folder return(subFolder); } } return(null); } try { return(envDTEProjectItems.AddFromDirectory(fullPath)); } catch (NotImplementedException) { // This is the case for F#'s project system, we can't add from directory so we fall back // to this impl return(envDTEProjectItems.AddFolder(folderName)); } } return(null); }
private async Task <bool> IsProjectUpgradeableAsync() { return(await NuGetProjectUpgradeUtility.IsNuGetProjectUpgradeableAsync(null, EnvDTEProjectInfoUtility.GetActiveProject(VsMonitorSelection))); }
public bool TryCreateNuGetProject(EnvDTE.Project dteProject, ProjectSystemProviderContext context, out NuGetProject result) { if (dteProject == null) { throw new ArgumentNullException(nameof(dteProject)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } ThreadHelper.ThrowIfNotOnUIThread(); result = null; // The project must be an IVsHierarchy. var hierarchy = VsHierarchyUtility.ToVsHierarchy(dteProject); if (hierarchy == null) { return(false); } // Check if the project is not CPS capable or if it is CPS capable then it does not have TargetFramework(s), if so then return false if (!hierarchy.IsCapabilityMatch("CPS")) { return(false); } var buildPropertyStorage = hierarchy as IVsBuildPropertyStorage; // read MSBuild property RestoreProjectStyle, TargetFramework, and TargetFrameworks var restoreProjectStyle = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, RestoreProjectStyle); var targetFramework = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, TargetFramework); var targetFrameworks = VsHierarchyUtility.GetMSBuildProperty(buildPropertyStorage, TargetFrameworks); // check for RestoreProjectStyle property is set and if not set to PackageReference then return false if (!(string.IsNullOrEmpty(restoreProjectStyle) || restoreProjectStyle.Equals(ProjectStyle.PackageReference.ToString(), StringComparison.OrdinalIgnoreCase))) { return(false); } // check whether TargetFramework or TargetFrameworks property is set, else return false else if (string.IsNullOrEmpty(targetFramework) && string.IsNullOrEmpty(targetFrameworks)) { return(false); } // Lazy load the CPS enabled JoinableTaskFactory for the UI. NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor); var projectNames = ProjectNames.FromDTEProject(dteProject); var fullProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(dteProject); var unconfiguredProject = GetUnconfiguredProject(dteProject); result = new CpsPackageReferenceProject( dteProject.Name, EnvDTEProjectInfoUtility.GetCustomUniqueName(dteProject), fullProjectPath, _projectSystemCache, dteProject, unconfiguredProject, VsHierarchyUtility.GetProjectId(dteProject)); return(true); }
private static bool SupportsBindingRedirects(EnvDTE.Project Project) { return((Project.Kind != null && SupportedProjectTypes.IsSupportedForBindingRedirects(Project.Kind)) && !EnvDTEProjectInfoUtility.IsWindowsStoreApp(Project)); }
/// <summary> /// Get only the direct dependencies from a project /// </summary> public static async Task <IReadOnlyList <ProjectRestoreReference> > GetDirectProjectReferences( EnvDTEProject project, IEnumerable <string> resolvedProjects, ILogger log) { return(await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async() => { // DTE calls need to be done from the main thread await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var results = new List <ProjectRestoreReference>(); var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>(); // Verify ReferenceOutputAssembly var excludedProjects = GetExcludedReferences(project, itemsFactory); var hasMissingReferences = false; // find all references in the project foreach (var childReference in GetProjectReferences(project)) { try { var reference3 = childReference as Reference3; // check if deferred projects resolved this reference, which means this is still not loaded so simply continue // We'll get this reference from deferred projects later if (reference3 != null && resolvedProjects.Contains(reference3.Name, StringComparer.OrdinalIgnoreCase)) { continue; } // Set missing reference if // 1. reference is null OR // 2. reference is not resolved which means project is not loaded or assembly not found. else if (reference3 == null || !reference3.Resolved) { // Skip missing references and show a warning hasMissingReferences = true; continue; } // Skip missing references if (childReference.SourceProject != null) { if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(childReference.SourceProject)) { // Skip this shared project continue; } var childProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(childReference.SourceProject); // Skip projects which have ReferenceOutputAssembly=false if (!string.IsNullOrEmpty(childProjectPath) && !excludedProjects.Contains(childProjectPath, StringComparer.OrdinalIgnoreCase)) { var restoreReference = new ProjectRestoreReference() { ProjectPath = childProjectPath, ProjectUniqueName = childProjectPath }; results.Add(restoreReference); } } } catch (Exception ex) { // Exceptions are expected in some scenarios for native projects, // ignore them and show a warning hasMissingReferences = true; log.LogDebug(ex.ToString()); Debug.Fail("Unable to find project dependencies: " + ex.ToString()); } } if (hasMissingReferences) { // Log a generic message once per project if any items could not be resolved. // In most cases this can be ignored, but in the rare case where the unresolved // item is actually a project the restore result will be incomplete. var message = string.Format( CultureInfo.CurrentCulture, Strings.UnresolvedItemDuringProjectClosureWalk, EnvDTEProjectInfoUtility.GetUniqueName(project)); log.LogVerbose(message); } return results; })); }
private static List <string> GetExcludedReferences( EnvDTEProject project, IVsEnumHierarchyItemsFactory itemsFactory) { var excludedReferences = new List <string>(); var hierarchy = VsHierarchyUtility.ToVsHierarchy(project); // Get all items in the hierarchy, this includes project references, files, and everything else. IEnumHierarchyItems items; if (ErrorHandler.Succeeded(itemsFactory.EnumHierarchyItems( hierarchy, (uint)__VSEHI.VSEHI_Leaf, (uint)VSConstants.VSITEMID.Root, out items))) { var buildPropertyStorage = (IVsBuildPropertyStorage)hierarchy; // Loop through all items uint fetched; VSITEMSELECTION[] item = new VSITEMSELECTION[1]; while (ErrorHandler.Succeeded(items.Next(1, item, out fetched)) && fetched == 1) { // Check if the item has ReferenceOutputAssembly. This will // return null for the vast majority of items. string value; if (ErrorHandler.Succeeded(buildPropertyStorage.GetItemAttribute( item[0].itemid, "ReferenceOutputAssembly", out value)) && value != null) { // We only need to go farther if the flag exists and is not true if (!string.Equals(value, bool.TrueString, StringComparison.OrdinalIgnoreCase)) { // Get the DTE Project reference for the item id. This checks for nulls incase this is // somehow not a project reference that had the ReferenceOutputAssembly flag. object childObject; if (ErrorHandler.Succeeded(hierarchy.GetProperty( item[0].itemid, (int)__VSHPROPID.VSHPROPID_ExtObject, out childObject))) { // 1. Verify that this is a project reference // 2. Check that it is valid and resolved // 3. Follow the reference to the DTE project and get the unique name var reference = childObject as Reference3; if (reference != null && reference.Resolved && reference.SourceProject != null) { var childPath = EnvDTEProjectInfoUtility .GetFullProjectPath(reference.SourceProject); excludedReferences.Add(childPath); } } } } } } return(excludedReferences); }
public async Task <IEnumerable <ProjectRestoreReference> > GetProjectReferencesAsync( Common.ILogger logger, CancellationToken _) { // DTE calls need to be done from the main thread await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync(); var results = new List <ProjectRestoreReference>(); var itemsFactory = ServiceLocator.GetInstance <IVsEnumHierarchyItemsFactory>(); // Verify ReferenceOutputAssembly var excludedProjects = GetExcludedReferences(itemsFactory, logger); var hasMissingReferences = false; // find all references in the project foreach (var childReference in GetVSProjectReferences()) { try { var reference3 = childReference as Reference3; // Verify that this is a project reference if (IsProjectReference(reference3, logger)) { // Verify that this is a valid and resolved project reference if (!IsReferenceResolved(reference3, logger)) { hasMissingReferences = true; continue; } if (EnvDTEProjectUtility.HasUnsupportedProjectCapability(reference3.SourceProject)) { // Skip this shared project continue; } var childProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(reference3.SourceProject); // Skip projects which have ReferenceOutputAssembly=false if (!string.IsNullOrEmpty(childProjectPath) && !excludedProjects.Contains(childProjectPath, StringComparer.OrdinalIgnoreCase)) { var restoreReference = new ProjectRestoreReference() { ProjectPath = childProjectPath, ProjectUniqueName = childProjectPath }; results.Add(restoreReference); } } else { hasMissingReferences = true; } } catch (Exception ex) { // Exceptions are expected in some scenarios for native projects, // ignore them and show a warning hasMissingReferences = true; logger.LogDebug(ex.ToString()); Debug.Fail("Unable to find project dependencies: " + ex.ToString()); } } if (hasMissingReferences) { // Log a generic message once per project if any items could not be resolved. // In most cases this can be ignored, but in the rare case where the unresolved // item is actually a project the restore result will be incomplete. var message = string.Format( CultureInfo.CurrentCulture, Strings.UnresolvedItemDuringProjectClosureWalk, _vsProjectAdapter.UniqueName); logger.LogVerbose(message); } return(results); }
public static async Task <bool> IsNuGetProjectUpgradeableAsync(NuGetProject nuGetProject, Project envDTEProject = null) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); 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); } } // check if current project is packages.config based or not var msBuildNuGetProject = nuGetProject as MSBuildNuGetProject; if (msBuildNuGetProject == null || !msBuildNuGetProject.PackagesConfigNuGetProject.PackagesConfigExists()) { return(false); } // this further check if current project system supports VSProject4 or not which is essential to skip // projects like c++ which currently doesn't support VSProject4 implementation for PackageReference if (!msBuildNuGetProject.ProjectServices.Capabilities.SupportsPackageReferences) { 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))); }
public bool TryCreateNuGetProject(EnvDTE.Project envDTEProject, ProjectSystemProviderContext context, out NuGetProject result) { if (envDTEProject == null) { throw new ArgumentNullException(nameof(envDTEProject)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } ThreadHelper.ThrowIfNotOnUIThread(); result = null; var msBuildNuGetProjectSystem = MSBuildNuGetProjectSystemFactory.CreateMSBuildNuGetProjectSystem( envDTEProject, context.ProjectContext); var isWebSite = msBuildNuGetProjectSystem is WebSiteProjectSystem; // Web sites cannot have project.json if (!isWebSite) { // Find the project file path var projectFilePath = EnvDTEProjectInfoUtility.GetFullProjectPath(envDTEProject); if (!string.IsNullOrEmpty(projectFilePath)) { var msbuildProjectFile = new FileInfo(projectFilePath); var projectNameFromMSBuildPath = Path.GetFileNameWithoutExtension(msbuildProjectFile.Name); // Treat projects with project.json as build integrated projects // Search for projectName.project.json first, then project.json // If the name cannot be determined, search only for project.json string projectJsonPath = null; if (string.IsNullOrEmpty(projectNameFromMSBuildPath)) { projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName, ProjectJsonPathUtilities.ProjectConfigFileName); } else { projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(msbuildProjectFile.DirectoryName, projectNameFromMSBuildPath); } if (File.Exists(projectJsonPath)) { result = new ProjectJsonBuildIntegratedProjectSystem( projectJsonPath, msbuildProjectFile.FullName, envDTEProject, EnvDTEProjectInfoUtility.GetCustomUniqueName(envDTEProject)); } } } // Create a normal MSBuild project if no project.json was found if (result == null) { var folderNuGetProjectFullPath = context.PackagesPathFactory(); // Project folder path is the packages config folder path var packagesConfigFolderPath = EnvDTEProjectInfoUtility.GetFullPath(envDTEProject); result = new VSMSBuildNuGetProject( envDTEProject, msBuildNuGetProjectSystem, folderNuGetProjectFullPath, packagesConfigFolderPath); } return(result != null); }
/// <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(EnvDTEProjectInfoUtility.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(EnvDTEProjectInfoUtility.GetCustomUniqueName(p), customUniqueName)).FirstOrDefault(); } return(defaultDTEProject); }
/// <summary> /// Determines if NuGet is used in the project. Currently, it is determined by checking if packages.config is part of the project /// </summary> /// <param name="project">The project which is checked to see if NuGet is used in it</param> public static bool IsNuGetInUse(Project project) { return(EnvDTEProjectUtility.IsSupported(project) && File.Exists(EnvDTEProjectInfoUtility.GetPackagesConfigFullPath(project))); }