Exemple #1
0
        int IVsSolutionEventsProjectUpgrade.OnAfterUpgradeProject(IVsHierarchy pHierarchy, uint fUpgradeFlag, string bstrCopyLocation, SYSTEMTIME stUpgradeTime, IVsUpgradeLogger pLogger)
        {
            NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                Debug.Assert(pHierarchy != null);

                var upgradedProject      = VsHierarchyUtility.GetProjectFromHierarchy(pHierarchy);
                var upgradedNuGetProject = await EnvDTEProjectUtility.GetNuGetProjectAsync(upgradedProject, _solutionManager);

                if (ProjectRetargetingUtility.IsProjectRetargetable(upgradedNuGetProject))
                {
                    var packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(upgradedNuGetProject);

                    if (packagesToBeReinstalled.Any())
                    {
                        pLogger.LogMessage((int)__VSUL_ERRORLEVEL.VSUL_ERROR, upgradedProject.Name, upgradedProject.Name,
                                           string.Format(CultureInfo.CurrentCulture, Strings.ProjectUpgradeAndRetargetErrorMessage, string.Join(", ", packagesToBeReinstalled.Select(p => p.Id))));
                    }
                }
            });

            return(VSConstants.S_OK);
        }
Exemple #2
0
        private static async Task <bool> IsProjectCapabilityCompliantAsync(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(envDTEProject != null);
            var hierarchy = await envDTEProject.ToVsHierarchyAsync();

            return(await VsHierarchyUtility.IsProjectCapabilityCompliantAsync(hierarchy));
        }
Exemple #3
0
        public static void DoWorkInWriterLock(EnvDTEProject project, Action <MicrosoftBuildEvaluationProject> action)
        {
            IVsBrowseObjectContext context = project.Object as IVsBrowseObjectContext;

            if (context == null)
            {
                IVsHierarchy hierarchy = VsHierarchyUtility.ToVsHierarchy(project);
                context = hierarchy as IVsBrowseObjectContext;
            }

            if (context != null)
            {
                var service = context.UnconfiguredProject.ProjectService.Services.DirectAccessService;
                if (service != null)
                {
                    // This has to run on Main thread, otherwise it will dead-lock (for C++ projects at least)
                    ThreadHelper.Generic.Invoke(() =>
                                                service.Write(
                                                    context.UnconfiguredProject.FullPath,
                                                    dwa =>
                    {
                        MicrosoftBuildEvaluationProject buildProject = dwa.GetProject(context.UnconfiguredProject.Services.SuggestedConfiguredProject);
                        action(buildProject);
                    },
                                                    ProjectAccess.Read | ProjectAccess.Write)
                                                );
                }
            }
        }
        public ProjectJsonBuildIntegratedProjectSystem(
            string jsonConfigPath,
            string msbuildProjectFilePath,
            EnvDTEProject envDTEProject,
            string uniqueName)
            : base(jsonConfigPath, msbuildProjectFilePath)
        {
            _envDTEProject = envDTEProject;

            // set project id
            var projectId = VsHierarchyUtility.GetProjectId(envDTEProject);

            InternalMetadata.Add(NuGetProjectMetadataKeys.ProjectId, projectId);

            // Override the JSON TFM value from the csproj for UAP framework
            if (InternalMetadata.TryGetValue(NuGetProjectMetadataKeys.TargetFramework, out object targetFramework))
            {
                var jsonTargetFramework = targetFramework as NuGetFramework;
                if (IsUAPFramework(jsonTargetFramework))
                {
                    var platfromMinVersion = VsHierarchyUtility.GetMSBuildProperty(VsHierarchyUtility.ToVsHierarchy(envDTEProject), EnvDTEProjectInfoUtility.TargetPlatformMinVersion);

                    if (!string.IsNullOrEmpty(platfromMinVersion))
                    {
                        // Found the TPMinV in csproj, store this as a new target framework to be replaced in project.json
                        var newTargetFramework = new NuGetFramework(jsonTargetFramework.Framework, new Version(platfromMinVersion));
                        InternalMetadata[NuGetProjectMetadataKeys.TargetFramework] = newTargetFramework;
                    }
                }
            }

            InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, uniqueName);
        }
