Beispiel #1
0
        public async Task <IVsProjectAdapter> CreateAdapterForFullyLoadedProjectAsync(EnvDTE.Project dteProject)
        {
            Assumes.Present(dteProject);

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var vsHierarchyItem = VsHierarchyItem.FromDteProject(dteProject);
            Func <IVsHierarchy, EnvDTE.Project> loadDteProject = _ => dteProject;

            var buildStorageProperty = vsHierarchyItem.VsHierarchy as IVsBuildPropertyStorage;
            var vsBuildProperties    = new VsProjectBuildProperties(
                dteProject, buildStorageProperty, _threadingService);

            var projectNames = await ProjectNames.FromDTEProjectAsync(dteProject);

            var fullProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(dteProject);

            return(new VsProjectAdapter(
                       vsHierarchyItem,
                       projectNames,
                       fullProjectPath,
                       dteProject.Kind,
                       loadDteProject,
                       vsBuildProperties,
                       _threadingService));
        }
Beispiel #2
0
        public async Task <IVsProjectAdapter> CreateAdapterForFullyLoadedProjectAsync(EnvDTE.Project dteProject)
        {
            Assumes.Present(dteProject);

            _threadingService.ThrowIfNotOnUIThread();

            var vsHierarchyItem = VsHierarchyItem.FromDteProject(dteProject);
            Func <IVsHierarchy, EnvDTE.Project> loadDteProject = _ => dteProject;

            IProjectBuildProperties vsBuildProperties;

            if (vsHierarchyItem.VsHierarchy is IVsBuildPropertyStorage)
            {
                vsBuildProperties = new VsManagedLanguagesProjectBuildProperties(
                    vsHierarchyItem.VsHierarchy as IVsBuildPropertyStorage, _threadingService);
            }
            else
            {
                vsBuildProperties = new VsCoreProjectBuildProperties(dteProject, _threadingService);
            }

            var projectNames = await ProjectNames.FromDTEProjectAsync(dteProject);

            var fullProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(dteProject);

            return(new VsProjectAdapter(
                       vsHierarchyItem,
                       projectNames,
                       fullProjectPath,
                       dteProject.Kind,
                       loadDteProject,
                       vsBuildProperties,
                       _threadingService));
        }
        public async Task <IVsProjectAdapter> CreateAdapterForFullyLoadedProjectAsync(EnvDTE.Project dteProject)
        {
            Assumes.Present(dteProject);

            // Get services while we might be on background thread
            var vsSolution5 = await _vsSolution5.GetValueAsync();

            // switch to main thread and use services we know must be done on main thread.
            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var vsHierarchyItem = VsHierarchyItem.FromDteProject(dteProject);
            Func <IVsHierarchy, EnvDTE.Project> loadDteProject = _ => dteProject;

            var buildStorageProperty = vsHierarchyItem.VsHierarchy as IVsBuildPropertyStorage;
            var vsBuildProperties    = new VsProjectBuildProperties(
                dteProject, buildStorageProperty, _threadingService);

            var projectNames = await ProjectNames.FromDTEProjectAsync(dteProject, vsSolution5);

            var fullProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(dteProject);

            return(new VsProjectAdapter(
                       vsHierarchyItem,
                       projectNames,
                       fullProjectPath,
                       dteProject.Kind,
                       loadDteProject,
                       vsBuildProperties,
                       _threadingService));
        }
        public static Task <Dictionary <string, EnvDTE.Project> > GetPathToDTEProjectLookupAsync(EnvDTE.DTE dte)
        {
            var pathToProject = new Dictionary <string, EnvDTE.Project>(StringComparer.OrdinalIgnoreCase);

            var supportedProjects = dte.Solution.Projects.Cast <EnvDTE.Project>();

            foreach (var solutionProject in supportedProjects)
            {
                var solutionProjectPath = EnvDTEProjectInfoUtility.GetFullProjectPath(solutionProject);

                if (!string.IsNullOrEmpty(solutionProjectPath) &&
                    !pathToProject.ContainsKey(solutionProjectPath))
                {
                    pathToProject.Add(solutionProjectPath, solutionProject);
                }
            }

            return(Task.FromResult(pathToProject));
        }
        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;
            }));
        }
        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);
        }
        /// <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);
        }
Beispiel #9
0
        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);
        }
Beispiel #10
0
        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);
        }