Example #1
0
 private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message)
 {
     SendErrorNotification(
         workspace,
         SolutionExplorerShim.The_rule_set_file_could_not_be_updated,
         message);
 }
        public static async Task <Stream> RequestServiceAsync(
            Workspace workspace,
            HubClient client,
            string serviceName,
            HostGroup hostGroup,
            CancellationToken cancellationToken)
        {
            var descriptor = new ServiceDescriptor(serviceName)
            {
                HostGroup = hostGroup
            };

            try
            {
                return(await client.RequestServiceAsync(descriptor, cancellationToken).ConfigureAwait(false));
            }
            catch (Exception e) when(ReportNonFatalWatson(e, cancellationToken))
            {
                // TODO: Once https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1040692.
                // ServiceHub may throw non-cancellation exceptions if it is called after VS started to shut down,
                // even if our cancellation token is signaled. Cancel the operation and do not report an error in these cases.
                //
                // If ServiceHub did not throw non-cancellation exceptions when cancellation token is signaled,
                // we can assume that these exceptions indicate a failure and should be reported to the user.
                cancellationToken.ThrowIfCancellationRequested();

                RemoteHostCrashInfoBar.ShowInfoBar(workspace, e);

                // TODO: Propagate the original exception (see https://github.com/dotnet/roslyn/issues/40476)
                throw new SoftCrashException("Unexpected exception from HubClient", e, cancellationToken);
            }
            public RemoteHostClientService(Workspace workspace, IDiagnosticAnalyzerService analyzerService)
            {
                _gate = new object();

                _workspace = workspace;
                _analyzerService = analyzerService;
            }
            public bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory)
            {
                undoHistory = null;

                if (!(editorWorkspace is VisualStudioWorkspaceImpl) &&
                    !(editorWorkspace is MiscellaneousFilesWorkspace))
                {
                    return false;
                }

                // TODO: Handle undo if context changes
                var documentId = editorWorkspace.GetDocumentIdInCurrentContext(textBuffer.AsTextContainer());
                if (documentId == null)
                {
                    return false;
                }

                var document = GetDocument(editorWorkspace, documentId);
                if (document == null)
                {
                    return false;
                }

                undoHistory = document.GetTextUndoHistory();
                return true;
            }
 private IndentationOptions(Workspace workspace)
 {
     var options = workspace.Options;
     this.IndentationSize = options.GetOption(FormattingOptions.IndentationSize, LanguageNames.CSharp);
     this.TabSize = options.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp);
     this.UseTabs = options.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp);
 }
Example #6
0
        public static void Enable(Workspace workspace, Options options)
        {
            var service = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();

            workspace.Options = GetOptions(workspace, options);
            service.Register(workspace);
        }
Example #7
0
        protected AbstractTable(Workspace workspace, ITableManagerProvider provider, string tableIdentifier)
        {
            _workspace = workspace;
            _provider = provider;

            this.TableManager = provider.GetTableManager(tableIdentifier);
        }
        private SourceReferenceTreeItem(
            Document document, TextSpan sourceSpan, ushort glyphIndex, int commonPathElements)
            : base(glyphIndex)
        {
            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.

            _workspace   = document.Project.Solution.Workspace;
            _documentId  = document.Id;
            _projectName = document.Project.Name;
            _filePath    = GetFilePath(document, commonPathElements);
            _sourceSpan  = sourceSpan;

            var text     = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(_sourceSpan.Start);

            _textLineString = textLine.ToString();

            _lineNumber = textLine.LineNumber;
            _offset     = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);
            var succeeded             = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, _documentId, out var spanInPrimaryBuffer);

            _mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            _mappedOffset     = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;
        }
Example #9
0
        public IList<TextChange> FormatToken(Workspace workspace, SyntaxToken token, CancellationToken cancellationToken)
        {
            Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None || token.Kind() == SyntaxKind.EndOfFileToken);

            // get previous token
            var previousToken = token.GetPreviousToken(includeZeroWidth: true);
            if (previousToken.Kind() == SyntaxKind.None)
            {
                // no previous token. nothing to format
                return SpecializedCollections.EmptyList<TextChange>();
            }

            // This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios (see Devdiv:823958).
            // Formatter uses FindToken on the position, which returns token to left, if there is nothing to the right and returns token to the right
            // if there exists one. If the shape is "{|}", we're including '}' in the formatting range. Avoid doing that to improve verbatim typing
            // in the following special scenarios.  
            int adjustedEndPosition = token.Span.End;
            if (token.IsKind(SyntaxKind.OpenBraceToken) &&
                (token.Parent.IsInitializerForArrayOrCollectionCreationExpression() ||
                    token.Parent is AnonymousObjectCreationExpressionSyntax))
            {
                var nextToken = token.GetNextToken(includeZeroWidth: true);
                if (nextToken.IsKind(SyntaxKind.CloseBraceToken))
                {
                    // Format upto '{' and exclude '}'
                    adjustedEndPosition = token.SpanStart;
                }
            }

            var smartTokenformattingRules = (new SmartTokenFormattingRule()).Concat(_formattingRules);
            return Formatter.GetFormattedTextChanges(_root, new TextSpan[] { TextSpan.FromBounds(previousToken.SpanStart, adjustedEndPosition) }, workspace, _optionSet, smartTokenformattingRules, cancellationToken);
        }
        public static async Task <RemoteHostClient> CreateAsync(
            Workspace workspace, CancellationToken cancellationToken)
        {
            try
            {
                using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken))
                {
                    var primary = new HubClient("ManagedLanguage.IDE.RemoteHostClient");
                    var timeout = TimeSpan.FromMilliseconds(workspace.Options.GetOption(RemoteHostOptions.RequestServiceTimeoutInMS));

                    // Retry (with timeout) until we can connect to RemoteHost (service hub process).
                    // we are seeing cases where we failed to connect to service hub process when a machine is under heavy load.
                    // (see https://devdiv.visualstudio.com/DevDiv/_workitems/edit/481103 as one of example)
                    var instance = await Connections.RetryRemoteCallAsync <IOException, ServiceHubRemoteHostClient>(
                        workspace, () => CreateWorkerAsync(workspace, primary, timeout, cancellationToken), timeout, cancellationToken).ConfigureAwait(false);

                    instance.Started();

                    // return instance
                    return(instance);
                }
            }
            catch (SoftCrashException)
            {
                // at this point, we should have shown info bar (RemoteHostCrashInfoBar.ShowInfoBar) to users
                // returning null here will disable OOP for this VS session.
                // * Note * this is not trying to recover the exception. but giving users to time
                // to clean up before restart VS
                return(null);
            }
        }
            public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default)
            {
                var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace;

                if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName()))
                {
                    // We failed to add the reference, which means the project system wasn't able to bind.
                    // We'll pop up the Add Reference dialog to let the user figure this out themselves.
                    // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix


                    if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy)
                    {
                        var command = new OLECMD[1];
                        command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE;

                        if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero)))
                        {
                            if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0)
                            {
                                uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero);
                            }
                        }
                    }
                }
            }
Example #12
0
        /// <summary>
        /// Load a text and a version of the document in the workspace.
        /// </summary>
        /// <exception cref="IOException"></exception>
        public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path);

            TextAndVersion textAndVersion;

            // Open file for reading with FileShare mode read/write/delete so that we do not lock this file.
            using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: true)))
            {
                var version = VersionStamp.Create(prevLastWriteTime);

                // we do this so that we asynchronously read from file. and this should allocate less for IDE case. 
                // but probably not for command line case where it doesn't use more sophisticated services.
                using (var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    var text = CreateText(readStream, workspace);
                    textAndVersion = TextAndVersion.Create(text, version, _path);
                }
            }

            // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was
            // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read.
            // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us
            // and reload the file.
            DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
            if (!newLastWriteTime.Equals(prevLastWriteTime))
            {
                var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path);
                throw new IOException(message);
            }

            return textAndVersion;
        }
        internal /*for testing purposes*/ SonarAnalyzerManager(IServiceProvider serviceProvider, Workspace workspace,
            ISolutionAnalysisRequester solutionAnalysisRequester)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            this.workspace = workspace;
            this.activeSolutionBoundTracker = serviceProvider.GetMefService<IActiveSolutionBoundTracker>();

            if (this.activeSolutionBoundTracker == null)
            {
                Debug.Fail($"Could not get {nameof(IActiveSolutionBoundTracker)}");
            }

            this.solutionAnalysisRequester = solutionAnalysisRequester;
            this.activeSolutionBoundTracker.SolutionBindingChanged += this.ActiveSolutionBoundTracker_SolutionBindingChanged;

            SonarAnalysisContext.ShouldAnalysisBeDisabled =
                tree => ShouldAnalysisBeDisabledOnTree(tree);
        }
 private static MemberDeclarationSyntax GenerateBackingField(ITypeSymbol typeSymbol, string backingFieldName, Workspace workspace)
 {
     var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
     SyntaxNode type = generator.TypeExpression(typeSymbol);
     FieldDeclarationSyntax fieldDecl = ParseMember($"private _field_Type_ {backingFieldName};") as FieldDeclarationSyntax;
     return fieldDecl.ReplaceNode(fieldDecl.Declaration.Type, type.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation)); 
 }
Example #15
0
        public static IEnumerable<ClassifiedSpan> GetClassifiedSpans(
            SemanticModel semanticModel,
            TextSpan textSpan,
            Workspace workspace,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<IClassificationService>();

            var syntaxClassifiers = service.GetDefaultSyntaxClassifiers();

            var extensionManager = workspace.GetExtensionManager();
            var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(syntaxClassifiers, c => c.SyntaxNodeTypes);
            var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(syntaxClassifiers, c => c.SyntaxTokenKinds);

            var syntacticClassifications = new List<ClassifiedSpan>();
            var semanticClassifications = new List<ClassifiedSpan>();

            service.AddSyntacticClassifications(semanticModel.SyntaxTree, textSpan, syntacticClassifications, cancellationToken);
            service.AddSemanticClassifications(semanticModel, textSpan, workspace, getNodeClassifiers, getTokenClassifiers, semanticClassifications, cancellationToken);

            var allClassifications = new List<ClassifiedSpan>(semanticClassifications.Where(s => s.TextSpan.OverlapsWith(textSpan)));
            var semanticSet = semanticClassifications.Select(s => s.TextSpan).ToSet();

            allClassifications.AddRange(syntacticClassifications.Where(
                s => s.TextSpan.OverlapsWith(textSpan) && !semanticSet.Contains(s.TextSpan)));
            allClassifications.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);

            return allClassifications;
        }
Example #16
0
        /// <summary>
        /// For testing purposes only.
        /// </summary>
        internal SymbolSearchService(
            Workspace workspace,
            IPackageInstallerService installerService,
            IRemoteControlService remoteControlService,
            ILogService logService,
            IDelayService delayService,
            IIOService ioService,
            IPatchService patchService,
            IDatabaseFactoryService databaseFactoryService,
            string localSettingsDirectory,
            Func<Exception, bool> reportAndSwallowException,
            CancellationTokenSource cancellationTokenSource)
        {
            if (remoteControlService == null)
            {
                // If we can't access the file update service, then there's nothing we can do.
                return;
            }

            _workspace = workspace;
            _installerService = installerService;
            _delayService = delayService;
            _ioService = ioService;
            _logService = logService;
            _remoteControlService = remoteControlService;
            _patchService = patchService;
            _databaseFactoryService = databaseFactoryService;
            _localSettingsDirectory = localSettingsDirectory;
            _reportAndSwallowException = reportAndSwallowException;

            _cancellationTokenSource = cancellationTokenSource;
            _cancellationToken = _cancellationTokenSource.Token;
        }
Example #17
0
        public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            DateTime prevLastWriteTime = File.GetLastWriteTimeUtc(this.path);

            // Open file for reading with FileShare mode read/write/delete so that we do not lock this file.
            // Allowing other theads/processes to write or delete the file is essential for scenarios such as
            // Rename refactoring where File.Replace API is invoked for updating the modified file. 
            TextAndVersion textAndVersion;
            using (var stream = File.Open(this.path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            {
                var version = VersionStamp.Create(prevLastWriteTime);
                var memoryStream = await this.ReadStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);

                var text = CreateText(memoryStream, workspace);
                textAndVersion = TextAndVersion.Create(text, version, path);
            }

            // this has a potential to return corrupted state text if someone changed text in the middle of us reading it.
            // previously, we attempted to detect such case and return empty string with workspace failed event. 
            // but that is nothing better or even worse than returning what we have read so far.
            //
            // I am letting it to return what we have read so far. and hopefully, file change event let us re-read this file.
            // (* but again, there is still a chance where file change event happens even before writing has finished which ends up
            //    let us stay in corrupted state)
            DateTime newLastWriteTime = File.GetLastWriteTimeUtc(this.path);
            if (!newLastWriteTime.Equals(prevLastWriteTime))
            {
                // TODO: remove this once we know how often this can happen.
                //       I am leaving this here for now for diagnostic purpose.
                var message = string.Format(WorkspacesResources.FileWasExternallyModified, this.path);
                workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.FileAccessFailure, message, documentId));
            }

            return textAndVersion;
        }
 private MiscellaneousDiagnosticListTable(
     SVsServiceProvider serviceProvider, Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider) :
     base(serviceProvider, workspace, diagnosticService, provider)
 {
     _source = new LiveTableDataSource(serviceProvider, workspace, diagnosticService, IdentifierString);
     AddInitialTableSource(workspace.CurrentSolution, _source);
 }