Exemple #5
0
        public async Task <IVsProjectAdapter> CreateAdapterForFullyLoadedProjectAsync(IVsHierarchy hierarchy)
        {
            Assumes.Present(hierarchy);

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

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

            var vsHierarchyItem = VsHierarchyItem.FromVsHierarchy(hierarchy);
            Func <IVsHierarchy, EnvDTE.Project> loadDteProject = hierarchy => VsHierarchyUtility.GetProjectFromHierarchy(hierarchy);

            var buildStorageProperty = vsHierarchyItem.VsHierarchy as IVsBuildPropertyStorage;
            var vsBuildProperties    = new VsProjectBuildProperties(
                new Lazy <EnvDTE.Project>(() => loadDteProject(hierarchy)), buildStorageProperty, _threadingService);

            var fullProjectPath = VsHierarchyUtility.GetProjectPath(hierarchy);
            var projectNames    = await ProjectNames.FromIVsSolution2(fullProjectPath, (IVsSolution2)vsSolution, hierarchy, CancellationToken.None);

            return(new VsProjectAdapter(
                       vsHierarchyItem,
                       projectNames,
                       fullProjectPath,
                       loadDteProject,
                       vsBuildProperties,
                       _threadingService));
        }
Exemple #6
0
        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 = await EnvDTEProjectUtility.GetNuGetProjectAsync(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);
                    }
                    // NuGet/Home#4833 Baseline
                    // Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
#pragma warning disable CS4014
                    ProjectRetargetingUtility.MarkPackagesForReinstallation(retargetedProject, packagesToBeReinstalled);
#pragma warning restore CS4014
                }
            });

            if (retargetedProject is LegacyPackageReferenceProject)
            {
                // 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));
            }
            return(VSConstants.S_OK);
        }
        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;

            var project = new EnvDTEProjectAdapter(dteProject);

            if (!project.IsLegacyCSProjPackageReferenceProject)
            {
                return(false);
            }

            // Lazy load the CPS enabled JoinableTaskFactory for the UI.
            NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as ProjectSystem.IProjectServiceAccessor);

            result = new LegacyCSProjPackageReferenceProject(
                project,
                VsHierarchyUtility.GetProjectId(dteProject));

            return(true);
        }
        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;

            var projectK = GetProjectKProject(dteProject);

            if (projectK == null)
            {
                return(false);
            }

            result = new ProjectKNuGetProject(
                projectK,
                dteProject.Name,
                EnvDTEProjectInfoUtility.GetCustomUniqueName(dteProject),
                VsHierarchyUtility.GetProjectId(dteProject));

            return(true);
        }
Exemple #9
0
        public async Task <IVsProjectAdapter> CreateAdapterForDeferredProjectAsync(IVsHierarchy project)
        {
            Assumes.Present(project);

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var vsHierarchyItem = VsHierarchyItem.FromVsHierarchy(project);
            var fullProjectPath = VsHierarchyUtility.GetProjectPath(project);

            var uniqueName = string.Empty;

            _vsSolution.Value.GetUniqueNameOfProject(project, out uniqueName);

            var projectNames = new ProjectNames(
                fullName: fullProjectPath,
                uniqueName: uniqueName,
                shortName: Path.GetFileNameWithoutExtension(fullProjectPath),
                customUniqueName: GetCustomUniqueName(uniqueName));

            var workspaceBuildProperties = new WorkspaceProjectBuildProperties(
                fullProjectPath, _workspaceService.Value, _threadingService);

            var projectTypeGuid = await _workspaceService.Value.GetProjectTypeGuidAsync(fullProjectPath);

            return(new VsProjectAdapter(
                       vsHierarchyItem,
                       projectNames,
                       fullProjectPath,
                       projectTypeGuid,
                       EnsureProjectIsLoaded,
                       workspaceBuildProperties,
                       _threadingService,
                       _workspaceService.Value));
        }
Exemple #10
0
 public static bool ContainsFile(EnvDTEProject envDTEProject, string path)
 {
     if (string.Equals(envDTEProject.Kind, NuGetVSConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
         string.Equals(envDTEProject.Kind, NuGetVSConstants.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
         string.Equals(envDTEProject.Kind, NuGetVSConstants.FsharpProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
         string.Equals(envDTEProject.Kind, NuGetVSConstants.JsProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
     {
         // For Wix and Nemerle projects, IsDocumentInProject() returns not found
         // even though the file is in the project. So we use GetProjectItem()
         // instead. Nemerle is a high-level statically typed programming language for .NET platform
         // Note that pszMkDocument, the document moniker, passed to IsDocumentInProject(), must be a path to the file
         // for certain file-based project systems such as F#. And, not just a filename. For these project systems as well,
         // do the following
         EnvDTEProjectItem item = GetProjectItem(envDTEProject, path);
         return(item != null);
     }
     else
     {
         IVsProject vsProject = (IVsProject)VsHierarchyUtility.ToVsHierarchy(envDTEProject);
         if (vsProject == null)
         {
             return(false);
         }
         int  pFound;
         uint itemId;
         int  hr = vsProject.IsDocumentInProject(path, out pFound, new VSDOCUMENTPRIORITY[0], out itemId);
         return(ErrorHandler.Succeeded(hr) && pFound == 1);
     }
 }
Exemple #11
0
        private static async Task <bool> IncludeExistingFolderToProjectAsync(EnvDTE.Project envDTEProject, string folderRelativePath)
        {
            // Execute command to include the existing folder into project. Must do this on UI thread.
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsUIHierarchy projectHierarchy = (IVsUIHierarchy)VsHierarchyUtility.ToVsHierarchy(envDTEProject);

            uint itemId;
            int  hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out itemId);

            if (!ErrorHandler.Succeeded(hr))
            {
                return(false);
            }

            hr = projectHierarchy.ExecCommand(
                itemId,
                ref VsMenus.guidStandardCommandSet2K,
                (int)VSConstants.VSStd2KCmdID.INCLUDEINPROJECT,
                0,
                IntPtr.Zero,
                IntPtr.Zero);

            return(ErrorHandler.Succeeded(hr));
        }
Exemple #12
0
        /// <summary>
        /// This method should be on the UI thread. The overrides should ensure that
        /// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out
        /// of date.
        /// The value does not matter, it just needs to change.
        /// </summary>
        protected static void UpdateImportStamp(EnvDTEProject envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            IVsBuildPropertyStorage propStore = VsHierarchyUtility.ToVsHierarchy(envDTEProject) as IVsBuildPropertyStorage;

            if (propStore != null)
            {
                // <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
                string stamp = Guid.NewGuid().ToString().Split('-')[0];
                try
                {
                    propStore.SetPropertyValue(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp);
                }
                catch (Exception ex1)
                {
                    ExceptionHelper.WriteToActivityLog(ex1);
                }

                // Remove the NuGetImportStamp so that VC++ project file won't be updated with this stamp on disk,
                // which causes unnecessary source control pending changes.
                try
                {
                    propStore.RemoveProperty(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE);
                }
                catch (Exception ex2)
                {
                    ExceptionHelper.WriteToActivityLog(ex2);
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Check if the project has an unsupported project capability, such as, "SharedAssetsProject"
        /// </summary>
        public static bool HasUnsupportedProjectCapability(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            var hier = VsHierarchyUtility.ToVsHierarchy(envDTEProject);

            return(VsHierarchyUtility.HasUnsupportedProjectCapability(hier));
        }
        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 = EnvDTEProjectInfoUtility.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);
                                    }
// NuGet/Home#4833 Baseline
// Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
#pragma warning disable CS4014
                                    ProjectRetargetingUtility.MarkPackagesForReinstallation(nuGetProject, packagesToBeReinstalled);
#pragma warning restore CS4014
                                }
                            }
                        }
                    }
                    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);
        }
Exemple #15
0
        public async Task <NuGetProject> UpdateNuGetProjectToPackageRef(NuGetProject oldProject)
        {
#if VS14
            // do nothing for VS 2015 and simply return the existing NuGetProject
            if (NuGetProjectUpdated != null)
            {
                NuGetProjectUpdated(this, new NuGetProjectEventArgs(oldProject));
            }

            return(await Task.FromResult(oldProject));
#else
            if (oldProject == null)
            {
                throw new ArgumentException(
                          Strings.Argument_Cannot_Be_Null_Or_Empty,
                          nameof(oldProject));
            }

            var projectName = GetNuGetProjectSafeName(oldProject);
            var dteProject  = GetDTEProject(projectName);

            ProjectNames oldEnvDTEProjectName;
            _projectSystemCache.TryGetProjectNames(projectName, out oldEnvDTEProjectName);

            RemoveEnvDTEProjectFromCache(projectName);

            var nuGetProject = await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var settings = ServiceLocator.GetInstance <ISettings>();

                var context = new ProjectSystemProviderContext(
                    EmptyNuGetProjectContext,
                    () => PackagesFolderPathUtility.GetPackagesFolderPath(this, settings));

                return(new LegacyCSProjPackageReferenceProject(
                           new EnvDTEProjectAdapter(dteProject),
                           VsHierarchyUtility.GetProjectId(dteProject)));
            });

            var added = _projectSystemCache.AddProject(oldEnvDTEProjectName, dteProject, nuGetProject);

            if (DefaultNuGetProjectName == null)
            {
                DefaultNuGetProjectName = projectName;
            }

            if (NuGetProjectUpdated != null)
            {
                NuGetProjectUpdated(this, new NuGetProjectEventArgs(nuGetProject));
            }

            return(nuGetProject);
#endif
        }
Exemple #16
0
        private void RemoveImportStatementForVS2013(string relativeTargetPath)
        {
            NuGetVS.ProjectHelper.DoWorkInWriterLock(
                EnvDTEProject,
                VsHierarchyUtility.ToVsHierarchy(EnvDTEProject),
                buildProject => MicrosoftBuildEvaluationProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));

            // notify the project system of the change
            UpdateImportStamp(EnvDTEProject, true);
        }
        private static async Task <bool> IsProjectCapabilityCompliantAsync(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(envDTEProject != null);

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var hierarchy = await envDTEProject.ToVsHierarchyAsync();

            return(VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy));
        }
Exemple #18
0
        private static bool IsProjectCapabilityCompliant(EnvDTE.Project envDTEProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Debug.Assert(envDTEProject != null);

            var hierarchy = VsHierarchyUtility.ToVsHierarchy(envDTEProject);

            return(hierarchy.IsCapabilityMatch("AssemblyReferences + DeclaredSourceItems + UserSourceItems"));
        }
Exemple #19
0
        private static bool IsProjectCapabilityCompliant(EnvDTE.Project envDTEProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Debug.Assert(envDTEProject != null);

            var hierarchy = VsHierarchyUtility.ToVsHierarchy(envDTEProject);

            return(VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy));
        }
Exemple #20
0
        private async Task RemoveImportStatementForVS2013Async(string relativeTargetPath)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            await NuGetVS.ProjectHelper.DoWorkInWriterLockAsync(
                EnvDTEProject,
                VsHierarchyUtility.ToVsHierarchy(EnvDTEProject),
                buildProject => MicrosoftBuildEvaluationProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));

            // notify the project system of the change
            UpdateImportStamp(EnvDTEProject);
        }
        private async Task AddImportStatementAsync(ImportLocation location, string relativeTargetPath)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            await ProjectSystem.ProjectHelper.DoWorkInWriterLockAsync(
                EnvDTEProject,
                VsHierarchyUtility.ToVsHierarchy(EnvDTEProject),
                buildProject => MicrosoftBuildEvaluationProjectUtility.AddImportStatement(buildProject, relativeTargetPath, location));

            // notify the project system of the change
            UpdateImportStamp(EnvDTEProject);
        }
        private static bool IsProjectPackageReferenceCompatible(Project project)
        {
            var projectGuids = VsHierarchyUtility.GetProjectTypeGuids(project);

            if (projectGuids.Any(t => UnupgradeableProjectTypes.Contains(t)))
            {
                return(false);
            }

            // Project is supported language, and not an unsupported type
            return(UpgradeableProjectTypes.Contains(project.Kind) &&
                   projectGuids.All(projectTypeGuid => !SupportedProjectTypes.IsUnsupported(projectTypeGuid)));
        }
Exemple #23
0
        private static bool IsClassLibrary(EnvDTEProject envDTEProject)
        {
            if (IsWebSite(envDTEProject))
            {
                return(false);
            }

            // Consider class libraries projects that have one project type guid and an output type of project library.
            var outputType = GetPropertyValue <prjOutputType>(envDTEProject, "OutputType");

            return(VsHierarchyUtility.GetProjectTypeGuids(envDTEProject).Length == 1 &&
                   outputType == prjOutputType.prjOutputTypeLibrary);
        }
Exemple #24
0
        public async Task <NuGetProject> TryCreateNuGetProjectAsync(
            IVsProjectAdapter vsProject,
            ProjectProviderContext context,
            bool forceProjectType)
        {
            Assumes.Present(vsProject);
            Assumes.Present(context);

            ThreadHelper.ThrowIfNotOnUIThread();

            // The project must be an IVsHierarchy.
            var hierarchy = vsProject.VsHierarchy;

            if (hierarchy == null)
            {
                return(null);
            }

            // Check if the project is not CPS capable or if it is CPS capable that its opt'd in PackageReferences
            if (!VsHierarchyUtility.IsCPSCapabilityCompliant(hierarchy) ||
                !VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy))
            {
                return(null);
            }

            var buildProperties = vsProject.BuildProperties;

            // read MSBuild property RestoreProjectStyle
            var restoreProjectStyle = await buildProperties.GetPropertyValueAsync(ProjectBuildProperties.RestoreProjectStyle);

            // check for RestoreProjectStyle property is set and if not set to PackageReference then return false
            if (!(string.IsNullOrEmpty(restoreProjectStyle) ||
                  restoreProjectStyle.Equals(PackageReference, StringComparison.OrdinalIgnoreCase)))
            {
                return(null);
            }

            var fullProjectPath     = vsProject.FullProjectPath;
            var unconfiguredProject = GetUnconfiguredProject(vsProject.Project);

            var projectServices = new NetCoreProjectSystemServices(vsProject, await _componentModel.GetValueAsync());

            return(new CpsPackageReferenceProject(
                       vsProject.ProjectName,
                       vsProject.CustomUniqueName,
                       fullProjectPath,
                       _projectSystemCache,
                       unconfiguredProject,
                       projectServices,
                       vsProject.ProjectId));
        }
        public static async Task <bool> ContainsFileAsync(EnvDTE.Project envDTEProject, string path)
        {
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (string.Equals(envDTEProject.Kind, VsProjectTypes.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.FsharpProjectTypeGuid, StringComparison.OrdinalIgnoreCase)
                ||
                string.Equals(envDTEProject.Kind, VsProjectTypes.JsProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
            {
                // For Wix and Nemerle projects, IsDocumentInProject() returns not found
                // even though the file is in the project. So we use GetProjectItem()
                // instead. Nemerle is a high-level statically typed programming language for .NET platform
                // Note that pszMkDocument, the document moniker, passed to IsDocumentInProject(), must be a path to the file
                // for certain file-based project systems such as F#. And, not just a filename. For these project systems as well,
                // do the following
                var item = await GetProjectItemAsync(envDTEProject, path);

                return(item != null);
            }

            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var hierarchy = await envDTEProject.ToVsHierarchyAsync();

            var vsProject = hierarchy as IVsProject;

            if (vsProject == null)
            {
                return(false);
            }

            int pFound;

            if (VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy))
            {
                // REVIEW: We want to revisit this after RTM - the code in this if statement should be applied to every project type.
                // We're checking for VSDOCUMENTPRIORITY.DP_Standard here to see if the file is included in the project.
                // Original check (outside of if) did not have this.
                var priority = new VSDOCUMENTPRIORITY[1];
                var hr       = vsProject.IsDocumentInProject(path, out pFound, priority, out _);
                return(ErrorHandler.Succeeded(hr) && pFound == 1 && priority[0] >= VSDOCUMENTPRIORITY.DP_Standard);
            }

            var hres = vsProject.IsDocumentInProject(path, out pFound, Array.Empty <VSDOCUMENTPRIORITY>(), out _);

            return(ErrorHandler.Succeeded(hres) && pFound == 1);
        }
        public static async Task <bool> IsSupportedAsync(EnvDTE.Project envDTEProject)
        {
            Assumes.Present(envDTEProject);
            await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var hierarchy = await envDTEProject.ToVsHierarchyAsync();

            if (VsHierarchyUtility.IsProjectCapabilityCompliant(hierarchy))
            {
                return(true);
            }

            return(envDTEProject.Kind != null && ProjectType.IsSupported(envDTEProject.Kind) && !VsHierarchyUtility.HasUnsupportedProjectCapability(hierarchy));
        }
Exemple #27
0
        /// <summary>
        /// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out of date.
        /// The value does not matter, it just needs to change.
        /// </summary>
        protected static void UpdateImportStamp(EnvDTEProject envDTEProject, bool isCpsProjectSystem = false)
        {
            // There is no reason to call this for pre-Dev12 project systems.
            if (VSVersionHelper.VsMajorVersion >= 12)
            {
#if VS14
                // Switch to UI thread to update Import Stamp for Dev14.
                if (isCpsProjectSystem && VSVersionHelper.IsVisualStudio2014)
                {
                    try
                    {
                        var             projectServiceAccessor = ServiceLocator.GetInstance <IProjectServiceAccessor>();
                        ProjectService  projectService         = projectServiceAccessor.GetProjectService();
                        IThreadHandling threadHandling         = projectService.Services.ThreadingPolicy;
                        threadHandling.SwitchToUIThread();
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.WriteToActivityLog(ex);
                    }
                }
#endif

                IVsBuildPropertyStorage propStore = VsHierarchyUtility.ToVsHierarchy(envDTEProject) as IVsBuildPropertyStorage;
                if (propStore != null)
                {
                    // <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
                    string stamp = Guid.NewGuid().ToString().Split('-')[0];
                    try
                    {
                        int r1 = propStore.SetPropertyValue(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp);
                    }
                    catch (Exception ex1)
                    {
                        ExceptionHelper.WriteToActivityLog(ex1);
                    }

                    // Remove the NuGetImportStamp so that VC++ project file won't be updated with this stamp on disk,
                    // which causes unnecessary source control pending changes.
                    try
                    {
                        int r2 = propStore.RemoveProperty(NuGetImportStamp, string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE);
                    }
                    catch (Exception ex2)
                    {
                        ExceptionHelper.WriteToActivityLog(ex2);
                    }
                }
            }
        }
Exemple #28
0
        public Task CollapseAllNodes(ISolutionManager solutionManager)
        {
            if (solutionManager == null)
            {
                throw new ArgumentNullException(nameof(solutionManager));
            }

            return(NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                await VsHierarchyUtility.CollapseAllNodesAsync(solutionManager, _expandedNodes);

                return Task.CompletedTask;
            }));
        }
Exemple #29
0
        /// <summary>
        /// Check if the project has an unsupported project capability, such as, "SharedAssetsProject"
        /// </summary>
        public static bool HasUnsupportedProjectCapability(EnvDTE.Project envDTEProject)
        {
            Debug.Assert(ThreadHelper.CheckAccess());

            var hier = VsHierarchyUtility.ToVsHierarchy(envDTEProject);

            foreach (var unsupportedProjectCapability in UnsupportedProjectCapabilities)
            {
                if (hier.IsCapabilityMatch(unsupportedProjectCapability))
                {
                    return(true);
                }
            }

            return(false);
        }
        public ProjectJsonBuildIntegratedProjectSystem(
            string jsonConfigPath,
            string msbuildProjectFilePath,
            EnvDTEProject envDTEProject,
            string uniqueName)
            : base(jsonConfigPath, msbuildProjectFilePath)
        {
            _envDTEProject = envDTEProject;

            // set project id
            var projectId = VsHierarchyUtility.GetProjectId(envDTEProject);

            InternalMetadata.Add(NuGetProjectMetadataKeys.ProjectId, projectId);

            InternalMetadata.Add(NuGetProjectMetadataKeys.UniqueName, uniqueName);
        }