コード例 #1
0
        private async Task DeleteMessageFile(QueuedMessage queuedMessage)
        {
            var message       = queuedMessage.Message;
            var headers       = message.Headers;
            var pattern       = headers.MessageId + "*.pmsg";
            var matchingFiles = _directory.EnumerateFiles(pattern);

            foreach (var matchingFile in matchingFiles)
            {
                matchingFile.Delete();
                await DiagnosticService.EmitAsync(
                    new FilesystemEventBuilder(this, FilesystemEventType.MessageFileDeleted)
                {
                    Detail  = "Message file deleted",
                    Message = message,
                    Queue   = QueueName,
                    Path    = matchingFile.FullName
                }.Build());
            }
        }
コード例 #2
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            // Change the background analysis scope to OpenFiles instead of ActiveFile (default),
            // so that every diagnostic tagger test does not need to mark test files as "active" file.
            workspace.GlobalOptions.SetGlobalOption(new OptionKey(SolutionCrawlerOptionsStorage.BackgroundAnalysisScopeOption, LanguageNames.CSharp), BackgroundAnalysisScope.OpenFiles);
            workspace.GlobalOptions.SetGlobalOption(new OptionKey(SolutionCrawlerOptionsStorage.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic), BackgroundAnalysisScope.OpenFiles);

            _workspace = workspace;

            _registrationService = (SolutionCrawlerRegistrationService)workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            if (!_registrationService.GetTestAccessor().TryGetWorkCoordinator(workspace, out var coordinator))
            {
                throw new InvalidOperationException();
            }

            AnalyzerService   = (DiagnosticAnalyzerService?)_registrationService.GetTestAccessor().AnalyzerProviders.SelectMany(pair => pair.Value).SingleOrDefault(lazyProvider => lazyProvider.Metadata.Name == WellKnownSolutionCrawlerAnalyzers.Diagnostic && lazyProvider.Metadata.HighPriorityForActiveFile)?.Value;
            DiagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue <IDiagnosticService>();

            if (updateSource is object)
            {
                DiagnosticService.Register(updateSource);
            }

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }
        }
コード例 #3
0
        private DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            Dictionary <string, DiagnosticAnalyzer[]> analyzerMap,
            IDiagnosticUpdateSource updateSource,
            bool createTaggerProvider)
        {
            _asyncListener = new AsynchronousOperationListener();
            _listeners     = AsynchronousOperationListener.CreateListeners(
                ValueTuple.Create(FeatureAttribute.DiagnosticService, _asyncListener),
                ValueTuple.Create(FeatureAttribute.ErrorSquiggles, _asyncListener));

            if (analyzerMap != null || updateSource == null)
            {
                AnalyzerService = CreateDiagnosticAnalyzerService(analyzerMap, _asyncListener);
            }

            if (updateSource == null)
            {
                updateSource = AnalyzerService;
            }

            _workspace = workspace;

            _registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listeners);
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                var taggerProvider = this.TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
コード例 #4
0
        public void TestGetDiagnostics2()
        {
            using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic))
            {
                var set       = new ManualResetEvent(false);
                var document  = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", string.Empty);
                var document2 = document.Project.AddDocument("TestDocument2", string.Empty);

                var source            = new TestDiagnosticUpdateSource(false, null);
                var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonCollection(source), AggregateAsynchronousOperationListener.EmptyListeners);
                diagnosticService.DiagnosticsUpdated += (s, o) => { set.Set(); };

                var id = Tuple.Create(workspace, document);
                RaiseDiagnosticEvent(set, source, workspace, document.Project.Id, document.Id, id);

                var id2 = Tuple.Create(workspace, document.Project, document);
                RaiseDiagnosticEvent(set, source, workspace, document.Project.Id, document.Id, id2);

                RaiseDiagnosticEvent(set, source, workspace, document2.Project.Id, document2.Id, Tuple.Create(workspace, document2));

                var id3 = Tuple.Create(workspace, document.Project);
                RaiseDiagnosticEvent(set, source, workspace, document.Project.Id, null, id3);
                RaiseDiagnosticEvent(set, source, workspace, null, null, Tuple.Create(workspace));

                var data1 = diagnosticService.GetDiagnostics(workspace, null, null, null, CancellationToken.None);
                Assert.Equal(5, data1.Count());

                var data2 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, null, null, CancellationToken.None);
                Assert.Equal(4, data2.Count());

                var data3 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, null, id3, CancellationToken.None);
                Assert.Equal(1, data3.Count());

                var data4 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, null, CancellationToken.None);
                Assert.Equal(2, data4.Count());

                var data5 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, id, CancellationToken.None);
                Assert.Equal(1, data5.Count());
            }
        }
コード例 #5
0
        private async Task MoveToDeadLetterDirectory(QueuedMessage queuedMessage)
        {
            var message       = queuedMessage.Message;
            var headers       = message.Headers;
            var pattern       = headers.MessageId + "*.pmsg";
            var matchingFiles = _directory.EnumerateFiles(pattern);

            foreach (var matchingFile in matchingFiles)
            {
                var messageFile = new MessageFile(matchingFile);
                var deadLetter  = await messageFile.MoveTo(_deadLetterDirectory);

                await DiagnosticService.EmitAsync(
                    new FilesystemEventBuilder(this, DiagnosticEventType.DeadLetter)
                {
                    Detail  = "Message file deleted",
                    Message = message,
                    Queue   = QueueName,
                    Path    = deadLetter.File.FullName
                }.Build());
            }
        }
コード例 #6
0
        private DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            Dictionary <string, DiagnosticAnalyzer[]> analyzerMap,
            IDiagnosticUpdateSource updateSource,
            bool createTaggerProvider)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            if (analyzerMap != null || updateSource == null)
            {
                AnalyzerService = CreateDiagnosticAnalyzerService(analyzerMap, _listenerProvider.GetListener(FeatureAttribute.DiagnosticService));
            }

            if (updateSource == null)
            {
                updateSource = AnalyzerService;
            }

            _workspace = workspace;

            _registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listenerProvider, Array.Empty <Lazy <IEventListener, EventListenerMetadata> >());
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                var taggerProvider = this.TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
コード例 #7
0
        /// <inheritdoc />
        /// <summary>
        /// Returns messages in the queue that are pending
        /// </summary>
        /// <param name="cancellationToken">(Optional) A token provided by the caller that can
        /// be used by the caller to request cancellation of the fetch operation</param>
        /// <returns>Returns the set of pending messages in the queue</returns>
        protected override async Task <IEnumerable <QueuedMessage> > GetPendingMessages(CancellationToken cancellationToken = default(CancellationToken))
        {
            var fb     = Builders <QueuedMessageDocument> .Filter;
            var filter = fb.Eq(qm => qm.Queue, (string)QueueName) &
                         fb.Eq(qm => qm.State, QueuedMessageState.Pending);

            var existingMessages = await _queuedMessages.Find(filter).ToListAsync(cancellationToken);

            var queuedMessages = new List <QueuedMessage>();

            foreach (var queuedMessage in existingMessages)
            {
                try
                {
                    var messageHeaders = new MessageHeaders(queuedMessage.Headers);
                    var principal      = await _securityTokenService.NullSafeValidate(messageHeaders.SecurityToken);

                    var message = new Message(messageHeaders, queuedMessage.Content);
                    if (message.IsEncrypted() && _messageEncryptionService != null)
                    {
                        message = await _messageEncryptionService.Decrypt(message);
                    }
                    message = message.WithoutSecurityToken();
                    queuedMessages.Add(new QueuedMessage(message, principal, queuedMessage.Attempts));
                }
                catch (Exception ex)
                {
                    DiagnosticService.Emit(new MongoDBEventBuilder(this, MongoDBEventType.MessageDocumentFormatError)
                    {
                        Detail         = "Error reading previously queued message document ID " + queuedMessage.Id + "; skipping",
                        CollectionName = _queuedMessages.CollectionNamespace.CollectionName,
                        DatabaseName   = _queuedMessages.Database.DatabaseNamespace.DatabaseName,
                        Exception      = ex
                    }.Build());
                }
            }
            return(queuedMessages);
        }
コード例 #8
0
        private async Task CreateMessageFile(QueuedMessage queuedMessage)
        {
            var message       = queuedMessage.Message;
            var principal     = queuedMessage.Principal;
            var securityToken = await _securityTokenService.NullSafeIssue(principal, message.Headers.Expires);

            var storedMessage = message.WithSecurityToken(securityToken);

            if (_messageEncryptionService != null)
            {
                storedMessage = await _messageEncryptionService.Encrypt(storedMessage);
            }
            var messageFile = await MessageFile.Create(_directory, storedMessage);

            await DiagnosticService.EmitAsync(
                new FilesystemEventBuilder(this, FilesystemEventType.MessageFileCreated)
            {
                Detail  = "Message file created",
                Message = message,
                Queue   = QueueName,
                Path    = messageFile.File.FullName
            }.Build());
        }
コード例 #9
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            if (updateSource == null)
            {
                updateSource = AnalyzerService = new MyDiagnosticAnalyzerService(_listenerProvider.GetListener(FeatureAttribute.DiagnosticService));
            }

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            _workspace = workspace;

            _registrationService = workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listenerProvider, Array.Empty <Lazy <IEventListener, EventListenerMetadata> >());
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
コード例 #10
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            _workspace = workspace;

            _registrationService = (SolutionCrawlerRegistrationService)workspace.Services.GetRequiredService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            if (!_registrationService.GetTestAccessor().TryGetWorkCoordinator(workspace, out var coordinator))
            {
                throw new InvalidOperationException();
            }

            AnalyzerService   = (DiagnosticAnalyzerService?)_registrationService.GetTestAccessor().AnalyzerProviders.SelectMany(pair => pair.Value).SingleOrDefault(lazyProvider => lazyProvider.Metadata.Name == WellKnownSolutionCrawlerAnalyzers.Diagnostic && lazyProvider.Metadata.HighPriorityForActiveFile)?.Value;
            DiagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue <IDiagnosticService>();

            if (updateSource is object)
            {
                DiagnosticService.Register(updateSource);
            }

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }
        }
コード例 #11
0
        private DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            DiagnosticAnalyzerService analyzerService,
            IDiagnosticUpdateSource updateSource,
            bool createTaggerProvider)
        {
            if (updateSource == null)
            {
                updateSource = analyzerService;
            }

            this.workspace = workspace;

            this.registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            registrationService.Register(workspace);

            this.asyncListener = new AsynchronousOperationListener();
            this.listeners     = AsynchronousOperationListener.CreateListeners(
                ValueTuple.Create(FeatureAttribute.DiagnosticService, asyncListener),
                ValueTuple.Create(FeatureAttribute.ErrorSquiggles, asyncListener));

            this.analyzerService   = analyzerService;
            this.diagnosticService = new DiagnosticService(listeners);
            diagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                var taggerProvider = this.TaggerProvider;
            }

            if (analyzerService != null)
            {
                this.incrementalAnalyzers   = ImmutableArray.Create(analyzerService.CreateIncrementalAnalyzer(workspace));
                this.solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
コード例 #12
0
 public HomeController(DiagnosticService diagnosticService)
 {
     _diagnosticService = diagnosticService;
 }
コード例 #13
0
        public void ReportDiagnostics()
        {
            var service = new DiagnosticService(
                AsynchronousOperationListenerProvider.NullProvider, Array.Empty <Lazy <IEventListener, EventListenerMetadata> >());
            var source = new EditAndContinueDiagnosticUpdateSource(service);

            var updates = new List <string>();

            source.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs e) =>
            {
                updates.Add($"{e.Kind} p={e.ProjectId} d={e.DocumentId}: {string.Join(",", e.Diagnostics.Select(d => d.Id.ToString()))}");
            };

            var id = new object();

            var srcC1 = "class C1 {}";
            var srcC2 = "class C2 {}";
            var srcD1 = "class D1 {}";
            var srcD2 = "class D2 {}";
            var docC1 = new TestHostDocument(srcC1, displayName: "DocC1");
            var docC2 = new TestHostDocument(srcC2, displayName: "DocC2");
            var docD1 = new TestHostDocument(srcD1, displayName: "DocD1");
            var docD2 = new TestHostDocument(srcD2, displayName: "DocD2");

            var workspace = new TestWorkspace();
            var projC     = new TestHostProject(workspace, "ProjC");

            projC.AddDocument(docC1);
            projC.AddDocument(docC2);
            var projD = new TestHostProject(workspace, "ProjD");

            projD.AddDocument(docD1);
            projD.AddDocument(docD2);

            workspace.AddTestProject(projC);
            workspace.AddTestProject(projD);

            var treeC1 = workspace.CurrentSolution.GetDocument(docC1.Id).GetSyntaxTreeAsync().Result;
            var treeC2 = workspace.CurrentSolution.GetDocument(docC2.Id).GetSyntaxTreeAsync().Result;
            var treeD1 = workspace.CurrentSolution.GetDocument(docD1.Id).GetSyntaxTreeAsync().Result;
            var treeD2 = workspace.CurrentSolution.GetDocument(docD2.Id).GetSyntaxTreeAsync().Result;

            var diagnostics = new[]
            {
                Diagnostic.Create(new DiagnosticDescriptor("TST0001", "title1", "message1", "category", DiagnosticSeverity.Error, true), Location.Create(treeC1, new TextSpan(1, 1))),
                Diagnostic.Create(new DiagnosticDescriptor("TST0002", "title2", "message2", "category", DiagnosticSeverity.Error, true), Location.Create(treeC1, new TextSpan(1, 2))),
                Diagnostic.Create(new DiagnosticDescriptor("TST0003", "title3", "message3", "category", DiagnosticSeverity.Error, true), Location.Create(treeD1, new TextSpan(1, 2))),
                Diagnostic.Create(new DiagnosticDescriptor("TST0004", "title4", "message4", "category", DiagnosticSeverity.Error, true), Location.Create(treeD2, new TextSpan(1, 2))),
            };

            updates.Clear();
            var actual = source.ReportDiagnostics(id, workspace.CurrentSolution, projC.Id, diagnostics);

            AssertEx.Equal(new[] { docC1.Id }, actual);
            AssertEx.Equal(new[]
            {
                $"DiagnosticsCreated p={projC.Id} d={docC1.Id}: TST0001,TST0002",
                $"DiagnosticsCreated p={projC.Id} d={docD1.Id}: TST0003",
                $"DiagnosticsCreated p={projC.Id} d={docD2.Id}: TST0004"
            }, updates);

            updates.Clear();
            actual = source.ReportDiagnostics(id, workspace.CurrentSolution, projD.Id, diagnostics);
            AssertEx.SetEqual(new[] { docD1.Id, docD2.Id }, actual);
            AssertEx.Equal(new[]
            {
                $"DiagnosticsCreated p={projD.Id} d={docC1.Id}: TST0001,TST0002",
                $"DiagnosticsCreated p={projD.Id} d={docD1.Id}: TST0003",
                $"DiagnosticsCreated p={projD.Id} d={docD2.Id}: TST0004"
            }, updates);
        }
コード例 #14
0
 public VSCodeAnalyzerLoader(IDiagnosticAnalyzerService analyzerService, IDiagnosticService diagnosticService)
 {
     _analyzerService   = analyzerService;
     _diagnosticService = (DiagnosticService)diagnosticService;
 }
コード例 #15
0
        public void TestCleared()
        {
            using var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic);
            var mutex     = new ManualResetEvent(false);
            var document  = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", string.Empty);
            var document2 = document.Project.AddDocument("TestDocument2", string.Empty);

            var diagnosticService = new DiagnosticService(AsynchronousOperationListenerProvider.NullProvider);

            var source1 = new TestDiagnosticUpdateSource(support: false, diagnosticData: null);

            diagnosticService.Register(source1);

            var source2 = new TestDiagnosticUpdateSource(support: false, diagnosticData: null);

            diagnosticService.Register(source2);

            diagnosticService.DiagnosticsUpdated += MarkSet;

            // add bunch of data to the service for both sources
            RaiseDiagnosticEvent(mutex, source1, workspace, document.Project.Id, document.Id, Tuple.Create(workspace, document));
            RaiseDiagnosticEvent(mutex, source1, workspace, document.Project.Id, document.Id, Tuple.Create(workspace, document.Project, document));
            RaiseDiagnosticEvent(mutex, source1, workspace, document2.Project.Id, document2.Id, Tuple.Create(workspace, document2));

            RaiseDiagnosticEvent(mutex, source2, workspace, document.Project.Id, null, Tuple.Create(workspace, document.Project));
            RaiseDiagnosticEvent(mutex, source2, workspace, null, null, Tuple.Create(workspace));

            // confirm data is there.
            var data1 = diagnosticService.GetDiagnostics(workspace, null, null, null, false, CancellationToken.None);

            Assert.Equal(5, data1.Count());

            diagnosticService.DiagnosticsUpdated -= MarkSet;

            // confirm clear for a source
            mutex.Reset();
            var count = 0;

            diagnosticService.DiagnosticsUpdated += MarkCalled;

            source1.RaiseDiagnosticsClearedEvent();

            mutex.WaitOne();

            // confirm there are 2 data left
            var data2 = diagnosticService.GetDiagnostics(workspace, null, null, null, false, CancellationToken.None);

            Assert.Equal(2, data2.Count());

            void MarkCalled(object sender, DiagnosticsUpdatedArgs args)
            {
                // event is serialized. no concurrent call
                if (++count == 3)
                {
                    mutex.Set();
                }
            }

            void MarkSet(object sender, DiagnosticsUpdatedArgs args)
            {
                mutex.Set();
            }
        }
 protected override void Dispose(bool disposing)
 {
     DiagnosticService.RemoveSink(_diagnosticSink);
     base.Dispose(disposing);
 }
コード例 #17
0
        /// <summary>
        /// Gets diagnostics and settings info
        /// </summary>
        public IEnumerable <DiagnosticGroup> GetEnvironmentDiagnostics()
        {
            DiagnosticService service = new DiagnosticService(Umbraco);

            return(service.GetDiagnosticGroups());
        }
コード例 #18
0
 public diagnosticController(IDiagnosticRepository _diagnosticRepository)
 {
     diagnosticService = new DiagnosticService(_diagnosticRepository);
 }
コード例 #19
0
 public TargetUrlsController(DiagnosticService diagnosticService)
 {
     _diagnosticService = diagnosticService;
 }