Example #19
0
        public SourceListItem(Document document, TextSpan sourceSpan, ushort glyphIndex)
            : base(glyphIndex)
        {
            _workspace = document.Project.Solution.Workspace;

            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.
            _documentId = document.Id;

            var filePath = document.FilePath;

            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(sourceSpan.Start);

            _lineNumber = textLine.LineNumber;
            _offset = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);

            VsTextSpan spanInPrimaryBuffer;
            var succeeded = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, document.Id, out spanInPrimaryBuffer);

            var mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            var mappedOffset = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;

            SetDisplayProperties(filePath, mappedLineNumber, mappedOffset, _lineNumber, _offset, textLine.ToString(), sourceSpan.Length);
        }
        public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure)
        {
            var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
            if (visualStudioWorkspace != null)
            {
                foreach (var documentId in changedDocumentIDs)
                {
                    var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument;
                    if (containedDocument != null)
                    {
                        var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost;
                        if (containedLanguageHost != null)
                        {
                            var hresult = containedLanguageHost.OnRenamed(
                                GetRenameType(symbol), symbol.ToDisplayString(s_qualifiedDisplayFormat), newName);
                            if (hresult < 0)
                            {
                                if (throwOnFailure)
                                {
                                    Marshal.ThrowExceptionForHR(hresult);
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }

            return true;
        }
Example #21
0
 public SolutionServices(Workspace workspace)
 {
     this.Workspace = workspace;
     this.TemporaryStorage = workspace.Services.GetService<ITemporaryStorageService>();
     this.MetadataService = workspace.Services.GetService<IMetadataService>();
     this.CacheService = workspace.Services.GetService<IProjectCacheHostService>();
 }
        internal static void LogSession(Workspace workspace, LinkedFileDiffMergingSessionInfo sessionInfo)
        {
            if (sessionInfo.LinkedFileGroups.Count > 1)
            {
                LogNewSessionWithLinkedFiles();
                LogNumberOfLinkedFileGroupsProcessed(sessionInfo.LinkedFileGroups.Count);

                foreach (var groupInfo in sessionInfo.LinkedFileGroups)
                {
                    LogNumberOfIdenticalDiffs(groupInfo.IdenticalDiffs);
                    LogNumberOfIsolatedDiffs(groupInfo.IsolatedDiffs);
                    LogNumberOfOverlappingDistinctDiffs(groupInfo.OverlappingDistinctDiffs);
                    LogNumberOfOverlappingDistinctDiffsWithSameSpan(groupInfo.OverlappingDistinctDiffsWithSameSpan);
                    LogNumberOfOverlappingDistinctDiffsWithSameSpanAndSubstringRelation(groupInfo.OverlappingDistinctDiffsWithSameSpanAndSubstringRelation);
                    LogNumberOfInsertedMergeConflictComments(groupInfo.InsertedMergeConflictComments);
                    LogNumberOfInsertedMergeConflictCommentsAtAdjustedLocation(groupInfo.InsertedMergeConflictCommentsAtAdjustedLocation);

                    if (groupInfo.InsertedMergeConflictComments > 0 ||
                        groupInfo.InsertedMergeConflictCommentsAtAdjustedLocation > 0)
                    {
                        Logger.Log(FunctionId.Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup, SessionLogMessage.Create(groupInfo));
                    }
                }
            }
        }
Example #23
0
        public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(
            this VsTextSpan spanInSecondaryBuffer,
            Microsoft.CodeAnalysis.Workspace workspace,
            DocumentId documentId,
            out VsTextSpan spanInPrimaryBuffer
            )
        {
            spanInPrimaryBuffer = default;

            if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace))
            {
                return(false);
            }

            var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId);

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

            var bufferCoordinator = containedDocument.BufferCoordinator;

            var primary = new VsTextSpan[1];
            var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(
                spanInSecondaryBuffer,
                primary
                );

            spanInPrimaryBuffer = primary[0];

            return(ErrorHandler.Succeeded(hresult));
        }
Example #24
0
        public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer)
        {
            spanInPrimaryBuffer = default(VsTextSpan);

            var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
            if (visualStudioWorkspace == null)
            {
                return false;
            }

            var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument;
            if (containedDocument == null)
            {
                return false;
            }

            var bufferCoordinator = containedDocument.ContainedLanguage.BufferCoordinator;

            var primary = new VsTextSpan[1];
            var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary);

            spanInPrimaryBuffer = primary[0];

            return ErrorHandler.Succeeded(hresult);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompilationContext"/> class.
        /// </summary>
        public CompilationContext(Workspace workspace, Document currentDocument)
        {
            Workspace = workspace;
            CurrentDocument = currentDocument;

            DocumentEditor = DocumentEditor.CreateAsync(currentDocument).Result;
        }
        public static async Task<RemoteHostClient> CreateAsync(
            Workspace workspace, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken))
            {
                var primary = new HubClient("ManagedLanguage.IDE.RemoteHostClient");
                var remoteHostStream = await primary.RequestServiceAsync(WellKnownRemoteHostServices.RemoteHostService, cancellationToken).ConfigureAwait(false);

                var instance = new ServiceHubRemoteHostClient(workspace, primary, remoteHostStream);

                // make sure connection is done right
                var current = $"VS ({Process.GetCurrentProcess().Id})";
                var host = await instance._rpc.InvokeAsync<string>(WellKnownRemoteHostServices.RemoteHostService_Connect, current).ConfigureAwait(false);

                // TODO: change this to non fatal watson and make VS to use inproc implementation
                Contract.ThrowIfFalse(host == current.ToString());

                instance.Connected();

                // Create a workspace host to hear about workspace changes.  We'll 
                // remote those changes over to the remote side when they happen.
                RegisterWorkspaceHost(workspace, instance);

                // return instance
                return instance;
            }
        }
Example #27
0
        public static async Task<IEnumerable<LinePositionSpanTextChange>> GetFormattingChangesAfterKeystroke(Workspace workspace, OptionSet options, Document document, int position, char character)
        {
            var tree = await document.GetSyntaxTreeAsync();

            if (character == '\n')
            {
                // format previous line on new line
                var lines = (await document.GetTextAsync()).Lines;
                var targetLine = lines[lines.GetLineFromPosition(position).LineNumber - 1];
                if (!string.IsNullOrWhiteSpace(targetLine.Text.ToString(targetLine.Span)))
                {
                    return await GetFormattingChangesForRange(workspace, options, document, targetLine.Start, targetLine.End);
                }
            }
            else if (character == '}' || character == ';')
            {
                // format after ; and }
                var node = FindFormatTarget(tree, position);
                if (node != null)
                {
                    return await GetFormattingChangesForRange(workspace, options, document, node.FullSpan.Start, node.FullSpan.End);
                }
            }

            return Enumerable.Empty<LinePositionSpanTextChange>();
        }
Example #28
0
        public AbstractSourceTreeItem(Document document, TextSpan sourceSpan, ushort glyphIndex, int commonPathElements = 0)
            : base(glyphIndex)
        {
            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.

            _workspace = document.Project.Solution.Workspace;
            _documentId = document.Id;
            _projectName = document.Project.Name;
            _filePath = GetFilePath(document, commonPathElements);
            _sourceSpan = sourceSpan;

            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(_sourceSpan.Start);
            _textLineString = textLine.ToString();

            _lineNumber = textLine.LineNumber;
            _offset = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);

            VsTextSpan spanInPrimaryBuffer;
            var succeeded = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, _documentId, out spanInPrimaryBuffer);

            _mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            _mappedOffset = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;
        }
Example #29
0
        /// <summary>
        /// Register a workspace as the primary workspace. Only one workspace can be the primary.
        /// </summary>
        public static void Register(Workspace workspace)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException("workspace");
            }

            using (s_registryGate.DisposableWrite())
            {
                s_primaryWorkspace = workspace;

                foreach (var taskSource in s_primaryWorkspaceTaskSourceList)
                {
                    try
                    {
                        taskSource.TrySetResult(workspace);
                    }
                    catch
                    {
                    }
                }

                s_primaryWorkspaceTaskSourceList.Clear();
            }
        }
        public static IOleUndoManager TryGetUndoManager(
            this IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            Microsoft.CodeAnalysis.Workspace workspace,
            DocumentId contextDocumentId,
            CancellationToken cancellationToken)
        {
            // https://github.com/dotnet/roslyn/issues/17898
            // We have a report of a null ref occurring in this method. The only place we believe
            // this could be would be if 'document' was null. Try to catch a reasonable
            // non -fatal-watson dump to help track down what the root cause of this might be.
            var document = workspace.CurrentSolution.GetDocument(contextDocumentId);

            if (document == null)
            {
                var message = contextDocumentId == null
                    ? $"{nameof(contextDocumentId)} was null."
                    : $"{nameof(contextDocumentId)} was not null.";

                FatalError.ReportWithoutCrash(new InvalidOperationException("Could not retrieve document. " + message));

                return(null);
            }

            var text         = document.GetTextSynchronously(cancellationToken);
            var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
            var textBuffer   = textSnapshot?.TextBuffer;

            return(editorAdaptersFactoryService.TryGetUndoManager(textBuffer));
        }
        public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
        {
            var folders = new List<string>();

            if (workspace is VisualStudioWorkspaceImpl)
            {
                ((VisualStudioWorkspaceImpl)workspace).GetProjectData(projectId, out var ivisualStudioHostProject, out var hierarchy, out var envDTEProject);

                var projectItems = envDTEProject.ProjectItems;

                var projectItemsStack = new Stack<Tuple<ProjectItem, string>>();

                // Populate the stack
                projectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, "\\")));
                while (projectItemsStack.Count != 0)
                {
                    var projectItemTuple = projectItemsStack.Pop();
                    var projectItem = projectItemTuple.Item1;
                    var currentFolderPath = projectItemTuple.Item2;

                    var folderPath = currentFolderPath + projectItem.Name + "\\";

                    folders.Add(folderPath);
                    projectItem.ProjectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, folderPath)));
                }
            }

            return folders;
        }
        public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
        {
            this.AssertIsForeground();

            if (project.Language == LanguageNames.VisualBasic)
            {
                return "";
            }

            var folders = new List<string>();
            var defaultNamespace = "";

            if (workspace is VisualStudioWorkspaceImpl)
            {
                ((VisualStudioWorkspaceImpl)workspace).GetProjectData(project.Id, out var ivisualStudioHostProject, out var hierarchy, out var envDTEProject);

                try
                {
                    defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
                }
                catch (ArgumentException)
                {
                    // DefaultNamespace does not exist for this project.
                }
            }

            return defaultNamespace;
        }
 public static async Task<string> GetFormattedDocument(Workspace workspace, OptionSet options, Document document)
 {
     var formattedDocument = await Formatter.FormatAsync(document, options);
     var newText = (await formattedDocument.GetTextAsync()).ToString();
     newText = EnsureProperNewLine(newText, options);
     return newText;
 }
        private static Document GetCodeAnalysisDocumentFromDteDocument(EnvDTE.Document activeDocument, Workspace workspace)
        {
            var documentId = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName).FirstOrDefault();
            if (documentId == null) return null;

            return workspace.CurrentSolution.GetDocument(documentId);
        }
Example #35
0
        private void ConditionallyCollapseOutliningRegions(
            IVsTextView textView,
            IWpfTextView wpfTextView,
            Microsoft.CodeAnalysis.Workspace workspace,
            bool isOpenMetadataAsSource
            )
        {
            var outliningManagerService =
                this.Package.ComponentModel.GetService <IOutliningManagerService>();
            var outliningManager = outliningManagerService.GetOutliningManager(wpfTextView);

            if (outliningManager == null)
            {
                return;
            }

            if (
                !workspace.Options.GetOption(FeatureOnOffOptions.Outlining, this.RoslynLanguageName)
                )
            {
                outliningManager.Enabled = false;
            }
            else
            {
                if (textView is IVsTextViewEx viewEx)
                {
                    if (isOpenMetadataAsSource)
                    {
                        // If this file is a metadata-from-source file, we want to force-collapse any implementations.
                        // First make sure we know what all the outlining spans are.  Then ask the outlining mananger
                        // to collapse all the implementation spans.
                        EnsureOutliningTagsComputed(wpfTextView);
                        outliningManager.CollapseAll(
                            wpfTextView.TextBuffer.CurrentSnapshot.GetFullSpan(),
                            c => c.Tag.IsImplementation
                            );
                    }
                    else
                    {
                        // We also want to automatically collapse any region tags *on the first
                        // load of a file* if the file contains them.  In order to not do expensive
                        // parsing, we only do this if the file contains #region in it.
                        if (ContainsRegionTag(wpfTextView.TextSnapshot))
                        {
                            // Make sure we at least know what the outlining spans are.
                            // Then when we call PersistOutliningState below the editor will
                            // get these outlining tags and automatically collapse any
                            // IsDefaultCollapsed spans the first time around.
                            //
                            // If it is not the first time opening a file, VS will simply use
                            // the data stored in the SUO file.
                            EnsureOutliningTagsComputed(wpfTextView);
                        }

                        viewEx.PersistOutliningState();
                    }
                }
            }
        }
Example #36
0
        public APMRefactoring(Solution originalSolution, Workspace workspace)
        {
            _workspace = workspace;
            if (originalSolution == null) throw new ArgumentNullException("originalSolution");
            if (workspace == null) throw new ArgumentNullException("workspace");

            OriginalSolution = originalSolution;
        }
 public WorkspaceManager(Microsoft.CodeAnalysis.Workspace workspace)
 {
     workspace.WorkspaceChanged += WorkspaceChanged;
     if (workspace.CurrentSolution != null)
     {
         Task.Run(() => AddToCacheAsync(workspace.CurrentSolution.Projects));
     }
 }
		public static async Task<long> GetSolutionSizeAsync (Workspace workspace, SolutionId id, CancellationToken cancellationToken)
		{
			long result = 0;
			foreach (var project in workspace.CurrentSolution.Projects) {
				result += await GetProjectSizeAsync (project, cancellationToken);
			}
			return result;
		}
 public RoslynSolutionWatcher(DTE dte, Workspace workspace, ICoverageStore coverageStore, IRewrittenDocumentsStorage rewrittenDocumentsStorage, ITaskCoverageManager taskCoverageManager)
 {
     _dte = dte;
     _workspace = workspace;
     _coverageStore = coverageStore;
     _rewrittenDocumentsStorage = rewrittenDocumentsStorage;
     _taskCoverageManager = taskCoverageManager;
 }
Example #40
0
        private void SendErrorNotification(Workspace workspace, string message1, string message2)
        {
            var notificationService = workspace.Services.GetService <INotificationService>();

            notificationService.SendNotification(
                message1 + Environment.NewLine + Environment.NewLine + message2,
                severity: NotificationSeverity.Error
                );
        }
Example #41
0
        public RemotableDataJsonRpc(Microsoft.CodeAnalysis.Workspace workspace, Stream stream)
            : base(stream, callbackTarget: null, useThisAsCallback: true)
        {
            _remotableDataService = workspace.Services.GetService <IRemotableDataService>();

            _shutdownCancellationSource = new CancellationTokenSource();

            StartListening();
        }
Example #42
0
    public TextAdornment1(Microsoft.VisualStudio.Text.Editor.IWpfTextView view)
    {
        var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));

        Workspace = componentModel.GetService <Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>();

        View = view;
        View.LayoutChanged += OnLayoutChanged;
    }
Example #43
0
        private Workspace TryGetWorkspace()
        {
            if (_workspace == null)
            {
                var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
                _workspace = componentModel.DefaultExportProvider.GetExportedValueOrDefault <VisualStudioWorkspace>();
            }

            return(_workspace);
        }
Example #44
0
        public IIncrementalAnalyzer CreateIncrementalAnalyzer(Microsoft.CodeAnalysis.Workspace workspace)
        {
            var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;

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

            return(new Analyzer(_notificationService, _listener, visualStudioWorkspace));
        }
Example #45
0
        public MonoDevelopAnalyzer(FilePath fullPath, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, ProjectId projectId, Microsoft.CodeAnalysis.Workspace workspace, IAnalyzerAssemblyLoader loader, string language)
        {
            FullPath = fullPath;
            _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource;
            _projectId = projectId;
            _workspace = workspace;
            _loader    = loader;
            _language  = language;

            FileService.FileChanged += OnUpdatedOnDisk;
        }
Example #46
0
 private void ApplyChanges(Microsoft.CodeAnalysis.Workspace workspace, Document document)
 {
     if (IsBatchOpen)
     {
         _batchDocument = document;
     }
     else
     {
         workspace.TryApplyChanges(document.Project.Solution);
     }
 }
Example #47
0
        public string GetProjectType(Microsoft.CodeAnalysis.Workspace workspace, ProjectId projectId)
        {
            if (workspace == null || projectId == null)
            {
                return(string.Empty);
            }

            var vsWorkspace = workspace as VisualStudioWorkspaceImpl;
            var project     = vsWorkspace?.GetHostProject(projectId) as AbstractLegacyProject;

            return(project?.ProjectType ?? string.Empty);
        }
            public void AddWorkspace(Microsoft.CodeAnalysis.Workspace ws, CancellationToken token)
            {
                workspaces.Add(ws);
                ws.WorkspaceChanged += Ws_WorkspaceChanged;

                foreach (var p in ws.CurrentSolution.Projects)
                {
                    if (p.FilePath.EndsWith("csproj", StringComparison.Ordinal))
                    {
                        SearchAsync(documentInfos, p, token);
                    }
                }
            }
Example #49
0
        private Workspace TryGetWorkspace()
        {
            if (_workspace == null)
            {
                var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
                var provider       = componentModel.DefaultExportProvider.GetExportedValueOrDefault <ISolutionExplorerWorkspaceProvider>();
                if (provider != null)
                {
                    _workspace = provider.GetWorkspace();
                }
            }

            return(_workspace);
        }
        public static async Task <ServiceHubRemoteHostClient> CreateWorkerAsync(Workspace workspace, HubClient primary, TimeSpan timeout, CancellationToken cancellationToken)
        {
            ServiceHubRemoteHostClient client = null;

            try
            {
                // let each client to have unique id so that we can distinguish different clients when service is restarted
                var current = CreateClientId(Process.GetCurrentProcess().Id.ToString());

                var hostGroup = new HostGroup(current);

                // Create the RemotableDataJsonRpc before we create the remote host: this call implicitly sets up the remote IExperimentationService so that will be available for later calls
                var remotableDataRpc = new RemotableDataJsonRpc(
                    workspace, primary.Logger,
                    await Connections.RequestServiceAsync(workspace, primary, WellKnownServiceHubServices.SnapshotService, hostGroup, timeout, cancellationToken).ConfigureAwait(false));

                var remoteHostStream = await Connections.RequestServiceAsync(workspace, primary, WellKnownRemoteHostServices.RemoteHostService, hostGroup, timeout, cancellationToken).ConfigureAwait(false);

                var enableConnectionPool = workspace.Options.GetOption(RemoteHostOptions.EnableConnectionPool);
                var maxConnection        = workspace.Options.GetOption(RemoteHostOptions.MaxPoolConnection);

                var connectionManager = new ConnectionManager(primary, hostGroup, enableConnectionPool, maxConnection, timeout, new ReferenceCountedDisposable <RemotableDataJsonRpc>(remotableDataRpc));

                client = new ServiceHubRemoteHostClient(workspace, primary.Logger, connectionManager, remoteHostStream);

                var uiCultureLCID = CultureInfo.CurrentUICulture.LCID;
                var cultureLCID   = CultureInfo.CurrentCulture.LCID;

                // make sure connection is done right
                var host = await client._rpc.InvokeWithCancellationAsync <string>(
                    nameof(IRemoteHostService.Connect), new object[] { current, uiCultureLCID, cultureLCID, TelemetryService.DefaultSession.SerializeSettings() }, cancellationToken).ConfigureAwait(false);

                return(client);
            }
            catch (ConnectionLostException ex)
            {
                RemoteHostCrashInfoBar.ShowInfoBar(workspace, ex);

                Shutdown(client, ex, cancellationToken);

                // dont crash VS because OOP is failed to start. we will show info bar telling users to restart
                // but never physically crash VS.
                throw new SoftCrashException("Connection Lost", ex, cancellationToken);
            }
            catch (Exception ex)
            {
                Shutdown(client, ex, cancellationToken);
                throw;
            }
        public static async Task <RemoteHostClient?> CreateAsync(Workspace workspace, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken))
            {
                var enableConnectionPool = workspace.Options.GetOption(RemoteHostOptions.EnableConnectionPool);
                var maxConnection        = workspace.Options.GetOption(RemoteHostOptions.MaxPoolConnection);

                // let each client to have unique id so that we can distinguish different clients when service is restarted
                var clientId = CreateClientId(Process.GetCurrentProcess().Id.ToString());

                var hostGroup = new HostGroup(clientId);
                var hubClient = new HubClient("ManagedLanguage.IDE.RemoteHostClient");

                // use the hub client logger for unexpected exceptions from devenv as well, so we have complete information in the log:
                WatsonReporter.InitializeLogger(hubClient.Logger);

                var remoteHostStream = await RequestServiceAsync(workspace, hubClient, WellKnownRemoteHostServices.RemoteHostService, hostGroup, cancellationToken).ConfigureAwait(false);

                var connectionManager = new ConnectionManager(workspace, hubClient, hostGroup, enableConnectionPool, maxConnection);

                var client = new ServiceHubRemoteHostClient(workspace, hubClient.Logger, connectionManager, remoteHostStream);

                var uiCultureLCID = CultureInfo.CurrentUICulture.LCID;
                var cultureLCID   = CultureInfo.CurrentCulture.LCID;

                bool success = false;
                try
                {
                    // initialize the remote service
                    _ = await client._endPoint.InvokeAsync <string>(
                        nameof(IRemoteHostService.Connect),
                        new object[] { clientId, uiCultureLCID, cultureLCID, TelemetryService.DefaultSession.SerializeSettings() },
                        cancellationToken).ConfigureAwait(false);

                    success = true;
                }
                finally
                {
                    if (!success)
                    {
                        client.Dispose();
                    }
                }

                client.Started();
                return(client);
            }
        }
        public static LinePosition GetAdjustedLineColumn(Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, int originalLine, int originalColumn, int mappedLine, int mappedColumn)
        {
            var vsWorkspace = workspace as VisualStudioWorkspaceImpl;

            if (vsWorkspace == null)
            {
                return(new LinePosition(mappedLine, mappedColumn));
            }

            if (TryAdjustSpanIfNeededForVenus(vsWorkspace, documentId, originalLine, originalColumn, out var span))
            {
                return(span.MappedLinePosition);
            }

            return(new LinePosition(mappedLine, mappedColumn));
        }
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            TraceSource logger,
            ConnectionManager connectionManager,
            Stream stream)
            : base(workspace)
        {
            _shutdownCancellationTokenSource = new CancellationTokenSource();

            _connectionManager = connectionManager;

            _endPoint = new RemoteEndPoint(stream, logger, incomingCallTarget: this);
            _endPoint.Disconnected += OnDisconnected;
            _endPoint.UnexpectedExceptionThrown += OnUnexpectedExceptionThrown;
            _endPoint.StartListening();
        }
