• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# CodeAnalysis.Workspace类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.CodeAnalysis.Workspace的典型用法代码示例。如果您正苦于以下问题:C# Workspace类的具体用法?C# Workspace怎么用?C# Workspace使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Workspace类属于Microsoft.CodeAnalysis命名空间,在下文中一共展示了Workspace类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SolutionServices

 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>();
 }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:SolutionServices.cs


示例2: GetClassifiedSpans

        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;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:29,代码来源:Classifier.cs


示例3: Enable

        public static void Enable(Workspace workspace, Options options)
        {
            var service = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();

            workspace.Options = GetOptions(workspace, options);
            service.Register(workspace);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:DiagnosticProvider.cs


示例4: AbstractSourceTreeItem

        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;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:AbstractSourceTreeItem.cs


示例5: LogSession

        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));
                    }
                }
            }
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:25,代码来源:LinkedFileDiffMergingLogger.cs


示例6: TryMapSpanFromSecondaryBufferToPrimaryBuffer

        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);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:25,代码来源:VsTextSpanExtensions.cs


示例7: SymbolSearchService

        /// <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;
        }
开发者ID:rgani,项目名称:roslyn,代码行数:36,代码来源:SymbolSearchService.cs


示例8: SonarAnalyzerManager

        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);
        }
开发者ID:SonarSource-VisualStudio,项目名称:sonarlint-visualstudio,代码行数:27,代码来源:SonarAnalyzerManager.cs


示例9: SourceListItem

        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);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:28,代码来源:SourceListItem.cs


示例10: MiscellaneousDiagnosticListTable

 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);
 }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:7,代码来源:MiscellaneousDiagnosticListTable.cs


示例11: TryOnAfterGlobalSymbolRenamed

        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;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:33,代码来源:ContainedLanguageRefactorNotifyService.cs


示例12: FormatToken

        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);
        }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:32,代码来源:SmartTokenFormatter.cs


示例13: IndentationOptions

 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);
 }
开发者ID:neugenes,项目名称:StyleCopAnalyzers,代码行数:7,代码来源:IndentationOptions.cs


示例14: TryGetTextUndoHistory

            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;
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:26,代码来源:VisualStudioTextUndoHistoryWorkspaceServiceFactory.cs


示例15: GenerateBackingField

 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)); 
 }
开发者ID:CNinnovation,项目名称:TechConference2016,代码行数:7,代码来源:CodeGeneration.cs


示例16: LoadTextAndVersionAsync

        /// <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;
        }
开发者ID:GuilhermeSa,项目名称:roslyn,代码行数:37,代码来源:FileTextLoader.cs


示例17: CompilationContext

        /// <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;
        }
开发者ID:szabototo89,项目名称:CodeSharper,代码行数:10,代码来源:CompilationContext.cs


示例18: RemoteHostClientService

            public RemoteHostClientService(Workspace workspace, IDiagnosticAnalyzerService analyzerService)
            {
                _gate = new object();

                _workspace = workspace;
                _analyzerService = analyzerService;
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:RemoteHostClientServiceFactory.RemoteHostClientService.cs


示例19: GetCodeAnalysisDocumentFromDteDocument

        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);
        }
开发者ID:FrankBakkerNl,项目名称:IntelliFind,代码行数:7,代码来源:RoslynVisxHelpers.cs


示例20: CreateAsync

        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;
            }
        }
开发者ID:tralivali1234,项目名称:roslyn,代码行数:27,代码来源:ServiceHubRemoteHostClient.cs



注:本文中的Microsoft.CodeAnalysis.Workspace类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# BuildTasks.CommandLineBuilderExtension类代码示例发布时间:2022-05-26
下一篇:
C# CodeAnalysis.TouchedFileLogger类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap