public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var namedType = graphBuilder.GetSymbol(node) as INamedTypeSymbol; if (namedType == null) { continue; } if (namedType.TypeKind == TypeKind.Class) { var derivedTypes = await namedType.FindDerivedClassesAsync(solution, cancellationToken).ConfigureAwait(false); foreach (var derivedType in derivedTypes) { var symbolNode = await graphBuilder.AddNodeForSymbolAsync(derivedType, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node); } } else if (namedType.TypeKind == TypeKind.Interface) { var derivedTypes = await namedType.FindDerivedInterfacesAsync(solution, cancellationToken).ConfigureAwait(false); foreach (var derivedType in derivedTypes) { var symbolNode = await graphBuilder.AddNodeForSymbolAsync(derivedType, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node); } } } return graphBuilder; }
public bool IsAuthorizedToView(IUser user, IGraphContext graphContext) { var roles = GetAuthorizedToView(graphContext); if (roles.Contains("Anonymous")) return true; if (user == null) return false; return user.As<IUserRoles>().Roles.Intersect(roles).Count() != 0; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); var references = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false); foreach (var reference in references) { var referencedSymbol = reference.Definition; var projectId = graphBuilder.GetContextProject(node).Id; var allLocations = referencedSymbol.Locations.Concat(reference.Locations.Select(r => r.Location)) .Where(l => l != null && l.IsInSource); foreach (var location in allLocations) { var locationNode = GetLocationNode(referencedSymbol, location, context, projectId, cancellationToken); graphBuilder.AddLink(node, CodeLinkCategories.SourceReferences, locationNode); } } } return graphBuilder; }
public void ImportConnections(IGraphContext graphContext, string serializationText) { var connections = _simpleSerializer.JsonDeserialize<List<int[]>>(serializationText); foreach (var connection in connections) { _graphManager.FindGraph(graphContext).Services.ConnectionManager.Connect(connection[0], connection[1]); } }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var searchTasks = solution.Projects.Select(p => ProcessProjectAsync(p, graphBuilder, cancellationToken)).ToArray(); await Task.WhenAll(searchTasks).ConfigureAwait(false); return graphBuilder; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { if (!cancellationToken.IsCancellationRequested) { var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { bool containsChildren = SymbolContainment.GetContainedSymbols(symbol).Any(); graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, containsChildren); } else if (node.HasCategory(CodeNodeCategories.File)) { var document = graphBuilder.GetContextDocument(node); if (document != null) { var childNodes = await SymbolContainment.GetContainedSyntaxNodesAsync(document, cancellationToken).ConfigureAwait(false); graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, childNodes.Any()); } else { var uri = node.Id.GetNestedValueByName<Uri>(CodeGraphNodeIdName.File); if (uri != null) { // Since a solution load is not yet completed, there is no document available to answer this query. // The solution explorer presumes that if somebody doesn't answer for a file, they never will. // See Providers\GraphContextAttachedCollectionSource.cs for more. Therefore we should answer by setting // ContainsChildren property to either true or false, so any following updates will be tractable. // We will set it to false since the solution explorer assumes the default for this query response is 'false'. // Todo: we may need fallback to check if this node actually represents a C# or VB language // even when its extension fails to say so. One option would be to call DTEWrapper.IsRegisteredForLangService, // which may not be called here however since deadlock could happen. // The Uri returned by `GetNestedValueByName()` above isn't necessarily absolute and the `OriginalString` is // the only property that doesn't throw if the UriKind is relative, so `OriginalString` must be used instead // of `AbsolutePath`. string ext = Path.GetExtension(uri.OriginalString); if (ext.Equals(".cs", StringComparison.OrdinalIgnoreCase) || ext.Equals(".vb", StringComparison.OrdinalIgnoreCase)) { graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, false); } } } } } } return graphBuilder; }
protected void RegisterRoute(string name, Route route, IGraphContext graphContext) { route.DataTokens["GraphContext"] = graphContext; _routes.Add(new RouteDescriptor { Name = name, Route = route }); }
public string ExportAllConnections(IGraphContext graphContext) { var connections = _graphManager.FindGraph(graphContext).Services.ConnectionManager.GetAll(0, int.MaxValue); var serializableConnections = new List<int[]>(); foreach (var connection in connections) { serializableConnections.Add(new int[] { connection.Node1Id, connection.Node2Id }); } return _simpleSerializer.JsonSerialize(serializableConnections); }
public IEnumerable<IGraphDescriptor> FindGraphs(IGraphContext graphContext) { var descriptors = new Dictionary<string, IGraphDescriptor>(); foreach (var descriptor in _descriptorFilterer.FilterByMatchingGraphContext(Descriptors, graphContext)) { if(!String.IsNullOrEmpty(descriptor.Name)) descriptors[descriptor.Name] = descriptor; } return descriptors.Values; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (int depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { cancellationToken.ThrowIfCancellationRequested(); var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeForSymbolAsync(newSymbol, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode); } } else if (node.HasCategory(CodeNodeCategories.File)) { var document = graphBuilder.GetContextDocument(node); if (document != null) { foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeForSymbolAsync(newSymbol, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode); } } } } nodesToProcess = newNodes; } return graphBuilder; }
private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); }
protected void RegisterEngineRoute(string url, string instanceModule, string frontendEngine, IGraphContext graphContext, string engineModule = "Associativy.Frontends") { RegisterRoute( graphContext.Stringify() + " " + frontendEngine, new Route( url, new RouteValueDictionary { {"area", instanceModule}, {"controller", frontendEngine + "Engine"}, {"action", "Index"} }, new RouteValueDictionary(), new RouteValueDictionary { {"area", engineModule}, }, new MvcRouteHandler()), graphContext); }
internal GraphNode GetLocationNode(ISymbol symbol, Location location, IGraphContext context, ProjectId projectId, CancellationToken cancellationToken) { var span = location.GetLineSpan(); var lineText = location.SourceTree.GetText(cancellationToken).Lines[span.StartLinePosition.Line].ToString(); var filePath = location.SourceTree.FilePath; var sourceLocation = new SourceLocation(filePath, new Position(span.StartLinePosition.Line, span.StartLinePosition.Character), new Position(span.EndLinePosition.Line, span.EndLinePosition.Character)); var label = string.Format("{0} ({1}, {2}): {3}", System.IO.Path.GetFileName(filePath), span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, lineText.TrimStart()); var locationNode = context.Graph.Nodes.GetOrCreate(sourceLocation.CreateGraphNodeId(), label, CodeNodeCategories.SourceLocation); locationNode[CodeNodeProperties.SourceLocation] = sourceLocation; locationNode[RoslynGraphProperties.ContextProjectId] = projectId; locationNode[DgmlNodeProperties.Icon] = IconHelper.GetIconName("Reference", Accessibility.NotApplicable); return locationNode; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol is IMethodSymbol || symbol is IPropertySymbol || symbol is IEventSymbol) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var o in overrides) { var symbolNode = await graphBuilder.AddNodeForSymbolAsync(o, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, RoslynGraphCategories.Overrides, node); } } } return graphBuilder; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { foreach (var newSymbol in await GetCalledMethodSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeForSymbolAsync(newSymbol, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(node, CodeLinkCategories.Calls, newNode); } } } return graphBuilder; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { var overriddenMember = symbol.OverriddenMember(); if (overriddenMember != null) { var symbolNode = await graphBuilder.AddNodeForSymbolAsync(overriddenMember, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(node, RoslynGraphCategories.Overrides, symbolNode); } } } return graphBuilder; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { var callers = await SymbolFinder.FindCallersAsync(symbol, solution, cancellationToken).ConfigureAwait(false); foreach (var caller in callers.Where(c => c.IsDirect)) { var callerNode = await graphBuilder.AddNodeForSymbolAsync(caller.CallingSymbol, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(callerNode, CodeLinkCategories.Calls, node); } } } return graphBuilder; }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol is INamedTypeSymbol || symbol is IMethodSymbol || symbol is IPropertySymbol || symbol is IEventSymbol) { var implementations = await SymbolFinder.FindImplementationsAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementation in implementations) { var symbolNode = await graphBuilder.AddNodeForSymbolAsync(implementation, relatedNode: node).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.Implements, node); } } } return graphBuilder; }
internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (int depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { var namedType = graphBuilder.GetSymbol(node) as INamedTypeSymbol; if (namedType != null) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder.AddNodeForSymbolAsync(namedType.BaseType, relatedNode: node).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode); } else if (namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty) { foreach (var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct()) { var baseTypeNode = await graphBuilder.AddNodeForSymbolAsync(baseNode, relatedNode: node).ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink(node, CodeLinkCategories.InheritsFrom, baseTypeNode); } } } } nodesToProcess = newNodes; } return graphBuilder; }
public IEnumerable<IGraphDescriptor> FilterByMatchingGraphContext(IEnumerable<IGraphDescriptor> descriptors, IGraphContext graphContext) { var filteredDescriptors = descriptors; if (!String.IsNullOrEmpty(graphContext.Name)) { // Catch-alls with empty name property are kept filteredDescriptors = filteredDescriptors.Where((descriptor) => descriptor.Name == graphContext.Name || String.IsNullOrEmpty(descriptor.Name)); } if (graphContext.ContentTypes != null && graphContext.ContentTypes.Count() != 0) { if (filteredDescriptors.Count() == 0) { // If there are no descriptors with the graph context, try only with content types filteredDescriptors = descriptors; } filteredDescriptors = filteredDescriptors.Where((descriptor) => { foreach (var contentType in graphContext.ContentTypes) { // A descriptor is only suitable if it has no content types specified (catch-all) or contains all content // types listed in the context. if (descriptor.ContentTypes == null || descriptor.ContentTypes.Count() == 0) return true; if (!descriptor.ContentTypes.Contains(contentType)) return false; } return true; }); } // Catch-alls will be at the top, so the more specific descriptors at the bottom. // Also, because OrderBy is a stable sort, registration (dependency) order is kept. filteredDescriptors = filteredDescriptors.OrderBy(descriptor => descriptor.ContentTypes != null && descriptor.ContentTypes.Count() != 0); return filteredDescriptors; }
public override void BeginGetGraphData(IGraphContext context) { RegisterImages(); if (context.Direction == GraphContextDirection.Contains) { CreateOutline(context); if (context.TrackChanges) { ThreadPool.QueueUserWorkItem(CreateChildren, context); } else { CreateChildren(context); } return; // Don't call OnCompleted } else if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren)) { foreach (GraphNode node in GetAllowedFiles(context.InputNodes)) { node.SetValue(DgmlNodeProperties.ContainsChildren, true); } foreach (var node in context.InputNodes.Where(n => n.HasCategory(CssGraphSchema.CssAtDirectivesParent) || n.HasCategory(CssGraphSchema.CssIdSelectorParent) || n.HasCategory(CssGraphSchema.CssClassSelectorParent) )) { node.SetValue(DgmlNodeProperties.ContainsChildren, true); } } // Signals that all results have been created. context.OnCompleted(); }
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node); if (symbol is INamedTypeSymbol) { var namedType = (INamedTypeSymbol)symbol; var implementedSymbols = namedType.AllInterfaces; await AddImplementedSymbols(graphBuilder, node, implementedSymbols).ConfigureAwait(false); } else if (symbol is IMethodSymbol || symbol is IPropertySymbol || symbol is IEventSymbol) { var implements = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); await AddImplementedSymbols(graphBuilder, node, implements).ConfigureAwait(false); } } return graphBuilder; }
protected abstract bool CanHandle(IGraphContext graphContext);
public override bool HandleRequest(IGraphContext graphContext) { Search(graphContext); return(false); }
/// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static Task PopulateContextGraphAsync(Solution solution, List <IGraphQuery> graphQueries, IGraphContext context) { var cancellationToken = context.CancelToken; var graphTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var whenAllTask = Task.WhenAll(graphTasks); return(whenAllTask.SafeContinueWith( t => ProcessGraphTasks(t.Result, context), cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default)); }
public void BeginGetGraphData(IGraphContext context) => _provider.BeginGetGraphData(context);
public override void BuildGraph( IGraphContext graphContext, string projectPath, IDependency dependency, GraphNode dependencyGraphNode, ITargetedDependenciesSnapshot targetedSnapshot) { // store refreshed dependency info dependencyGraphNode.SetValue(DependenciesGraphSchema.DependencyIdProperty, dependency.Id); dependencyGraphNode.SetValue(DependenciesGraphSchema.ResolvedProperty, dependency.Resolved); var children = targetedSnapshot.GetDependencyChildren(dependency); if (children == null) { return; } var regularChildren = new List <IDependency>(); var fxAssembliesChildren = new List <IDependency>(); foreach (var childDependency in children) { if (!childDependency.Visible) { continue; } if (childDependency.Flags.Contains(DependencyTreeFlags.FxAssemblyProjectFlags)) { fxAssembliesChildren.Add(childDependency); } else { regularChildren.Add(childDependency); } } var isFxAssembliesFolder = dependencyGraphNode.GetValue <bool>(DependenciesGraphSchema.IsFrameworkAssemblyFolderProperty); if (isFxAssembliesFolder) { foreach (var fxAssembly in fxAssembliesChildren) { Builder.AddGraphNode( graphContext, projectPath, dependencyGraphNode, fxAssembly.ToViewModel(targetedSnapshot)); } } else { foreach (var childDependency in regularChildren) { Builder.AddGraphNode( graphContext, projectPath, dependencyGraphNode, childDependency.ToViewModel(targetedSnapshot)); } if (fxAssembliesChildren.Count > 0) { var fxAssembliesViewModel = new PackageFrameworkAssembliesViewModel(); var fxAssembliesNode = Builder.AddGraphNode(graphContext, projectPath, dependencyGraphNode, fxAssembliesViewModel); fxAssembliesNode.SetValue(DgmlNodeProperties.ContainsChildren, true); fxAssembliesNode.SetValue(DependenciesGraphSchema.IsFrameworkAssemblyFolderProperty, true); fxAssembliesNode.SetValue(DependenciesGraphSchema.DependencyIdProperty, dependency.Id); fxAssembliesNode.SetValue(DependenciesGraphSchema.ResolvedProperty, dependency.Resolved); } } }
public void BeginGetGraphData(IGraphContext context) { this.BeginGetGraphData(context, true); }
public GraphInspectorPanel(IGraphContext context) { this.context = context; titleContent = new GUIContent("Graph Inspector", BoltCore.Icons.inspectorWindow ? [IconSize.Small]); }
public void SetAuthorizedToView(IGraphContext graphContext, IEnumerable<string> roles) { _settingsService.Set(graphContext.Name, new FrontendAuthorizationSettings { Roles = roles.ToList() }); }
public async Task <GraphBuilder> GetGraphAsync( Solution solution, IGraphContext context, CancellationToken cancellationToken ) { var graphBuilder = await GraphBuilder .CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken) .ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet <GraphNode>(); foreach (var node in nodesToProcess) { var symbol = graphBuilder.GetSymbol(node); if (symbol is INamedTypeSymbol namedType) { if (namedType.BaseType != null) { var baseTypeNode = await graphBuilder .AddNodeAsync(namedType.BaseType, relatedNode : node) .ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink( node, CodeLinkCategories.InheritsFrom, baseTypeNode ); } else if ( namedType.TypeKind == TypeKind.Interface && !namedType.OriginalDefinition.AllInterfaces.IsEmpty ) { foreach ( var baseNode in namedType.OriginalDefinition.AllInterfaces.Distinct() ) { var baseTypeNode = await graphBuilder .AddNodeAsync(baseNode, relatedNode : node) .ConfigureAwait(false); newNodes.Add(baseTypeNode); graphBuilder.AddLink( node, CodeLinkCategories.InheritsFrom, baseTypeNode ); } } } } nodesToProcess = newNodes; } return(graphBuilder); }
private static async Task PopulateContextGraphAsync(Solution solution, List <IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph); context.OutputNodes.AddAll(graphBuilder.CreatedNodes); } transaction.Complete(); } catch (Exception ex) when(FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(ex)) { throw ExceptionUtilities.Unreachable; } }
public static async Task <List <ResourceResponse <Document> > > UpsertGraphDocumentsAsync(this DocumentClient client, DocumentCollection collection, IGraphContext context) { List <ResourceResponse <Document> > results = new List <ResourceResponse <Document> >(); foreach (object poco in context.Elements) { IGraphSerializer serializer = GraphSerializerFactory.CreateGraphSerializer(context, poco.GetType()); results.Add(await client.UpsertDocumentAsync(collection.SelfLink, serializer.ConvertToDocDBJObject(poco))); } return(results); }
internal VertexTree(JObject items, IGraphContext context) : base((IEnumerable <dynamic>)items, context) { _graphContext = context as GraphContextBase; }
public async Task <GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { if (!cancellationToken.IsCancellationRequested) { var symbol = graphBuilder.GetSymbol(node); if (symbol != null) { var containsChildren = SymbolContainment.GetContainedSymbols(symbol).Any(); graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, containsChildren); } else if (node.HasCategory(CodeNodeCategories.File)) { var document = graphBuilder.GetContextDocument(node); if (document != null) { var childNodes = await SymbolContainment.GetContainedSyntaxNodesAsync(document, cancellationToken).ConfigureAwait(false); graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, childNodes.Any()); } else { var uri = node.Id.GetNestedValueByName <Uri>(CodeGraphNodeIdName.File); if (uri != null) { // Since a solution load is not yet completed, there is no document available to answer this query. // The solution explorer presumes that if somebody doesn't answer for a file, they never will. // See Providers\GraphContextAttachedCollectionSource.cs for more. Therefore we should answer by setting // ContainsChildren property to either true or false, so any following updates will be tractable. // We will set it to false since the solution explorer assumes the default for this query response is 'false'. // Todo: we may need fallback to check if this node actually represents a C# or VB language // even when its extension fails to say so. One option would be to call DTEWrapper.IsRegisteredForLangService, // which may not be called here however since deadlock could happen. // The Uri returned by `GetNestedValueByName()` above isn't necessarily absolute and the `OriginalString` is // the only property that doesn't throw if the UriKind is relative, so `OriginalString` must be used instead // of `AbsolutePath`. var path = uri.OriginalString; // Recorded in https://github.com/dotnet/roslyn/issues/27805, we // have seen crashes because the URI in the graph node has the // following form, including the quotes (which are invalid path // characters): // C:\path\to\"some path\App.config" // So we avoid calling Path.GetExtension here. Alternatively, we // could check for illegal path characters directly first, but then // that check would actually happen twice because GetExtension will // also perform the check. if (path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".vb", StringComparison.OrdinalIgnoreCase)) { graphBuilder.AddDeferredPropertySet(node, DgmlNodeProperties.ContainsChildren, false); } } } } } } return(graphBuilder); }
protected override bool CanHandle(IGraphContext graphContext) { return(graphContext.Direction == GraphContextDirection.Self && graphContext.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren)); }
public abstract void BuildGraph( IGraphContext graphContext, string projectPath, IDependency dependency, GraphNode dependencyGraphNode, TargetedDependenciesSnapshot targetedSnapshot);
internal GremlinContext(IGraphContext connector) : base(connector) { }
/// <summary> /// Works simmilar to ExecuteNextAsyc<T> from IDocumentQuery<T> and allows to deserialize the results /// to custom objects of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="gremlinQuery">ExtensionObject IDocumentQuery</param> /// <param name="context">Context that can store GraphElements. If you retrieved vertices and then an edge refering to those vertices they will be automatically linked.</param> /// <returns></returns> public static async Task <IList <T> > ExecuteNextAsyncAsPOCO <T>(this IDocumentQuery gremlinQuery, IGraphContext context = null) // where T : new() { List <T> result = new List <T>(); IGraphSerializer serializer = null; Type targetType = typeof(T); if (gremlinQuery.GetType().GenericTypeArguments[0] != typeof(Vertex)) { IDocumentQuery <Edge> edgeQuery = gremlinQuery as IDocumentQuery <Edge>; var resultSet = await edgeQuery.ExecuteNextAsync <Edge>(); foreach (Edge e in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(e, out string inVTypeString, out string outVTypeString); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(e, out object edge); result.Add((T)edge); } } else { IDocumentQuery <Vertex> vertexQuery = gremlinQuery as IDocumentQuery <Vertex>; var resultSet = await vertexQuery.ExecuteNextAsync <Vertex>(); foreach (Vertex v in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(v); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(v, out object vertex); result.Add((T)vertex); } } return(result); }
internal EdgeGraphSet(IGraphContext context, bool useVerticesIdsAsEdgeId) { _context = context; _useVerticesIdsAsEdgeId = useVerticesIdsAsEdgeId; }
public GraphRepository(IGraphContext ctx) { _ctx = ctx; }
private static void OnContextChange(IGraphContext context) { GraphClipboard.context = context; }
protected void RegisterAnyEngineRoute(string instanceModule, string frontendEngine, IGraphContext graphContext, string engineModule = "Associativy.Frontends") { RegisterEngineRoute(instanceModule + "/{controller}/{action}", instanceModule, frontendEngine, graphContext, engineModule); }
/// <inheritdoc /> public abstract bool TryHandleRequest(IGraphContext graphContext);
protected void RegisterDefaultEngineRoute(string instanceModule, string frontendEngine, IGraphContext graphContext, string engineModule = "Associativy.Frontends") { RegisterEngineRoute(instanceModule + "/" + frontendEngine + "Engine/{action}", instanceModule, frontendEngine, graphContext, engineModule); }
public override bool CanHandleRequest(IGraphContext graphContext) { return(graphContext.Direction == GraphContextDirection.Custom); }
public FrontendContext(IEngineContext engineContext, IGraphContext graphContext) { EngineContext = engineContext; GraphContext = graphContext; }
/// <summary> /// Generates search graph containing nodes matching search criteria in Solution Explorer /// and attaches it to correct top level node. /// </summary> private void Search(IGraphContext graphContext) { string searchParametersTypeName = typeof(ISolutionSearchParameters).GUID.ToString(); ISolutionSearchParameters searchParameters = graphContext.GetValue <ISolutionSearchParameters>(searchParametersTypeName); string searchTerm = searchParameters?.SearchQuery.SearchString?.ToLowerInvariant(); if (searchTerm == null) { return; } var cachedDependencyToMatchingResultsMap = new Dictionary <string, HashSet <IDependency> >(StringComparer.OrdinalIgnoreCase); var searchResultsPerContext = new Dictionary <string, HashSet <IDependency> >(StringComparer.OrdinalIgnoreCase); System.Collections.Generic.IReadOnlyCollection <IDependenciesSnapshotProvider> snapshotProviders = AggregateSnapshotProvider.GetSnapshotProviders(); foreach (IDependenciesSnapshotProvider snapshotProvider in snapshotProviders) { IDependenciesSnapshot snapshot = snapshotProvider.CurrentSnapshot; if (snapshot == null) { continue; } searchResultsPerContext[snapshotProvider.ProjectFilePath] = SearchFlat( searchTerm.ToLowerInvariant(), snapshot); } foreach (IDependenciesSnapshotProvider snapshotProvider in snapshotProviders) { IDependenciesSnapshot snapshot = snapshotProvider.CurrentSnapshot; if (snapshot == null) { continue; } IEnumerable <IDependency> allTopLevelDependencies = snapshot.GetFlatTopLevelDependencies(); HashSet <IDependency> matchedDependencies = searchResultsPerContext[snapshotProvider.ProjectFilePath]; using (var scope = new GraphTransactionScope()) { foreach (IDependency topLevelDependency in allTopLevelDependencies) { ITargetedDependenciesSnapshot targetedSnapshot = snapshot.Targets[topLevelDependency.TargetFramework]; if (!cachedDependencyToMatchingResultsMap .TryGetValue(topLevelDependency.Id, out HashSet <IDependency> topLevelDependencyMatches)) { IDependenciesGraphViewProvider viewProvider = ViewProviders .FirstOrDefaultValue((x, d) => x.SupportsDependency(d), topLevelDependency); if (viewProvider == null) { continue; } bool processed = viewProvider.MatchSearchResults( snapshotProvider.ProjectFilePath, topLevelDependency, searchResultsPerContext, out topLevelDependencyMatches); if (!processed) { if (matchedDependencies.Count == 0) { continue; } topLevelDependencyMatches = GetMatchingResultsForDependency( topLevelDependency, targetedSnapshot, matchedDependencies, cachedDependencyToMatchingResultsMap); } cachedDependencyToMatchingResultsMap[topLevelDependency.Id] = topLevelDependencyMatches; } if (topLevelDependencyMatches.Count == 0) { continue; } GraphNode topLevelNode = Builder.AddTopLevelGraphNode(graphContext, snapshotProvider.ProjectFilePath, topLevelDependency.ToViewModel(targetedSnapshot)); foreach (IDependency matchedDependency in topLevelDependencyMatches) { GraphNode matchedDependencyNode = Builder.AddGraphNode(graphContext, snapshotProvider.ProjectFilePath, topLevelNode, matchedDependency.ToViewModel(targetedSnapshot)); graphContext.Graph.Links.GetOrCreate(topLevelNode, matchedDependencyNode, label: null, GraphCommonSchema.Contains); } if (topLevelNode != null) { // 'node' is a GraphNode for top level dependency (which is part of solution explorer tree) // Setting ProjectItem category (and correct GraphNodeId) ensures that search graph appears // under right solution explorer hierarchy item topLevelNode.AddCategory(CodeNodeCategories.ProjectItem); } } scope.Complete(); } } graphContext.OnCompleted(); }
protected void RegisterRoute(Route route, IGraphContext graphContext) { RegisterRoute(graphContext.Stringify() + route.Url, route, graphContext); }
protected override bool CanHandle(IGraphContext graphContext) { return(graphContext.Direction == GraphContextDirection.Contains); }
// Analysis are conceptually reference-bound, but practically context-bound, // so it's faster to avoid the reference-to-context lookup if we can avoid it. public static IAnalyser Analyser(this object target, IGraphContext context) { return(context.analyserProvider.GetDecorator(target)); }
protected VertexTreeRoot(IGraphContext context) { _context = context; }
public static TAnalyser Analyser <TAnalyser>(this object target, IGraphContext context) where TAnalyser : IAnalyser { return(context.analyserProvider.GetDecorator <TAnalyser>(target)); }
public GraphBuilder(IGraphContext context) { Context = context; }
public static TAnalysis Analysis <TAnalysis>(this object target, IGraphContext context) where TAnalysis : IAnalysis { return((TAnalysis)target.Analysis(context)); }
private void CreateValues(IGraphContext context, GraphNode node) { StyleSheet stylesheet = CssGraphProvider.GetOrCreateStyleSheet(node, _fileService); GraphNodeId urlPart = node.Id + GraphNodeId.GetPartial(CssGraphSchema.CssStyleSheet, stylesheet); // Mixin if (FindCssItems<LessMixinDeclaration>(stylesheet).Count > 0) { GraphNode mixinNode = CreateParentNode(context, urlPart, "Mixins", LessGraphSchema.LessMixinParent); context.Graph.Links.GetOrCreate(node, mixinNode, "mixin", GraphCommonSchema.Contains); context.OutputNodes.Add(mixinNode); } // Variable if (FindCssItems<LessVariableDeclaration>(stylesheet).Count > 0) { GraphNode variableNode = CreateParentNode(context, urlPart, "Variables", LessGraphSchema.LessVariableParent); context.Graph.Links.GetOrCreate(node, variableNode, "hat", GraphCommonSchema.Contains); context.OutputNodes.Add(variableNode); } }
/// <summary> /// Can be called on a GraphTraversal to retrieve Vertices or Edges as custom objects. /// </summary> /// <typeparam name="T">Type of custom object that represents the Vertex or Edge</typeparam> /// <param name="trav">Extension Object GraphTraversal</param> /// <param name="context">Context that can store GraphElements. If you retrieved vertices and then an edge refering to those vertices they will be automatically linked.</param> /// <returns></returns> public static async Task <IList <T> > NextAsPOCO <T>(this GraphTraversal trav, IGraphContext context = null) // where T : new() { IGraphSerializer serializer = null; List <T> result = new List <T>(); /// Verify if the OutputFormat of the GraphCommand was set to GraphSON! Type graphTraversalType = typeof(GraphTraversal); Type targetType = typeof(T); FieldInfo outputFormatPropertyInfo = graphTraversalType.GetField("outputFormat", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); string outputFormat = outputFormatPropertyInfo.GetValue(trav).ToString(); if (!outputFormat.StartsWith("GraphSON")) { throw new Exception("OutputFormat of GraphCommand needs to be set to GRAPHSON!"); } // GraphSerializer<T> serializer = GraphSerializerFactory.CreateGraphSerializer<T>(context); // Edges and Vertices must be treated separately if (GraphSerializer.GetElementType(typeof(T)) == GraphElementType.Edge) { List <Edge> resultSet = await trav.NextAsModelAsync <Edge>(); foreach (Edge e in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(e, out string inVTypeString, out string outVTypeString); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(e, out object edge); result.Add((T)edge); } } else { List <Vertex> resultSet = await trav.NextAsModelAsync <Vertex>(); foreach (Vertex v in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(v); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(v, out object vertex); result.Add((T)vertex); } //Alternative implementation TODO: Measure speed //========================== //foreach (var graphSON in trav) //{ // List<T> partialResult = serializer.DeserializeGraphSON(graphSON); // foreach (T r in partialResult) // result.Add(r); //} } return(result); }
internal static List <IGraphQuery> GetGraphQueries(IGraphContext context) { var graphQueries = new List <IGraphQuery>(); if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren)) { graphQueries.Add(new ContainsChildrenGraphQuery()); } if (context.Direction == GraphContextDirection.Contains || (context.Direction == GraphContextDirection.Target && context.LinkCategories.Contains(CodeLinkCategories.Contains))) { graphQueries.Add(new ContainsGraphQuery()); } if (context.LinkCategories.Contains(CodeLinkCategories.InheritsFrom)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new InheritsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new InheritedByGraphQuery()); } } if (context.LinkCategories.Contains(CodeLinkCategories.SourceReferences)) { graphQueries.Add(new IsUsedByGraphQuery()); } if (context.LinkCategories.Contains(CodeLinkCategories.Calls)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new CallsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new IsCalledByGraphQuery()); } } if (context.LinkCategories.Contains(CodeLinkCategories.Implements)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new ImplementsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new ImplementedByGraphQuery()); } } if (context.LinkCategories.Contains(RoslynGraphCategories.Overrides)) { if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new OverridesGraphQuery()); } else if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new OverriddenByGraphQuery()); } } if (context.Direction == GraphContextDirection.Custom) { var searchParameters = context.GetValue <ISolutionSearchParameters>(typeof(ISolutionSearchParameters).GUID.ToString()); if (searchParameters != null) { // WARNING: searchParameters.SearchQuery returns an IVsSearchQuery object, which // is a COM type. Therefore, it's probably best to grab the values we want now // rather than get surprised by COM marshalling later. graphQueries.Add(new SearchGraphQuery(searchParameters.SearchQuery.SearchString)); } } return(graphQueries); }
private void CreateOutline(IGraphContext context) { using (var scope = new GraphTransactionScope()) { context.Graph.Links.Remove(context.Graph.Links.Where(l => l.Label == "mixin" || l.Label == "hat")); foreach (GraphNode node in GetAllowedFiles(context.InputNodes)) { Uri url = node.Id.GetNestedValueByName<Uri>(CodeGraphNodeIdName.File); _cache[url] = context; node.AddCategory(LessGraphSchema.LessFile); CreateValues(context, node); } scope.Complete(); } }