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; } }
internal static LinePositionSpan GetEntityOfInterestSpan(ISymbol symbol, Workspace workspace, Location identifierLocation, CancellationToken cancellationToken) { // This is called on a background thread, but since we don't have proper asynchrony we must block var root = identifierLocation.SourceTree.GetRoot(cancellationToken); var node = root.FindToken(identifierLocation.SourceSpan.Start).Parent; var syntaxFactsService = workspace.Services.GetLanguageServices(root.Language).GetService<ISyntaxFactsService>(); switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: node = node.FirstAncestorOrSelf<SyntaxNode>(syntaxFactsService.IsMethodLevelMember) ?? node; break; case SymbolKind.NamedType: case SymbolKind.Namespace: node = node.FirstAncestorOrSelf<SyntaxNode>(syntaxFactsService.IsTopLevelNodeWithMembers) ?? node; break; } return identifierLocation.SourceTree.GetLocation(node.Span).GetLineSpan().Span; }
private void openStack() { refreshSession(); StatusText = "Neuer Workspace wird erstellt"; CreateProjectDialog createProjectDialog = new CreateProjectDialog(); if (createProjectDialog.DialogResult.HasValue && createProjectDialog.DialogResult.Value) { try { Workspace = new Workspace(createProjectDialog.NewProjectName); Workspace.createFromPictureStack(createProjectDialog.StackPath); Project = new HausarbeitAPProjectCT(createProjectDialog.NewProjectName); Project.description = createProjectDialog.NewProjectDescription; Project.initFileListFromStack(Workspace.TempFolder); Project.SaveToFile(Workspace.TempFolder + @"\project.xml"); ProjectText = Project.description; stackSlider.Maximum = Project.totalLayers - 1; stackSlider.Value = 0; loadPicture(0); StackIsLoaded = true; SectionView = false; this.Title = System.IO.Path.GetFileNameWithoutExtension(Project.name); } catch (Exception exc) { System.Windows.MessageBox.Show("Das Projekt konnte nicht erstellt werden\n" + exc.Message + exc.StackTrace); refreshSession(); } } else { refreshSession(); } }
protected MainForm InitEditor() { var workspace = new Workspace(); MainForm main = new MainForm(workspace); DualityEditorApp.Init(main, this.recover, workspace); return main; }
public override void OnMouseDown(System.Windows.Forms.MouseEventArgs e, Workspace w) { base.OnMouseDown(e, w); FloodFill(w.temp, ClickPoint.X, ClickPoint.Y, w.color); w.graphics.Clear(Color.Transparent); w.graphics.DrawImage(w.temp,0,0); }
public static string GetBingHelpMessage(this Diagnostic diagnostic, Workspace workspace = null) { var option = GetCustomTypeInBingSearchOption(workspace); // We use the ENU version of the message for bing search. return option ? diagnostic.GetMessage(USCultureInfo) : diagnostic.Descriptor.GetBingHelpMessage(); }
public Report Export(Workspace workspace, string resultPath, UserRequestData userRequestData, ExportCounterSettings counterSettings = null) { _exportImageCounter = 0; _currentWorkspace = workspace; _counterSettings = counterSettings; _userRequestData = userRequestData; _resultPath = resultPath; string result = string.Empty; result += CreateHeader(); if (Template.IncludeToc) { result += CreateTocHeader(); result += CreateToc(); result += CreateTocFooter(); } result += CreateContent(); result += CreateFooter(); result = ExportTemplateImages(result); var report = CreateReport(result, resultPath); return report; }
public LanguageServiceTests() { this.workspace = new Workspace(); this.powerShellContext = new PowerShellContext(); this.languageService = new LanguageService(this.powerShellContext); }
private Tuple<DiagnosticAnalyzer, CodeFixProvider> GetOrCreateDiagnosticProviderAndFixer( Workspace workspace, object fixProviderData) { return fixProviderData == null ? _analyzerAndFixerMap.GetOrAdd(workspace, CreateDiagnosticProviderAndFixer) : CreateDiagnosticProviderAndFixer(workspace, fixProviderData); }
public override void Apply(Workspace workspace, CancellationToken cancellationToken) { if (workspace.CanOpenDocuments) { workspace.OpenDocument(this.documentId, this.activate); } }
private bool openProjectFile() { OpenFileDialog newOpenFileDialog = new OpenFileDialog(); newOpenFileDialog.InitialDirectory = rootAppFolder + @"\Projects"; newOpenFileDialog.Filter = "zip files (*.zip)|*.zip"; if (newOpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { refreshSession(); Workspace = new Workspace(System.IO.Path.GetFileNameWithoutExtension(newOpenFileDialog.SafeFileName)); Workspace.createFromZip(newOpenFileDialog.FileName); Project = HausarbeitAPProjectCT.createFromFile(Path.Combine(Workspace.TempFolder, "project.xml")); Project.initFileListFromStack(Workspace.TempFolder); stackSlider.Minimum = 0; stackSlider.Maximum = Project.totalLayers - 1; loadPicture(0); StackIsLoaded = true; SectionView = false; ProjectText = Project.description; this.Title = System.IO.Path.GetFileNameWithoutExtension(Project.name); return true; } catch (Exception exc) { System.Windows.Forms.MessageBox.Show("Das Projekt konnte nicht geöffnet werden\n" + exc.Message + exc.InnerException, "Achtung"); return false; } } else { return false; } }
public override async Task SynchronizeWithBuildAsync(Workspace workspace, ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> map) { if (!PreferBuildErrors(workspace)) { // prefer live errors over build errors return; } var solution = workspace.CurrentSolution; foreach (var projectEntry in map) { var project = solution.GetProject(projectEntry.Key); if (project == null) { continue; } var stateSets = _stateManager.CreateBuildOnlyProjectStateSet(project); var lookup = projectEntry.Value.ToLookup(d => d.DocumentId); // do project one first await SynchronizeWithBuildAsync(project, stateSets, lookup[null]).ConfigureAwait(false); foreach (var document in project.Documents) { await SynchronizeWithBuildAsync(document, stateSets, lookup[document.Id]).ConfigureAwait(false); } } }
public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager) { _correlationId = correlationId; _owner = owner; _workspace = workspace; _analyzerManager = analyzerManager; }
public static async Task<ISymbolSearchUpdateEngine> CreateEngineAsync( Workspace workspace, ISymbolSearchLogService logService, CancellationToken cancellationToken) { var outOfProcessAllowed = workspace.Options.GetOption(SymbolSearchOptions.OutOfProcessAllowed); if (outOfProcessAllowed) { var client = await workspace.GetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); if (client != null) { var emptySolution = workspace.CreateSolution(workspace.CurrentSolution.Id); // We create a single session and use it for the entire lifetime of this process. // That single session will be used to do all communication with the remote process. // This is because each session will cause a new instance of the RemoteSymbolSearchUpdateEngine // to be created on the remote side. We only want one instance of that type. The // alternative is to make that type static variable on the remote side. But that's // much less clean and would make some of the state management much more complex. var session = await client.CreateServiceSessionAsync( WellKnownServiceHubServices.RemoteSymbolSearchUpdateEngine, emptySolution, logService, cancellationToken).ConfigureAwait(false); return new RemoteUpdateEngine(session); } } // Couldn't go out of proc. Just do everything inside the current process. return new SymbolSearchUpdateEngine(logService); }
public CSharpCompletionItem( Workspace workspace, CompletionListProvider completionProvider, string displayText, TextSpan filterSpan, Func<CancellationToken, Task<ImmutableArray<SymbolDisplayPart>>> descriptionFactory, Glyph? glyph, string sortText = null, string filterText = null, bool preselect = false, bool isBuilder = false, bool showsWarningIcon = false, bool shouldFormatOnCommit = false) : base(completionProvider, displayText, filterSpan, descriptionFactory, glyph, sortText, filterText, preselect, isBuilder, showsWarningIcon, shouldFormatOnCommit) { Contract.ThrowIfNull(workspace); this.Workspace = workspace; }
public DiagnosticData( string id, string category, string message, string enuMessageForBingSearch, DiagnosticSeverity severity, bool isEnabledByDefault, int warningLevel, Workspace workspace, ProjectId projectId, DocumentId documentId = null, TextSpan? span = null, string originalFilePath = null, int originalStartLine = 0, int originalStartColumn = 0, int originalEndLine = 0, int originalEndColumn = 0, string title = null, string description = null, string helpLink = null) : this( id, category, message, enuMessageForBingSearch, severity, severity, isEnabledByDefault, warningLevel, ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty, workspace, projectId, documentId, span, null, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn, originalFilePath, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn, title, description, helpLink) { }
public DiagnosticsUpdatedArgs( object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics) : base(id, workspace, projectId, documentId) { this.Solution = solution; this.Diagnostics = diagnostics; }
public MainForm(Workspace workspace,User user) { this.Visible = false; InitializeComponent(); _workspace = workspace; _user = user; }
public TodoItem( int priority, string message, Workspace workspace, DocumentId documentId, int mappedLine, int originalLine, int mappedColumn, int originalColumn, string mappedFilePath, string originalFilePath) { Priority = priority; Message = message; Workspace = workspace; DocumentId = documentId; MappedLine = mappedLine; MappedColumn = mappedColumn; MappedFilePath = mappedFilePath; OriginalLine = originalLine; OriginalColumn = originalColumn; OriginalFilePath = originalFilePath; }
public object Create([FromBody] WorkspaceCreateModel model) { var workspace = new Workspace<IExtent>(model.name, model.annotation); _workspaceCollection.AddWorkspace(workspace); return new {success = true}; }
internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration( IMethodSymbol constructor, CodeGenerationDestination destination, Workspace workspace, CodeGenerationOptions options, ParseOptions parseOptions) { options = options ?? CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConstructorDeclarationSyntax>(constructor, options); if (reusableSyntax != null) { return reusableSyntax; } bool hasNoBody = !options.GenerateMethodBodies; var declaration = SyntaxFactory.ConstructorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), options), modifiers: GenerateModifiers(constructor, options), identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(), parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, options: options), initializer: GenerateConstructorInitializer(constructor), body: hasNoBody ? null : GenerateBlock(constructor), semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken)); declaration = UseExpressionBodyIfDesired(workspace, declaration, parseOptions); return AddCleanupAnnotationsTo( ConditionallyAddDocumentationCommentTo(declaration, constructor, options)); }
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.Services.GetService<IExtensionManager>(); 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; }
public bool IsSupported(Workspace workspace) { lock (_gate) { return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id); } }
internal void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Workspace workspace, ProjectId projectId) { if (workspace != this.Workspace) { return; } var project = workspace.CurrentSolution.GetProject(projectId); bool raiseDiagnosticsUpdated = true; var diagnosticData = project != null ? DiagnosticData.Create(project, diagnostic) : DiagnosticData.Create(this.Workspace, diagnostic); var dxs = ImmutableInterlocked.AddOrUpdate(ref s_analyzerHostDiagnosticsMap, analyzer, ImmutableHashSet.Create(diagnosticData), (a, existing) => { var newDiags = existing.Add(diagnosticData); raiseDiagnosticsUpdated = newDiags.Count > existing.Count; return newDiags; }); if (raiseDiagnosticsUpdated) { RaiseDiagnosticsUpdated(MakeArgs(analyzer, dxs, project)); } }
private BaseDiagnosticIncrementalAnalyzer CreateIncrementalAnalyzerCallback(Workspace workspace) { // subscribe to active context changed event for new workspace workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged; return new DiagnosticIncrementalAnalyzer(this, LogAggregator.GetNextId(), workspace, _hostAnalyzerManager, _hostDiagnosticUpdateSource); }
/// <summary> /// Get approximate solution size at the point of call. /// /// This API is not supposed to return 100% accurate size. /// /// if a feature require 100% accurate size, use Solution to calculate it. this API is supposed to /// lazy and very cheap on answering that question. /// </summary> public long GetSolutionSize(Workspace workspace, SolutionId solutionId) { var service = workspace.Services.GetService<IPersistentStorageLocationService>(); return service.IsSupported(workspace) ? _tracker.GetSolutionSize(solutionId) : -1; }
public async void Register(Workspace workspace) { try { var workerBackOffTimeSpanInMS = workspace.Options.GetOption(InternalSolutionCrawlerOptions.PreviewBackOffTimeSpanInMS); var analyzer = _provider.CreateIncrementalAnalyzer(workspace); var source = s_cancellationTokens.GetValue(workspace, _ => new CancellationTokenSource()); var solution = workspace.CurrentSolution; foreach (var documentId in workspace.GetOpenDocumentIds()) { var document = solution.GetDocument(documentId); if (document == null) { continue; } // delay analyzing await Task.Delay(workerBackOffTimeSpanInMS).ConfigureAwait(false); // do actual analysis await analyzer.AnalyzeSyntaxAsync(document, source.Token).ConfigureAwait(false); await analyzer.AnalyzeDocumentAsync(document, bodyOpt: null, cancellationToken: source.Token).ConfigureAwait(false); // don't call project one. } } catch (OperationCanceledException) { // do nothing } }
internal static IEnumerable<ISymbol> GetSymbolsTouchingPosition( int position, SemanticModel semanticModel, Workspace workspace, CancellationToken cancellationToken) { var bindableToken = semanticModel.SyntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); var semanticInfo = semanticModel.GetSemanticInfo(bindableToken, workspace, cancellationToken); var symbols = semanticInfo.DeclaredSymbol != null ? ImmutableArray.Create<ISymbol>(semanticInfo.DeclaredSymbol) : semanticInfo.GetSymbols(includeType: false); // if there are more than one symbol, then remove the alias symbols. // When using (not declaring) an alias, the alias symbol and the target symbol are returned // by GetSymbols if (symbols.Length > 1) { symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Alias); } if (symbols.Length == 0) { var info = semanticModel.GetSymbolInfo(bindableToken, cancellationToken); if (info.CandidateReason == CandidateReason.MemberGroup) { return info.CandidateSymbols; } } return symbols; }
internal EditorConfigDocumentOptionsProvider(Workspace workspace) { _codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager(); workspace.DocumentOpened += Workspace_DocumentOpened; workspace.DocumentClosed += Workspace_DocumentClosed; }
public void Add(string key, string path) { if (string.IsNullOrEmpty(path)) { path = Shell.GetCurrentPath(); } if (string.IsNullOrEmpty(key)) throw new Exception("Key is required"); Workspace workspace = new Workspace() { Key = key, Path = path }; //try to get if existing var workspaceData = Data.GetWorkspace(workspace.Key); if (workspaceData != null) { Data.UpdateWorkspace(workspace); } else { Data.CreateWorkspace(workspace); } Shell.Write(string.Format("[{0}] '{1}' added.", workspace.Key, workspace.Path)); }
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpNamingStyleDiagnosticAnalyzer(), new NamingStyleCodeFixProvider());
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider();
private async Task <IEnumerable <CompletionItem> > GetSnippetsForDocumentAsync(Document document, int position, Workspace workspace, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var semanticFacts = document.GetLanguageService <ISemanticFactsService>(); if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) || syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) || syntaxFacts.GetContainingTypeDeclaration(await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false), position) is EnumDeclarationSyntax) { return(SpecializedCollections.EmptyEnumerable <CompletionItem>()); } var span = new TextSpan(position, 0); var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); if (semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken)) { var directive = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true).GetAncestor <DirectiveTriviaSyntax>(); if (directive.DirectiveNameToken.IsKind( SyntaxKind.IfKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElifKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.LineKeyword, SyntaxKind.PragmaKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.UndefKeyword, SyntaxKind.EndRegionKeyword, SyntaxKind.WarningKeyword)) { return(SpecializedCollections.EmptyEnumerable <CompletionItem>()); } return(await GetSnippetCompletionItemsAsync(workspace, semanticModel, position, isPreProcessorContext : true, cancellationToken : cancellationToken).ConfigureAwait(false)); } if (semanticFacts.IsGlobalStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsExpressionContext(semanticModel, position, cancellationToken) || semanticFacts.IsStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsNamespaceContext(semanticModel, position, cancellationToken) || semanticFacts.IsMemberDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsLabelContext(semanticModel, position, cancellationToken)) { return(await GetSnippetCompletionItemsAsync(workspace, semanticModel, position, isPreProcessorContext : false, cancellationToken : cancellationToken).ConfigureAwait(false)); } return(SpecializedCollections.EmptyEnumerable <CompletionItem>()); }
private ImmutableArray <CodeRefactoring> FilterOnUIThread(ImmutableArray <CodeRefactoring> refactorings, Workspace workspace) { return(refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToImmutableArray()); }
public TestProjectSnapshotManager(IEnumerable <ProjectSnapshotChangeTrigger> triggers, Workspace workspace) : base(Mock.Of <ForegroundDispatcher>(), Mock.Of <ErrorReporter>(), triggers, workspace) { }
public abstract bool CanNavigateTo(Workspace workspace);
protected override object CreateCodeRefactoringProvider(Workspace workspace) { return(new ExtractMethodCodeRefactoringProvider()); }
public void TestJobCreationAndDeletion() { string workspaceName = "testjobcreationanddeletion_workspace"; string clusterName = "testjobcreationanddeletion_cluster"; string expName = "testjobcreationanddeletion_experiment"; string jobName = "testjobcreationanddeletion_testjob"; var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType().FullName)) { var client = Helpers.GetBatchAIClient(context, handler1); var rgClient = Helpers.GetResourceManagementClient(context, handler2); string rgName = Helpers.CreateResourceGroup(rgClient); var clusterCreateParams = new ClusterCreateParameters() { ScaleSettings = new ScaleSettings() { Manual = new ManualScaleSettings() { TargetNodeCount = 1 } }, VmSize = "STANDARD_D1", UserAccountSettings = new UserAccountSettings() { AdminUserName = Helpers.ADMIN_USER_NAME, AdminUserPassword = Helpers.ADMIN_USER_PASSWORD, }, }; var workspaceCreateParams = new WorkspaceCreateParameters() { Location = Helpers.LOCATION, }; Workspace workspace = client.Workspaces.Create(rgName, workspaceName, workspaceCreateParams); Cluster cluster = client.Clusters.Create(rgName, workspaceName, clusterName, clusterCreateParams); Helpers.WaitAllNodesToBeIdle(client, rgName, workspaceName, clusterName); Experiment experiment = client.Experiments.Create(rgName, workspaceName, expName); var jobCreateParams = new JobCreateParameters() { Cluster = new ResourceId(cluster.Id), NodeCount = 1, CustomToolkitSettings = new CustomToolkitSettings() { CommandLine = "echo Hello" }, StdOutErrPathPrefix = "$AZ_BATCHAI_JOB_TEMP", }; client.Jobs.Create(rgName, workspaceName, expName, jobName, jobCreateParams); Helpers.WaitJobSucceeded(client, rgName, workspaceName, expName, jobName); client.Clusters.Delete(rgName, workspaceName, clusterName); client.Jobs.Delete(rgName, workspaceName, expName, jobName); } }
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new MakeLocalFunctionStaticDiagnosticAnalyzer(), GetMakeLocalFunctionStaticCodeFixProvider());
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertConditionalCodeRefactoringProvider();
private async Task TestFixAllWithMultipleEncodingsAsync(FixAllScope scope) { string[] testCode = new[] { "class Foo { }", "class Bar { }" }; this.fileEncoding = Encoding.Unicode; // Create a project using the specified encoding Project project = this.CreateProject(testCode); project = project.AddDocument("Test2.cs", SourceText.From("class FooBar { }", Encoding.UTF7)).Project; Project oldProject = project; Workspace workspace = project.Solution.Workspace; var codeFixer = this.GetCSharpCodeFixProvider(); var fixAllProvider = codeFixer.GetFixAllProvider(); var diagnostics = new List <Diagnostic>(); var descriptor = this.GetCSharpDiagnosticAnalyzers().First().SupportedDiagnostics.First(); foreach (var document in project.Documents) { // Create a diagnostic for the document to fix var properties = ImmutableDictionary <string, string> .Empty.SetItem(SA1412StoreFilesAsUtf8.EncodingProperty, (await document.GetTextAsync().ConfigureAwait(false)).Encoding.WebName); var diagnostic = Diagnostic.Create( descriptor, Location.Create(await document.GetSyntaxTreeAsync().ConfigureAwait(false), TextSpan.FromBounds(0, 0)), properties); diagnostics.Add(diagnostic); } FixAllContext fixAllContext = new FixAllContext( project.Documents.First(), codeFixer, scope, nameof(SA1412CodeFixProvider) + "." + this.fileEncoding.WebName, new[] { SA1412StoreFilesAsUtf8.DiagnosticId }, TestDiagnosticProvider.Create(diagnostics.ToImmutableArray()), CancellationToken.None); CodeAction codeAction = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false); var operation = codeAction.GetOperationsAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()[0]; operation.Apply(workspace, CancellationToken.None); // project should now have the "fixed document" in it. // Because of limitations in Roslyn the fixed document should // have a different DocumentId then the broken document project = workspace.CurrentSolution.Projects.First(); Assert.Equal(3, project.DocumentIds.Count); // The order of the document ids is now different from the order before. for (int i = 1; i < 3; i++) { DocumentId documentId = project.DocumentIds[i]; SourceText sourceText = await project.GetDocument(documentId).GetTextAsync().ConfigureAwait(false); Assert.Equal(testCode[i - 1], sourceText.ToString()); Assert.Equal(Encoding.UTF8, sourceText.Encoding); Assert.NotEqual(oldProject.DocumentIds[i - 1], project.DocumentIds[i]); } // Check that Test2.cs was not changed DocumentId otherDocumentId = project.DocumentIds[0]; var otherDocument = project.GetDocument(otherDocumentId); Assert.Equal("Test2.cs", otherDocument.Name); SourceText otherDocumentText = await otherDocument.GetTextAsync().ConfigureAwait(false); Assert.Equal("class FooBar { }", otherDocumentText.ToString()); Assert.Equal(Encoding.UTF7, otherDocumentText.Encoding); Assert.Equal(oldProject.DocumentIds[2], project.DocumentIds[0]); }
private async Task <IEnumerable <CompletionItem> > GetSnippetCompletionItemsAsync(Workspace workspace, SemanticModel semanticModel, int position, bool isPreProcessorContext, CancellationToken cancellationToken) { var service = _snippetInfoService ?? workspace.Services.GetLanguageServices(semanticModel.Language).GetService <ISnippetInfoService>(); if (service == null) { return(SpecializedCollections.EmptyEnumerable <CompletionItem>()); } var snippets = service.GetSnippetsIfAvailable(); if (isPreProcessorContext) { snippets = snippets.Where(snippet => snippet.Shortcut.StartsWith("#", StringComparison.Ordinal)); } var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return(snippets.Select(snippet => new CompletionItem( this, displayText: isPreProcessorContext?snippet.Shortcut.Substring(1) : snippet.Shortcut, sortText: isPreProcessorContext ? snippet.Shortcut.Substring(1) : snippet.Shortcut, descriptionFactory: c => Task.FromResult((snippet.Title + Environment.NewLine + snippet.Description).ToSymbolDisplayParts()), filterSpan: CompletionUtilities.GetTextChangeSpan(text, position), glyph: Glyph.Snippet, shouldFormatOnCommit: service.ShouldFormatSnippet(snippet)))); }
public ActiveStatementTrackingService(Workspace workspace) { _workspace = workspace; _spanProvider = new RemoteEditAndContinueServiceProxy(_workspace); }
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAddDocCommentNodesCodeFixProvider());
public bool IsGlobalTransactionOpen(Workspace workspace) => GetHistory(workspace).CurrentTransaction != null;
public bool CanUndo(Workspace workspace) { // only primary workspace supports global undo return(workspace is InteractiveWindowWorkspace); }
public bool OpenFileOnly(Workspace workspace) => true;
public bool OpenFileOnly(Workspace workspace) => false;
internal override Tuple <DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return(Tuple.Create <DiagnosticAnalyzer, CodeFixProvider>( new MockDiagnosticAnalyzer(), null)); }
/// this is for test only internal VisualStudioDiagnosticListTable(Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider) : this(null, workspace, diagnosticService, null, provider) { AddInitialTableSource(workspace.CurrentSolution, _liveTableSource); }
internal ContainedLanguage( IVsTextBufferCoordinator bufferCoordinator, IComponentModel componentModel, VisualStudioProject project, IVsHierarchy hierarchy, uint itemid, VisualStudioProjectTracker projectTrackerOpt, ProjectId projectId, TLanguageService languageService, IFormattingRule vbHelperFormattingRule = null) { this.BufferCoordinator = bufferCoordinator; this.ComponentModel = componentModel; this.Project = project; _languageService = languageService; this.Workspace = projectTrackerOpt?.Workspace ?? componentModel.GetService <VisualStudioWorkspace>(); _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>(); _diagnosticAnalyzerService = componentModel.GetService <IDiagnosticAnalyzerService>(); // Get the ITextBuffer for the secondary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)); var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines; SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer); // Get the ITextBuffer for the primary buffer Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)); DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines); // Create our tagger var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>(); _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer); if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemid, out filePath)) { FatalError.Report(new System.Exception("Failed to get document moniker for a contained document")); } } DocumentId documentId; if (this.Project != null) { documentId = this.Project.AddSourceTextContainer(SubjectBuffer.AsTextContainer(), filePath); } else { documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}"); // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath)); Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer()); } this.ContainedDocument = new ContainedDocument( componentModel.GetService <IThreadingContext>(), documentId, subjectBuffer: SubjectBuffer, dataBuffer: DataBuffer, bufferCoordinator, this.Workspace, project, hierarchy, itemid, componentModel, vbHelperFormattingRule); // TODO: Can contained documents be linked or shared? this.DataBuffer.Changed += OnDataBufferChanged; }
protected override void DisconnectFromWorkspace(Workspace workspace) { _notificationService.OpenedDocumentSemanticChanged -= OnOpenedDocumentSemanticChanged; this.RaiseChanged(); }
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpNameTupleElementCodeRefactoringProvider();
protected override object CreateCodeRefactoringProvider(Workspace workspace) { return new InvertIfCodeRefactoringProvider(); }
private static bool TryBuildWorkspaceInternal( ICommandLineConfiguration commandLineConfig, FrontEndContext frontEndContext, EngineContext engineContext, EvaluationFilter evaluationFilter, EventHandler <WorkspaceProgressEventArgs> progressHandler, out Workspace workspace, out FrontEndHostController frontEndHostController, out IMutablePipGraph pipGraph, WorkspaceBuilderConfiguration configuration, bool forIDE, FrontEndEngineAbstraction frontEndEngineAbstraction = null, bool collectMemoryAsSoonAsPossible = true) { Contract.Requires((commandLineConfig.Engine.Phase & (EnginePhases.ParseWorkspace | EnginePhases.AnalyzeWorkspace)) != EnginePhases.None); Contract.Requires(frontEndContext != null); Contract.Requires(engineContext != null); Contract.Requires(commandLineConfig.Startup.ConfigFile.IsValid); Contract.Requires(evaluationFilter != null); workspace = null; frontEndHostController = null; pipGraph = null; var pathTable = engineContext.PathTable; var loggingContext = frontEndContext.LoggingContext; var mutableCommandlineConfig = GetCommandLineConfiguration( commandLineConfig, configuration); BuildXLEngine.ModifyConfigurationForCloudbuild(mutableCommandlineConfig, false, pathTable, loggingContext); BuildXLEngine.PopulateLoggingAndLayoutConfiguration(mutableCommandlineConfig, pathTable, bxlExeLocation: null); var statistics = new FrontEndStatistics(progressHandler); var frontEndControllerFactory = FrontEndControllerFactory.Create( mode: FrontEndMode.NormalMode, loggingContext: loggingContext, configuration: mutableCommandlineConfig, collector: null, statistics: statistics, collectMemoryAsSoonAsPossible: collectMemoryAsSoonAsPossible); var controller = frontEndControllerFactory.Create(engineContext.PathTable, engineContext.SymbolTable); controller.InitializeHost(frontEndContext, mutableCommandlineConfig); frontEndHostController = (FrontEndHostController)controller; // If there is an explicit engine abstraction, we set it. This is used by the IDE. if (frontEndEngineAbstraction != null) { // The IDE engine typically doesn't have mounts configured. We do it here if they haven't been configured yet. // Observe these are just the default mounts used for config evaluation. if (frontEndEngineAbstraction is BasicFrontEndEngineAbstraction basicEngine && !frontEndEngineAbstraction.GetMountNames("Script", BuildXL.Utilities.ModuleId.Invalid).Any()) { // If this fails we just ignore the failure. Mounts not being properly configured doesn't prevent the IDE plugin from working. basicEngine.TryPopulateWithDefaultMountsTable(loggingContext, engineContext, mutableCommandlineConfig, mutableCommandlineConfig.Startup.Properties); } frontEndHostController.SetState(frontEndEngineAbstraction, pipGraph: null, configuration: mutableCommandlineConfig); } else { // Otherwise we construct one with all mounts populated for config evaluation var configurationEngine = new BasicFrontEndEngineAbstraction(engineContext.PathTable, engineContext.FileSystem, mutableCommandlineConfig); if (!configurationEngine.TryPopulateWithDefaultMountsTable(loggingContext, engineContext, mutableCommandlineConfig, mutableCommandlineConfig.Startup.Properties)) { // Errors are logged already return(false); } frontEndEngineAbstraction = configurationEngine; } var config = controller.ParseConfig(frontEndEngineAbstraction, mutableCommandlineConfig); if (config == null) { return(false); } IMutablePipGraph pipGraphBuilder = null; using (var cache = Task.FromResult <Possible <EngineCache> >( new EngineCache( new InMemoryArtifactContentCache(), // Note that we have an 'empty' store (no hits ever) rather than a normal in memory one. new EmptyTwoPhaseFingerprintStore()))) { var mountsTable = MountsTable.CreateAndRegister(loggingContext, engineContext, config, mutableCommandlineConfig.Startup.Properties); // For the IDE case, we want to make sure all config-specific mounts are properly populated if (forIDE && frontEndEngineAbstraction is BasicFrontEndEngineAbstraction languageServiceEngine) { Contract.AssertNotNull(frontEndEngineAbstraction); AddConfigurationMounts(config, mountsTable); languageServiceEngine.SetMountsTable(mountsTable); } if (frontEndEngineAbstraction == null) { if (mutableCommandlineConfig.Engine.Phase.HasFlag(EnginePhases.Schedule)) { frontEndEngineAbstraction = new FrontEndEngineImplementation( loggingContext, frontEndContext.PathTable, config, mutableCommandlineConfig.Startup, mountsTable, InputTracker.CreateDisabledTracker(loggingContext), null, null, () => FileContentTable.CreateStub(loggingContext), 5000, false, controller.RegisteredFrontEnds); var searchPathToolsHash = new DirectoryMembershipFingerprinterRuleSet(config, engineContext.StringTable).ComputeSearchPathToolsHash(); pipGraphBuilder = new PipGraph.Builder( EngineSchedule.CreateEmptyPipTable(engineContext), engineContext, Pips.Tracing.Logger.Log, loggingContext, config, mountsTable.MountPathExpander, fingerprintSalt: config.Cache.CacheSalt, searchPathToolsHash: searchPathToolsHash); // Observe mount table is completed during workspace construction AddConfigurationMounts(config, mountsTable); IDictionary <ModuleId, MountsTable> moduleMountsTableMap; if (!mountsTable.PopulateModuleMounts(config.ModulePolicies.Values, out moduleMountsTableMap)) { Contract.Assume(loggingContext.ErrorWasLogged, "An error should have been logged after MountTable.PopulateModuleMounts()"); return(false); } } else { frontEndEngineAbstraction = new BasicFrontEndEngineAbstraction(frontEndContext.PathTable, frontEndContext.FileSystem, config); } } using (frontEndEngineAbstraction is IDisposable ? (IDisposable)frontEndEngineAbstraction : null) { // Attempt to build and/or analyze the workspace if (!controller.PopulateGraph( cache: cache, graph: pipGraphBuilder, engineAbstraction: frontEndEngineAbstraction, evaluationFilter: evaluationFilter, configuration: config, startupConfiguration: mutableCommandlineConfig.Startup)) { workspace = frontEndHostController.GetWorkspace(); // Error has been reported already return(false); } pipGraph = pipGraphBuilder; } } Contract.Assert(frontEndHostController != null); workspace = frontEndHostController.GetWorkspace(); if (mutableCommandlineConfig.Engine.Phase == EnginePhases.AnalyzeWorkspace) { // If workspace construction is successful, we run the linter on all specs. // This makes sure the workspace will carry all the errors that will occur when running the same specs in the regular engine path workspace = CreateLintedWorkspace( workspace, frontEndContext.LoggingContext, config.FrontEnd, pathTable); } return(true); }
/// <summary> /// Builds a workspace and uses filter to find specs to evaluate. /// </summary> public static bool TryBuildWorkspaceAndCollectFilesToAnalyze( Tracing.Logger logger, PathTable pathTable, ICommandLineConfiguration configuation, out Workspace workspace, out IMutablePipGraph pipGraph, out IReadOnlyDictionary <AbsolutePath, ISourceFile> filesToAnalyze, out FrontEndContext context) { workspace = null; pipGraph = null; filesToAnalyze = null; var loggingContext = new LoggingContext("DScriptAnalyzer"); var fileSystem = new PassThroughFileSystem(pathTable); var engineContext = EngineContext.CreateNew(CancellationToken.None, pathTable, fileSystem); context = engineContext.ToFrontEndContext(loggingContext); // Parse filter string into EvaluationFilter var evaluationFilter = EvaluationFilter.Empty; if (!string.IsNullOrEmpty(configuation.Filter)) { if (!TryGetEvaluationFilter(logger, loggingContext, engineContext, configuation.Filter, out evaluationFilter)) { // Error has been reported already return(false); } } // Try parsing the workspace from config and evaluation filter if (!TryBuildWorkspace( configuation, context, engineContext, evaluationFilter, progressHandler: null, workspace: out workspace, frontEndHostController: out _, pipGraph: out pipGraph, configuration: GetDefaultConfiguration())) { return(false); } if (configuation.Engine.Phase == EnginePhases.AnalyzeWorkspace) { // Find strict subset of specs in workspace that should be analyzed var collectedFilesToAnalyze = CollectFilesToAnalyze( workspace, pathTable, configuation.Startup.ConfigFile, evaluationFilter); if (collectedFilesToAnalyze.Count == 0) { logger.ErrorFilterHasNoMatchingSpecs(loggingContext, configuation.Filter); return(false); } filesToAnalyze = collectedFilesToAnalyze; } else { filesToAnalyze = new Dictionary <AbsolutePath, ISourceFile>(); } return(true); }
public void StartListening(Workspace workspace, ITodoListProvider service) { new MiscellaneousTodoListTable(workspace, service, _tableManagerProvider); }
public MiscellaneousTodoListTable(Workspace workspace, ITodoListProvider todoListProvider, ITableManagerProvider provider) : base(workspace, todoListProvider, IdentifierString, provider) { ConnectWorkspaceEvents(); }
public abstract bool TryNavigateTo(Workspace workspace, bool isPreview);
protected RemoteHostClient(Workspace workspace) { _workspace = workspace; }