Example #54
0
        public static async Task <ServiceHubRemoteHostClient> CreateWorkerAsync(Workspace workspace, HubClient primary, TimeSpan timeout, CancellationToken cancellationToken)
        {
            ServiceHubRemoteHostClient client = null;

            try
            {
                // let each client to have unique id so that we can distinguish different clients when service is restarted
                var current = CreateClientId(Process.GetCurrentProcess().Id.ToString());

                var hostGroup = new HostGroup(current);

                // Create the RemotableDataJsonRpc before we create the remote host: this call implicitly sets up the remote IExperimentationService so that will be available for later calls
                var remotableDataRpc = new RemotableDataJsonRpc(
                    workspace, primary.Logger,
                    await Connections.RequestServiceAsync(workspace, primary, WellKnownServiceHubServices.SnapshotService, hostGroup, timeout, cancellationToken).ConfigureAwait(false));

                var remoteHostStream = await Connections.RequestServiceAsync(workspace, primary, WellKnownRemoteHostServices.RemoteHostService, hostGroup, timeout, cancellationToken).ConfigureAwait(false);

                var enableConnectionPool = workspace.Options.GetOption(RemoteHostOptions.EnableConnectionPool);
                var maxConnection        = workspace.Options.GetOption(RemoteHostOptions.MaxPoolConnection);

                var connectionManager = new ConnectionManager(primary, hostGroup, enableConnectionPool, maxConnection, timeout, new ReferenceCountedDisposable <RemotableDataJsonRpc>(remotableDataRpc));

                client = new ServiceHubRemoteHostClient(workspace, primary.Logger, connectionManager, remoteHostStream);

                var uiCultureLCID = CultureInfo.CurrentUICulture.LCID;
                var cultureLCID   = CultureInfo.CurrentCulture.LCID;

                // make sure connection is done right
                var host = await client._rpc.InvokeWithCancellationAsync <string>(
                    nameof(IRemoteHostService.Connect), new object[] { current, uiCultureLCID, cultureLCID, TelemetryService.DefaultSession.SerializeSettings() }, cancellationToken).ConfigureAwait(false);

                return(client);
            }
            catch (Exception ex)
            {
                // make sure we shutdown client if initializing client has failed.
                client?.Shutdown();

                // translate to our own cancellation if it is raised.
                cancellationToken.ThrowIfCancellationRequested();

                // otherwise, report watson and throw original exception
                ex.ReportServiceHubNFW("ServiceHub creation failed");
                throw;
            }
        }
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            ConnectionManager connectionManager,
            Stream stream)
            : base(workspace)
        {
            _shutdownCancellationTokenSource = new CancellationTokenSource();

            _connectionManager = connectionManager;

            _rpc = new JsonRpc(new JsonRpcMessageHandler(stream, stream), target: this);
            _rpc.JsonSerializer.Converters.Add(AggregateJsonConverter.Instance);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
Example #56
0
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            TraceSource logger,
            ConnectionManager connectionManager,
            Stream stream)
            : base(workspace)
        {
            _shutdownCancellationTokenSource = new CancellationTokenSource();

            _connectionManager = connectionManager;

            _rpc = stream.CreateStreamJsonRpc(target: this, logger);

            // handle disconnected situation
            _rpc.Disconnected += OnRpcDisconnected;

            _rpc.StartListening();
        }
Example #57
0
        public WorkspaceManager(Microsoft.CodeAnalysis.Workspace workspace)
        {
            watcher = new FileSystemWatcher
            {
                NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.FileName,
                IncludeSubdirectories = true,
                Filter = "*.csproj"
            };

            watcher.Changed += (s, e) => UpdateProjectDescription(e.FullPath);
            watcher.Renamed += (s, e) => UpdateProjectDescription(e.FullPath);

            workspace.WorkspaceChanged += WorkspaceChanged;
            if (workspace.CurrentSolution != null)
            {
#pragma warning disable VSTHRD110 // Observe result of async calls
                Task.Run(() => AddToCache(workspace.CurrentSolution));
#pragma warning restore VSTHRD110 // Observe result of async calls
            }
        }
        public static DocumentId GetDocumentId(Microsoft.CodeAnalysis.Workspace workspace, MonoDevelop.Projects.Project project, string fileName)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            fileName = FileService.GetFullPath(fileName);
            var projectId = ((MonoDevelopWorkspace)workspace).GetProjectId(project);

            if (projectId != null)
            {
                return(((MonoDevelopWorkspace)workspace).GetDocumentId(projectId, fileName));
            }
            else
            {
                LoggingService.LogWarning("Warning can't find " + fileName + " in project " + project.Name + "(" + projectId + ")");
            }
            return(null);
        }
        private ServiceHubRemoteHostClient(
            Workspace workspace,
            HubClient hubClient,
            HostGroup hostGroup,
            Stream stream)
            : base(workspace)
        {
            if (workspace.Options.GetOption(RemoteHostOptions.EnableConnectionPool))
            {
                int maxPoolConnection = workspace.Options.GetOption(RemoteHostOptions.MaxPoolConnection);

                _connectionPool = new ConnectionPool(
                    connectionFactory: (serviceName, cancellationToken) => CreateConnectionAsync(serviceName, callbackTarget: null, cancellationToken),
                    maxPoolConnection);
            }

            _hubClient = hubClient;
            _hostGroup = hostGroup;

            _endPoint = new RemoteEndPoint(stream, hubClient.Logger, incomingCallTarget: this);
            _endPoint.Disconnected += OnDisconnected;
            _endPoint.UnexpectedExceptionThrown += OnUnexpectedExceptionThrown;
            _endPoint.StartListening();
        }
 static void UpdateWorkspaceOptions(Microsoft.CodeAnalysis.Workspace ws)
 {
     // Roslyn uses | as separator.
     ws.Options = ws.Options.WithChangedOption(TodoCommentOptions.TokenList, CommentTag.ToString(CommentTag.SpecialCommentTags, "|"));
 }