private bool TryGetVsHierarchyAndItemId(
            Document document,
            [NotNullWhen(true)] out IVsHierarchy?hierarchy,
            out uint itemID
            )
        {
            AssertIsForeground();

            if (
                document.Project.Solution.Workspace is VisualStudioWorkspace visualStudioWorkspace &&
                document.FilePath is object
                )
            {
                hierarchy = visualStudioWorkspace.GetHierarchy(document.Project.Id);
                if (hierarchy is object)
                {
                    itemID = hierarchy.TryGetItemId(document.FilePath);
                    if (itemID != VSConstants.VSITEMID_NIL)
                    {
                        return(true);
                    }
                }
            }

            hierarchy = null;
            itemID    = (uint)VSConstants.VSITEMID.Nil;
            return(false);
        }
Esempio n. 2
0
        public IUnconfiguredProjectVsServicesMock ImplementVsHierarchy(IVsHierarchy?hierarchy)
        {
            SetupGet <IVsHierarchy?>(m => m.VsHierarchy)
            .Returns(hierarchy);

            return(this);
        }
Esempio n. 3
0
        private IVsProject?TryGetProjectOfHierarchy(IVsHierarchy?hierarchy)
        {
            // The invisible editor manager will fail in cases where the IVsProject passed to it is not consistent with
            // the IVsProject known to IVsSolution (e.g. if the object is a wrapper like AbstractHostObject created by
            // the CPS-based project system). This method returns an IVsProject instance known to the solution, or null
            // if the project could not be determined.
            if (hierarchy == null)
            {
                return(null);
            }

            if (!ErrorHandler.Succeeded(hierarchy.GetGuidProperty(
                                            (uint)VSConstants.VSITEMID.Root,
                                            (int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
                                            out var projectId)))
            {
                return(null);
            }

            var solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));

            if (!ErrorHandler.Succeeded(solution.GetProjectOfGuid(projectId, out var projectHierarchy)))
            {
                return(null);
            }

            return(projectHierarchy as IVsProject);
        }
 private static void AssertFailed(int result, IVsHierarchy?hierarchy, uint itemid, IVsContainedLanguageFactory?containedLanguageFactory)
 {
     Assert.Equal(VSConstants.E_FAIL, result);
     Assert.Null(hierarchy);
     Assert.Null(containedLanguageFactory);
     Assert.Equal((uint)VSConstants.VSITEMID.Nil, itemid);
 }
Esempio n. 5
0
        public bool IsProjectCpsBased(string projectPath)
        {
            IVsHierarchy?projectHierarchy = GetProjectHierarchy(projectPath);
            var          isCps            = projectHierarchy.IsCapabilityMatch("CPS");

            return(isCps);
        }
Esempio n. 6
0
 public static bool TryGetParentHierarchy(
     this IVsHierarchy hierarchy,
     [NotNullWhen(returnValue: true)] out IVsHierarchy?parentHierarchy
     ) =>
 hierarchy.TryGetProperty <IVsHierarchy>(
     __VSHPROPID.VSHPROPID_ParentHierarchy,
     out parentHierarchy
     );
Esempio n. 7
0
        private static DesignTimeAssemblyResolution CreateInstance(IVsHierarchy?hierarchy = null)
        {
            hierarchy ??= IVsHierarchyFactory.Create();

            IUnconfiguredProjectVsServices projectVsServices = IUnconfiguredProjectVsServicesFactory.Implement(() => hierarchy);

            return(new DesignTimeAssemblyResolution(projectVsServices));
        }
        /// <summary>
        /// Tries to set a build property on the project.
        /// </summary>
        public static async Task <bool> TrySetBuildPropertyAsync(this Project project, string name, string value, _PersistStorageType storageType = _PersistStorageType.PST_USER_FILE)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsHierarchy?hierarchy = await project.ToHierarchyAsync();

            return(hierarchy != null && hierarchy.TrySetBuildProperty(name, value, storageType));
        }
        /// <summary>
        /// Returns whether the project is a 'Shared' project.
        /// </summary>
        public static async Task <bool> IsSharedProjectAsync(this Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsHierarchy?hierarchy = await project.ToHierarchyAsync();

            return(hierarchy?.IsSharedAssetsProject() ?? false);
        }
Esempio n. 10
0
        public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy?projectHierarchy)
        {
            if (_tableControl == null)
            {
                return(false);
            }

            var shouldFixInProject = GetShouldFixInProjectDelegate(_vsHierarchyItemManager, _projectMap, projectHierarchy);

            return(ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: false, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true));
        }
        public int GetContainedLanguageFactoryForFile(string filePath,
                                                      out IVsHierarchy?hierarchy,
                                                      out uint itemid,
                                                      out IVsContainedLanguageFactory?containedLanguageFactory)
        {
            (itemid, hierarchy, containedLanguageFactory) = _projectVsServices.ThreadingService.ExecuteSynchronously(() =>
            {
                return(GetContainedLanguageFactoryForFileAsync(filePath));
            });

            return((hierarchy == null || containedLanguageFactory == null) ? HResult.Fail : HResult.OK);
        }
        private bool TryGetNavigationAPIRequiredArguments(
            DefinitionItem definitionItem,
            string?rqName,
            CancellationToken cancellationToken,
            [NotNullWhen(true)] out IVsHierarchy?hierarchy,
            out uint itemID,
            [NotNullWhen(true)] out IVsSymbolicNavigationNotify?navigationNotify
            )
        {
            AssertIsForeground();

            hierarchy        = null;
            navigationNotify = null;
            itemID           = (uint)VSConstants.VSITEMID.Nil;

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

            var sourceLocations = definitionItem.SourceSpans;

            if (!sourceLocations.Any())
            {
                return(false);
            }

            var documents = sourceLocations.SelectAsArray(loc => loc.Document);

            // We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from
            // documents we consider to be "generated" to give external language services the best
            // chance of participating.

            var generatedDocuments = documents.WhereAsArray(
                d => d.IsGeneratedCode(cancellationToken)
                );

            var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First();

            if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID))
            {
                return(false);
            }

            navigationNotify = hierarchy as IVsSymbolicNavigationNotify;
            if (navigationNotify == null)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Returns the unique project id as identified in the solution.
        /// </summary>
        public static async Task <Guid?> GetProjectGuidAsync(this Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsHierarchy?hierarchy = await project.ToHierarchyAsync();

            if (hierarchy != null && hierarchy.GetGuidProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out Guid id) == VSConstants.S_OK)
            {
                return(id);
            }

            return(null);
        }
Esempio n. 14
0
        private Project?GetProject(IVsHierarchy?hierarchy)
        {
            if (hierarchy != null)
            {
                var projectMap           = _workspace.Services.GetRequiredService <IHierarchyItemToProjectIdMap>();
                var projectHierarchyItem = _vsHierarchyItemManager.GetHierarchyItem(hierarchy, VSConstants.VSITEMID_ROOT);
                if (projectMap.TryGetProjectId(projectHierarchyItem, targetFrameworkMoniker: null, out var projectId))
                {
                    return(_workspace.CurrentSolution.GetProject(projectId));
                }
            }

            return(null);
        }
Esempio n. 15
0
        /// <remarks>
        /// <para>The optional project is used to obtain an <see cref="IVsProject"/> instance. When this instance is
        /// provided, Visual Studio will use <see cref="IVsProject.IsDocumentInProject"/> to attempt to locate the
        /// specified file within a project. If no project is specified, Visual Studio falls back to using
        /// <see cref="IVsUIShellOpenDocument4.IsDocumentInAProject2"/>, which performs a much slower query of all
        /// projects in the solution.</para>
        /// </remarks>
        public InvisibleEditor(IServiceProvider serviceProvider, string filePath, IVsHierarchy?hierarchy, bool needsSave, bool needsUndoDisabled)
            : base(serviceProvider.GetMefService <IThreadingContext>(), assertIsForeground: true)
        {
            _serviceProvider = serviceProvider;
            _filePath        = filePath;
            _needsSave       = needsSave;

            var invisibleEditorManager = (IIntPtrReturningVsInvisibleEditorManager)serviceProvider.GetService(typeof(SVsInvisibleEditorManager));
            var vsProject = hierarchy as IVsProject;

            Marshal.ThrowExceptionForHR(invisibleEditorManager.RegisterInvisibleEditor(filePath, vsProject, 0, null, out var invisibleEditorPtr));

            try
            {
                _invisibleEditor = (IVsInvisibleEditor)Marshal.GetUniqueObjectForIUnknown(invisibleEditorPtr);

                var docDataPtr = IntPtr.Zero;
                Marshal.ThrowExceptionForHR(_invisibleEditor.GetDocData(fEnsureWritable: needsSave ? 1 : 0, riid: typeof(IVsTextLines).GUID, ppDocData: out docDataPtr));

                try
                {
                    var docData = Marshal.GetObjectForIUnknown(docDataPtr);
                    _vsTextLines = (IVsTextLines)docData;
                    var editorAdapterFactoryService = serviceProvider.GetMefService <IVsEditorAdaptersFactoryService>();
                    _buffer = editorAdapterFactoryService.GetDocumentBuffer(_vsTextLines);
                    if (needsUndoDisabled)
                    {
                        Marshal.ThrowExceptionForHR(_vsTextLines.GetUndoManager(out _manager));
                        Marshal.ThrowExceptionForHR(((IVsUndoState)_manager).IsEnabled(out var isEnabled));
                        _needsUndoRestored = isEnabled != 0;
                        if (_needsUndoRestored)
                        {
                            _manager.DiscardFrom(null); // Discard the undo history for this document
                            _manager.Enable(0);         // Disable Undo for this document
                        }
                    }
                }
                finally
                {
                    Marshal.Release(docDataPtr);
                }
            }
            finally
            {
                // We need to clean up the extra reference we have, now that we have an RCW holding onto the object.
                Marshal.Release(invisibleEditorPtr);
            }
        }
        private static VsContainedLanguageComponentsFactory CreateInstance(
            IVsProject4 project,
            IVsContainedLanguageFactory?containedLanguageFactory = null,
            IVsHierarchy?hierarchy       = null,
            ProjectProperties?properties = null,
            IActiveWorkspaceProjectContextHost?projectContextHost = null)
        {
            var serviceProvider = IOleAsyncServiceProviderFactory.ImplementQueryServiceAsync(containedLanguageFactory, new Guid(LanguageServiceId));

            var projectVsServices = new IUnconfiguredProjectVsServicesMock();

            projectVsServices.ImplementVsHierarchy(hierarchy);
            projectVsServices.ImplementVsProject(project);
            projectVsServices.ImplementThreadingService(IProjectThreadingServiceFactory.Create());
            projectVsServices.ImplementActiveConfiguredProjectProperties(properties);

            return(CreateInstance(serviceProvider, projectVsServices.Object, projectContextHost));
        }
        public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy?projectHierarchy)
        {
            var errorReportingService = _workspace.Services.GetRequiredService <IErrorReportingService>();

            try
            {
                return(_implementation.RemoveSuppressions(selectedErrorListEntriesOnly, projectHierarchy));
            }
            catch (Exception ex)
            {
                errorReportingService.ShowGlobalErrorInfo(
                    string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message),
                    new InfoBarUI(
                        WorkspacesResources.Show_Stack_Trace,
                        InfoBarUI.UIKind.HyperLink,
                        () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true));
                return(false);
            }
        }
Esempio n. 18
0
        public bool AddSuppressions(IVsHierarchy?projectHierarchy)
        {
            if (_tableControl == null)
            {
                return(false);
            }

            var shouldFixInProject = GetShouldFixInProjectDelegate(_vsHierarchyItemManager, _projectMap, projectHierarchy);

            // Apply suppressions fix in global suppressions file for non-compiler diagnostics and
            // in source only for compiler diagnostics.
            var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly: false, isAddSuppression: true);

            if (!ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: false))
            {
                return(false);
            }

            return(ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: true, onlyCompilerDiagnostics: true, showPreviewChangesDialog: false));
        }
Esempio n. 19
0
        public static IVsSolutionBuildManager2 Create(
            IVsUpdateSolutionEvents?solutionEventsListener = null,
            IVsHierarchy?hierarchyToBuild = null,
            bool isBuilding  = false,
            bool cancelBuild = false)
        {
            var buildManager = new Mock <IVsSolutionBuildManager2>();

            solutionEventsListener ??= IVsUpdateSolutionEventsFactory.Create();
            hierarchyToBuild ??= IVsHierarchyFactory.Create();

            int isBusy = isBuilding ? 1 : 0;

            buildManager.Setup(b => b.QueryBuildManagerBusy(out isBusy))
            .Returns(VSConstants.S_OK);

            if (hierarchyToBuild != null)
            {
                int onBuildStartedWithReturn()
                {
                    solutionEventsListener !.UpdateSolution_Begin(It.IsAny <int>());

                    if (cancelBuild)
                    {
                        solutionEventsListener.UpdateSolution_Cancel();
                    }
                    else
                    {
                        solutionEventsListener.UpdateSolution_Done(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>());
                    }

                    return(VSConstants.S_OK);
                }

                uint dwFlags = (uint)(VSSOLNBUILDUPDATEFLAGS.SBF_SUPPRESS_SAVEBEFOREBUILD_QUERY | VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD);
                buildManager.Setup(b => b.StartSimpleUpdateProjectConfiguration(hierarchyToBuild, It.IsAny <IVsHierarchy>(), It.IsAny <string>(), dwFlags, It.IsAny <uint>(), It.IsAny <int>()))
                .Returns(onBuildStartedWithReturn);
            }

            return(buildManager.Object);
        }
        public bool AddSuppressions(IVsHierarchy?projectHierarchy)
        {
            var errorReportingService = _workspace.Services.GetRequiredService <IErrorReportingService>();

            try
            {
                return(_implementation.AddSuppressions(projectHierarchy));
            }
            catch (Exception ex)
            {
                errorReportingService.ShowGlobalErrorInfo(
                    string.Format(ServicesVSResources.Error_updating_suppressions_0, ex.Message),
                    TelemetryFeatureName.LegacySuppressionFix,
                    ex,
                    new InfoBarUI(
                        WorkspacesResources.Show_Stack_Trace,
                        InfoBarUI.UIKind.HyperLink,
                        () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true));
                return(false);
            }
        }
        public static IVsSolutionBuildManager2 Create(
            IVsUpdateSolutionEvents?solutionEventsListener = null,
            IVsHierarchy?hierarchyToBuild = null,
            bool isBuilding  = false,
            bool cancelBuild = false)
        {
            var buildManager = new Mock <IVsSolutionBuildManager2>();

            solutionEventsListener ??= IVsUpdateSolutionEventsFactory.Create();
            hierarchyToBuild ??= IVsHierarchyFactory.Create();

            int isBusy = isBuilding ? 1 : 0;

            buildManager.Setup(b => b.QueryBuildManagerBusy(out isBusy))
            .Returns(VSConstants.S_OK);

            if (hierarchyToBuild != null)
            {
                int onBuildStartedWithReturn()
                {
                    solutionEventsListener.UpdateSolution_Begin(It.IsAny <int>());

                    if (cancelBuild)
                    {
                        solutionEventsListener.UpdateSolution_Cancel();
                    }
                    else
                    {
                        solutionEventsListener.UpdateSolution_Done(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>());
                    }

                    return(VSConstants.S_OK);
                }

                buildManager.Setup(b => b.StartUpdateSpecificProjectConfigurations(It.IsAny <uint>(), It.IsAny <IVsHierarchy[]>(), It.IsAny <IVsCfg[]>(), It.IsAny <uint[]>(), It.IsAny <uint[]>(), It.IsAny <uint[]>(), It.IsAny <uint>(), It.IsAny <int>()))
                .Returns(onBuildStartedWithReturn);
            }

            return(buildManager.Object);
        }
        public void OnAfterGlobalSymbolRenamed(string projectPath, IEnumerable <string> filePaths, string rqName, string newName)
        {
            IVsHierarchy?projectHierarchy = GetProjectHierarchy(projectPath);

            if (projectHierarchy == null)
            {
                return;
            }

            if (!(projectHierarchy is IVsHierarchyRefactorNotify refactorNotify))
            {
                return;
            }

            uint[] ids = GetIdsForFiles(projectHierarchy, filePaths).ToArray();

            refactorNotify.OnGlobalSymbolRenamed(cItemsAffected: (uint)ids.Length,
                                                 rgItemsAffected: ids,
                                                 cRQNames: 1,
                                                 rglpszRQName: new[] { rqName },
                                                 lpszNewName: newName);
        }
Esempio n. 23
0
        public static ISolutionBuildManager Create(
            IVsUpdateSolutionEvents?solutionEventsListener = null,
            IVsHierarchy?hierarchyToBuild = null,
            bool isBuilding  = false,
            bool cancelBuild = false)
        {
            var buildManager = new Mock <ISolutionBuildManager>();

            solutionEventsListener ??= IVsUpdateSolutionEventsFactory.Create();
            hierarchyToBuild ??= IVsHierarchyFactory.Create();

            int isBusy = isBuilding ? 1 : 0;

            buildManager.Setup(b => b.QueryBuildManagerBusy())
            .Returns(isBusy);

            if (hierarchyToBuild != null)
            {
                void onBuildStartedWithReturn(IVsHierarchy[] _, uint[] __, uint ___)
                {
                    solutionEventsListener !.UpdateSolution_Begin(It.IsAny <int>());

                    if (cancelBuild)
                    {
                        solutionEventsListener.UpdateSolution_Cancel();
                    }
                    else
                    {
                        solutionEventsListener.UpdateSolution_Done(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>());
                    }
                }

                buildManager.Setup(b => b.StartUpdateSpecificProjectConfigurations(It.IsAny <IVsHierarchy[]>(), It.IsAny <uint[]>(), It.IsAny <uint>()))
                .Callback((System.Action <IVsHierarchy[], uint[], uint>)onBuildStartedWithReturn);
            }

            return(buildManager.Object);
        }
Esempio n. 24
0
            public async Task OnBeforeGlobalSymbolRenamedAsync(string projectPath, IEnumerable <string> filePaths, string rqName, string newName)
            {
                IVsHierarchy?projectHierarchy = await GetProjectHierarchy(projectPath);

                if (projectHierarchy == null)
                {
                    return;
                }

                if (!(projectHierarchy is IVsHierarchyRefactorNotify refactorNotify))
                {
                    return;
                }

                uint[] ids = GetIdsForFiles(projectHierarchy, filePaths).ToArray();

                refactorNotify.OnBeforeGlobalSymbolRenamed(cItemsAffected: (uint)ids.Length,
                                                           rgItemsAffected: ids,
                                                           cRQNames: (uint)1,
                                                           rglpszRQName: new[] { rqName },
                                                           lpszNewName: newName,
                                                           promptContinueOnFail: 1);
            }
Esempio n. 25
0
        public IReadOnlyDictionary <string, IEnumerable <DiagnosticDescriptor> > GetAllDiagnosticDescriptors(IVsHierarchy?hierarchy)
        {
            var currentSolution = _workspace.CurrentSolution;
            var infoCache       = _diagnosticService.AnalyzerInfoCache;
            var hostAnalyzers   = currentSolution.State.Analyzers;

            if (hierarchy == null)
            {
                return(Transform(hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache)));
            }

            // Analyzers are only supported for C# and VB currently.
            var projectsWithHierarchy = currentSolution.Projects
                                        .Where(p => p.Language is LanguageNames.CSharp or LanguageNames.VisualBasic)
                                        .Where(p => _workspace.GetHierarchy(p.Id) == hierarchy);

            if (projectsWithHierarchy.Count() <= 1)
            {
                var project = projectsWithHierarchy.FirstOrDefault();
                if (project == null)
                {
                    return(Transform(hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache)));
                }
                else
                {
                    return(Transform(hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache, project)));
                }
            }
            else
            {
                // Multiple workspace projects map to the same hierarchy, return a union of descriptors for all projects.
                // For example, this can happen for web projects where we create on the fly projects for aspx files.
                var descriptorsMap = ImmutableDictionary.CreateBuilder <string, IEnumerable <DiagnosticDescriptor> >();
                foreach (var project in projectsWithHierarchy)
                {
                    var descriptorsPerReference = hostAnalyzers.GetDiagnosticDescriptorsPerReference(infoCache, project);
                    foreach (var(displayName, descriptors) in descriptorsPerReference)
                    {
                        if (descriptorsMap.TryGetValue(displayName, out var existingDescriptors))
                        {
                            descriptorsMap[displayName] = existingDescriptors.Concat(descriptors).Distinct();
                        }
                        else
                        {
                            descriptorsMap[displayName] = descriptors;
                        }
                    }
                }

                return(descriptorsMap.ToImmutable());
            }
        }
Esempio n. 26
0
 void IRunningDocumentTableEventListener.OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy?hierarchy, IVsWindowFrame?_)
 => TryOpeningDocumentsForMoniker(moniker, textBuffer, hierarchy);
 void IRunningDocumentTableEventListener.OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy?hierarchy, IVsWindowFrame?windowFrame) => NotifyOnDocumentOpened(moniker, textBuffer);
Esempio n. 28
0
        void IRunningDocumentTableEventListener.OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy?hierarchy, IVsWindowFrame?windowFrame)
        {
            if (TryParseGeneratedFilePath(moniker, out var projectId, out var generatorTypeName, out var generatorAssemblyName, out var generatedSourceHintName))
            {
                // Attach to the text buffer if we haven't already
                if (!_openFiles.TryGetValue(moniker, out OpenSourceGeneratedFile openFile))
                {
                    openFile = new OpenSourceGeneratedFile(this, textBuffer, _visualStudioWorkspace, projectId, generatorTypeName, generatorAssemblyName, generatedSourceHintName, _threadingContext);
                    _openFiles.Add(moniker, openFile);
                    _threadingContext.JoinableTaskFactory.Run(() => openFile.UpdateBufferContentsAsync(CancellationToken.None));

                    // Update the RDT flags to ensure the file can't be saved or appears in any MRUs as it's a temporary generated file name.
                    var cookie = ((IVsRunningDocumentTable4)_runningDocumentTable).GetDocumentCookie(moniker);
                    ErrorHandler.ThrowOnFailure(_runningDocumentTable.ModifyDocumentFlags(cookie, (uint)(_VSRDTFLAGS.RDT_CantSave | _VSRDTFLAGS.RDT_DontAddToMRU), fSet: 1));
                }

                if (windowFrame != null)
                {
                    openFile.SetWindowFrame(windowFrame);
                }
            }
        }
Esempio n. 29
0
        public void RunAnalyzers(IVsHierarchy?hierarchy)
        {
            var project  = GetProject(hierarchy);
            var solution = _workspace.CurrentSolution;
            var projectOrSolutionName = project?.Name ?? PathUtilities.GetFileName(solution.FilePath);

            // Add a message to VS status bar that we are running code analysis.
            var statusBar         = _serviceProvider?.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            var totalProjectCount = project != null ? 1 : (uint)solution.ProjectIds.Count;
            var statusBarUpdater  = statusBar != null ?
                                    new StatusBarUpdater(statusBar, _threadingContext, projectOrSolutionName, totalProjectCount) :
                                    null;

            // Force complete analyzer execution in background.
            var asyncToken = _listener.BeginAsyncOperation($"{nameof(VisualStudioDiagnosticAnalyzerService)}_{nameof(RunAnalyzers)}");

            Task.Run(async() =>
            {
                try
                {
                    var onProjectAnalyzed = statusBarUpdater != null ? statusBarUpdater.OnProjectAnalyzed : (Action <Project>)((Project _) => { });
                    await _diagnosticService.ForceAnalyzeAsync(solution, onProjectAnalyzed, project?.Id, CancellationToken.None).ConfigureAwait(false);

                    // If user has disabled live analyzer execution for any project(s), i.e. set RunAnalyzersDuringLiveAnalysis = false,
                    // then ForceAnalyzeAsync will not cause analyzers to execute.
                    // We explicitly fetch diagnostics for such projects and report these as "Host" diagnostics.
                    HandleProjectsWithDisabledAnalysis();
                }
                finally
                {
                    statusBarUpdater?.Dispose();
                }
            }).CompletesAsyncOperation(asyncToken);

            return;

            void HandleProjectsWithDisabledAnalysis()
            {
                RoslynDebug.Assert(solution != null);

                // First clear all special host diagostics for all involved projects.
                var projects = project != null?SpecializedCollections.SingletonEnumerable(project) : solution.Projects;

                foreach (var project in projects)
                {
                    _hostDiagnosticUpdateSource.ClearDiagnosticsForProject(project.Id, key: this);
                }

                // Now compute the new host diagostics for all projects with disabled analysis.
                var projectsWithDisabledAnalysis = projects.Where(p => !p.State.RunAnalyzers).ToImmutableArrayOrEmpty();

                if (!projectsWithDisabledAnalysis.IsEmpty)
                {
                    // Compute diagnostics by overidding project's RunCodeAnalysis flag to true.
                    var tasks = new System.Threading.Tasks.Task <ImmutableArray <DiagnosticData> > [projectsWithDisabledAnalysis.Length];
                    for (var index = 0; index < projectsWithDisabledAnalysis.Length; index++)
                    {
                        var project = projectsWithDisabledAnalysis[index];
                        project      = project.Solution.WithRunAnalyzers(project.Id, runAnalyzers: true).GetProject(project.Id) !;
                        tasks[index] = Task.Run(
                            () => _diagnosticService.GetDiagnosticsAsync(project.Solution, project.Id));
                    }

                    Task.WhenAll(tasks).Wait();

                    // Report new host diagostics.
                    for (var index = 0; index < projectsWithDisabledAnalysis.Length; index++)
                    {
                        var project     = projectsWithDisabledAnalysis[index];
                        var diagnostics = tasks[index].Result;
                        _hostDiagnosticUpdateSource.UpdateDiagnosticsForProject(project.Id, key: this, diagnostics);
                    }
                }
            }
        }
Esempio n. 30
0
        private static Func <Project, bool> GetShouldFixInProjectDelegate(IVsHierarchyItemManager vsHierarchyItemManager, IHierarchyItemToProjectIdMap projectMap, IVsHierarchy?projectHierarchy)
        {
            ProjectId?projectIdToMatch = null;

            if (projectHierarchy != null)
            {
                var projectHierarchyItem = vsHierarchyItemManager.GetHierarchyItem(projectHierarchy, VSConstants.VSITEMID_ROOT);
                if (projectMap.TryGetProjectId(projectHierarchyItem, targetFrameworkMoniker: null, out var projectId))
                {
                    projectIdToMatch = projectId;
                }
            }

            return(p => projectHierarchy == null || p.Id == projectIdToMatch);
        }