Condividi tramite


Map dependencies across your code on dependency graphs

When you want to understand dependencies across your code, map them with Visual Studio Ultimate. When you want to understand dependencies across all your code, visualize them by creating code maps (Visual Studio Ultimate only). This helps you see how the code fits together without reading through files and lines of code.

Graph with selected items and expanded groups

Here are some videos:

Here's what you'll need:

  • Visual Studio Ultimate 2013

  • Visual C# .NET or Visual Basic .NET code in a solution or assemblies (.dll or .exe)

  • Native or managed C or C++ code in Visual C++ projects, header files (.h or #include), or binaries

  • Visual Studio 2013 Update 3 to map dependencies in:

    • Projects that share code across multiple apps

    • X++ projects and assemblies made from .NET modules for Microsoft Dynamics AX

    You can also drag assemblies and binaries from Windows Explorer to an existing graph and get color-coded relationships.

Get started here:

  • To see overall dependencies across your solution, go to the Architecture menu. Click Generate Dependency Graph, For Solution.

    - or -

  • To see specific dependencies in your solution, open Solution Explorer. Select the projects, assembly references, folders, files, types, or members that interest you. On the Solution Explorer toolbar, click Create a new graph documentCreate New Graph From Selected Nodes Button.

You can also:

  • See dependencies between C or C++ source files and header files

  • Share dependency graphs

  • Create graphs programmatically

See overall dependencies

See dependencies across your solution

  1. On the Architecture menu, click Generate Dependency Graph, For Solution.

    You get a graph that shows the top-level assemblies and aggregated links between them. The wider the aggregate link, the more dependencies it represents. The Externals group contains anything outside your solution, including platform dependencies. External assemblies show only those items that are used.

    Top-level dependency graph of assemblies

  2. To see inside an assembly, expand it. Move your mouse pointer on top of an assembly, and then click the chevron (^) when it appears. (Keyboard: Select the item, then press the PLUS key (+).) To explore deeper levels of code, do the same for namespaces, types, and members.

    Dependency graph with grouped nodes

    By default, containment relationships appear as groups, which you can expand and collapse. To see group relationships as links, on the graph shortcut menu, click Group, Turn Off Grouping.

    Dependency graph with nodes and links

  3. To examine items and dependencies represented by an aggregate link, select the link first, and then open its shortcut menu. Click Show, Contributing links in current diagram or Contributing links in a new diagram.

    Visual Studio expands the groups at both ends of the link and shows only those items and dependencies that participate in the link.

  4. To get more information about an item or link, move the pointer on top of the item until a tooltip appears. This shows the categories that a link represents.

  5. To see what the link color means, on the graph toolbar, click Legend.

    If you see a green link, it might not mean there's just an inheritance relationship. There might also be method calls, but these are hidden by the inheritance relationship.

  6. To see dependencies between members across groups, click an item on the graph.

    Graph with selected items and expanded groups

  7. To find potential problems in your code, run an analyzer.

See:

See dependencies across assemblies or binaries

  • Create a blank graph, or open an existing graph (.dgml file). From outside Visual Studio, drag the assemblies or binaries to the graph.

    Note

    You can drag assemblies or binaries from Windows Explorer only if you are running Windows Explorer and Visual Studio at the same User Access Control (UAC) permissions level. For example, if UAC is turned on, and you are running Visual Studio as Administrator, then Windows Explorer will block the dragging operation. To work around this, make sure that Visual Studio is running as Administrator, or turn UAC off. Note that in Windows 8, Windows Explorer is File Explorer.

Create a blank graph

  1. In Solution Explorer, open the shortcut menu for your top-level solution node. Click Add, New Item.

  2. Under Installed, click General.

  3. In the right pane, click Directed Graph Document.

    You now have a blank graph, which appears in your solution's Solution Items folder.

    To open a new blank graph without adding it to your solution, on the File menu, click New, File.

    To add a blank graph to a modeling project, open the Architecture menu, click New Diagram.

Q & A

Q: Why does it take so long to create the graph?

A: When you generate a graph for the first time, Visual Studio indexes all the dependencies that it finds. This process might take some time, especially for large solutions, but this will improve later performance. If your code changes, Visual Studio reindexes just the updated code. If you don't want to wait for the graph to finish, you can cancel this step at any time and try this instead:

  • Graph only the dependencies that interest you.

  • Before you generate the graph for an entire solution, reduce the solution scope.

Although Visual Studio can run with 1 GB of memory, we recommended that your computer have at least 2 GB of memory to avoid long delays while Visual Studio creates the code index and generates the graph.

It might take more time to create graphs or add items to a graph from Solution Explorer when a project item's Copy to Output Directory property is set to Copy Always. This might cause issues with incremental builds and Visual Studio to rebuild the project each time. To increase performance, change this property to Copy if newer or PreserveNewest. See Incremental Builds.

Q: Why didn't Visual Studio create my graph?

A: This might happen because none of the projects in your solution were built successfully. Visual Studio generates a graph if at least one project builds successfully. The graph will show dependencies only for successfully-built code. If build errors happen for certain components, then those errors appear on the graph. Make sure that a component actually builds and has dependencies on it before you make architectural decisions based on the graph.

See specific dependencies

For example, suppose you have a code review to perform in some files with pending changes. To see the dependencies in those changes, create a dependency graph from those files.

Dependency graph with grouped nodes

See specific dependencies in your solution

  1. Open Solution Explorer. Select the projects, assembly references, folders, files, types, and members that interest you.

  2. Graph your items and their members. On the Solution Explorer toolbar, click Create a new graph documentCreate New Graph From Selected Nodes Button.

    To find items that have dependencies on types or members, open the type or member's shortcut menu from Solution Explorer. Click the dependency type. Then select the results.

    How to visualize specific code

    To include parent hierarchies with your items, on the Solution Explorer toolbar, open the Create a new graph document… list. Click New Dependency Graph with Ancestors.

    How to visualize specific code and parents

    You can also drag items to a blank or existing graph. To create a blank graph, on the File menu, click New, File, Directed Graph Document. To include the parent hierarchy for your items, press and hold the CTRL key while you drag items.

    Note

    When you add items from a project that's shared across multiple apps, like Windows Phone or Windows Store, those items appear on the map with the currently active app project. If you change context to another app project and add more items from the shared project, those items now appear with the newly active app project. Operations that you perform with an item on the map apply only to those items that share the same context.

  3. To explore items, expand them. Move the mouse pointer on top of an item, then click the chevron (^) button when it appears. To expand all items, open the shortcut menu for the graph. Click Group, Expand All.

    Note

    This option isn't available if expanding all groups creates an unusable graph or memory issues.

  4. To see members that are in the code but don't appear on the graph, click Refetch ChildrenRefetch Children Icon. These group members appear with a different style so you can see them more easily. See Edit and customize dependency graphs.

  5. To see more items related to those on the graph, open that item's shortcut menu. Click Show and the kind of relationship that interests you.

    For an assembly, click:

    Referenced Assemblies

    Add assemblies that this assembly references. External assemblies appear in the Externals group.

    Referencing Assemblies

    Add assemblies in the solution that reference this assembly.

    For a class, click:

    Base Types

    For a class, add the base class and the implemented interfaces.

    For an interface, add the base interfaces.

    Derived Types

    For a class, add the derived classes.

    For an interface, add the derived interfaces and the implementing classes or structs.

    All Base Types

    Add the base class or interface hierarchy recursively.

    All Derived Types

    For a class, add all the derived classes recursively.

    For an interface, add all the derived interfaces and implementing classes or structs recursively.

    Containment Hierarchy

    Add the parent container hierarchy.

    Used Types

    Add all classes and their members that this class uses.

    Used-By Types

    Add all classes and their members that use this class.

    For a method, click:

    Containment Hierarchy

    Add the parent container hierarchy.

    Called Methods

    Add methods that this method calls.

    Called-By Methods

    Add methods that call this method.

    Overridden Methods in Base Types

    For a method that overrides other methods or implements an interface's method, add all the abstract or virtual methods in base classes that are overridden and, if any, the interface's method that is implemented.

    Referenced Fields

    Add fields that this method references.

    For a field, click:

    Containment Hierarchy

    Add the parent container hierarchy.

    Referencing Methods

    Add methods that reference this field.

See specific dependencies in assemblies or binaries

  1. On the Architecture menu, click Windows, Architecture Explorer.

  2. In the first column, under File System, click Select Files.

  3. In the Open box, find and select the assemblies or binaries. Click Open to add them to the next column in Architecture Explorer.

  4. In the next column, select the assemblies or the binaries.

    By default, the next column shows items contained by the selected items.

    Tip

    To select other related items, expand the collapsed column to the right of the column with your selections. Under Node Navigation, select the kinds of items that interest you. Under Outbound Navigation or Inbound Navigation, select the kinds of relationships that interest you. See Find code with Architecture Explorer.

  5. Find and select all the items that you want to put on the graph.

  6. To create a new graph, on the Architecture Explorer toolbar, click Create a new graph document from all the selected nodesCreate New Graph From Selected Nodes Button.

    -or-

    To add your selection to a graph, follow these steps:

    1. Open the graph's .dgml file, or create a blank graph.

    2. On the Architecture Explorer tool bar, click Add all the selected nodes to the currently visible graph documentAdd All Selected Nodes to Graph Button.

      -or-

      Drag items from Architecture Explorer to the graph.

See dependencies between C and C++ source files and header files

If you want to create more complete graphs for C++ projects, set the browse information compiler option (/FR) on those projects. See /FR, /Fr (Create .Sbr File). Otherwise, a message appears and prompts you to set this option. If you select OK, this sets the option for just the current graph. You can choose to hide the message for all later graphs. If you hide this message, you can make it appear again. Set the following registry key to 0 or delete the key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\NativeProvider : AutoEnableSbr

When you open a solution that contains Visual C++ projects, it might take some time to update the IntelliSense database. During this time, you might not be able to create dependency graphs for header (.h or #include) files until the IntelliSense database finishes updating. You can monitor the update progress in the Visual Studio status bar. To resolve issues or messages that appear because certain IntelliSense settings are disabled, see Troubleshoot graphs for C and C++ code.

  • To see dependencies between all source files and header files in your solution, on the Architecture menu, click Generate Dependency Graph, For Include File.

    Dependency graph for native code

  • To see dependencies between the currently open file and related source files and header files, open either the source file or the header file. Open the file shortcut menu anywhere inside the file. Click Generate Graph of Include Files.

    First-level dependency graph for .h file

Troubleshoot graphs for C and C++ code

These items aren't supported for C and C++ code:

  • Base types don't appear on graphs that include the parent hierarchy.

  • Most Show menu items aren't available for C and C++ code.

These issues might happen when you create dependency graphs for C and C++ code:

Issue

Possible cause

Resolution

The dependency graph failed to generate.

No projects in the solution were built successfully.

Fix the build errors that occurred and then regenerate the graph.

Visual Studio becomes unresponsive when you try to generate a dependency graph from the Architecture menu.

The program database (.pdb) file might be corrupted.

A .pdb file stores debugging information, such as type, method, and source file information.

Rebuild the solution and then try again.

Certain settings for the IntelliSense browsing database are disabled.

Certain IntelliSense settings might be disabled in the Visual Studio Options dialog box.

Turn on the settings to enable them.

See Options, Text Editor, C/C++, Advanced.

The message Unknown Methods appears on a method node.

This issue occurs because the name of the method cannot be resolved.

The binary file might not have a base relocation table.

Turn on the /FIXED:NO option in the linker.

See /FIXED (Fixed Base Address).

The program database (.pdb) file might not be built.

A .pdb file stores debugging information, such as type, method, and source file information.

Turn on the /DEBUG option in the linker.

See /DEBUG (Generate Debug Info).

Cannot open or find the .pdb file in the expected locations.

Make sure that the .pdb file exists in the expected locations.

Debug information has been stripped from the .pdb file.

If the /PDBSTRIPED option was used in the linker, include the complete .pdb file instead.

See /PDBSTRIPPED (Strip Private Symbols).

The caller is not a function and is either a thunk in the binary file or a pointer in the data section.

When the caller is a thunk, try using _declspec(dllimport) to avoid the thunk.

See:

Share dependency graphs

Share the graph with other Visual Studio users

  • Use the File menu to save the graph.

    -or-

    To save the graph as part of specific project, open the shortcut menu for the graph surface. Click Move <DependencyGraphName.dgml> into and the project where you want to save the graph.

    Visual Studio saves the graph as a .dgml file that you can share with other users of Visual Studio Ultimate, Visual Studio Premium, and Visual Studio Professional.

    Note

    Before you share a graph with those who use Visual Studio Premium and Visual Studio Professional, make sure to expand any groups, show hidden nodes and cross-group links, and retrieve any deleted nodes that you want others to see on your graph. Otherwise, other users won't be able to see these items.

    The following error might occur when you save a graph that is in a modeling project or was copied from a modeling project to another location:

    "Cannot save fileName outside the project directory. Linked items are not supported."

    Visual Studio shows the error, but creates the saved version anyway. To avoid the error, create the graph outside the modeling project. You can then save it to the location that you want. Just copying the file to another location in the solution, and then trying to save it will not work.

Export the graph as an image so you can copy it into other applications, such as Microsoft Word or PowerPoint

  1. Open the graph surface's shortcut menu. Click Edit, Copy Image.

  2. Paste the image into another application.

Export the graph as an XPS file so you can see it in XML or XAML viewers like Internet Explorer

  1. Open the graph surface's shortcut menu. Click Save As XPS.

  2. Browse to where you want to save the file.

  3. Name the graph. Make sure that the Save as type box is set to XPS files (*.xps). Click Save.

Create graphs programmatically

To create graph documents (.dgml files) so you can work during batch processing, run the GraphCmd.exe command-line tool. For example, to find dependencies that have changed between builds, run the tool after each build. To find this tool, look in this folder: C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE.

GraphCmd.exe supports only .NET code and generates dependency information only for assemblies or .dgml files, not source code in Visual Studio solution or project files. GraphCmd.exe runs outside Visual Studio, so support for actions in DGQL queries is limited.

Here's the syntax for GraphCmd.exe:

GraphCmd -? -all -exceptions -input File_Name -query File_Name -exec "DGQL_Statement" -output File_Name -path alias=path

Here are the options for GraphCmd.exe:

You can specify these options more than once: -input, -query, -exec, and -path

-?

Display the help for GraphCmd.exe.

-all

Include all intermediate query results, not just for the last node set.

-exceptions

Report the query exceptions as a graph document (.dgml) file.

-input File_Name

Process the specified .dgml file.

This is useful for post-processing a large .dgml file and filtering it so that you can visualize it more easily in Visual Studio.

-query File_Name

Run the specified Directed Graph Query Language (DGQL or .dgql) file.

See:

-exec "DGQL_Statement"

Run the specified DGQL statement.

See Understanding Directed Graph Query Language (DGQL).

-output File_Name

Output the specified .dgml file.

-path alias=path

Specify a new alias to use in the input and output of DGML documents.

For example:

GraphCmd -output MyGeneratedGraph.dgml -path "MyPathAlias=C:\Program Files\..."

See Aliases for Commonly-Used Paths.

Aliases for commonly-used paths

Aliases for commonly-used paths reduce the size of the .dgml file and the time required to load or save the file. To create an alias, add a <Paths></Paths> section at the end of the .dgml file. In this section, add a <Path/> element to define an alias for the path:

<Paths>
   <Path Id="MyPathAlias" Value="C:\...\..." />
</Paths>

To reference the alias from an element in the .dgml file, enclose the Id of the <Path/> element with a dollar sign ($) and parentheses (()):

<Nodes>
   <Node Id="MyNode" Reference="$(MyPathAlias)MyDocument.txt" />
</Nodes>
<Properties>
   <Property Id="Reference" Label="My Document" DataType="System.String" IsReference="True" />
</Properties>

To edit .dgml files, see Edit and customize dependency graphs.

Find out more about Directed Graph Query Language (DGQL)

DGQL is a lightweight query language that you can use to build DGML. A DGQL statement follows an alternating pattern of node selection and actions such that each node selection creates input for the next action, whose output becomes input for the next node selection, and so on.

The format of a DGQL statement is:

<node selection> / <action> / <node selection> / <action> / ...

The following table describes the DGQL syntax used to select nodes:

*

Select all nodes.

+ "text"

Select all nodes that contain "text".

+ Id.Equals("text")

Select all nodes whose Id is equal to "text".

+ Background.Contains("text")

Select all nodes whose Background attribute has a value that contains the string "text".

+ "text1" + "text2" + ...

Select all nodes that match "text1" or "text2".

+ MyProperty="True"

Select all nodes that have a property named MyProperty whose value is "True".

- Label.Contains("text")

Select all nodes except those that have a Label attribute that Contains the string "text".

+ Category.Is("MyCategory")

Select all nodes that have a category named MyCategory or that inherits from MyCategory.

The following table describes examples of direct actions that can be performed on selected nodes:

Example action

Description

Microsoft.Contains

Return all nodes that are contained by the input nodes. You can replace Contains with a different link category.

Microsoft.Open

Open the source code for the input nodes.

Note

Works only within Visual Studio.

Microsoft.AllOutBoundLinks

Return all nodes that are the target of an outgoing link from the input nodes.

Microsoft.AllInboundLinks

Return all nodes that are the source end of a link to the input nodes.

Microsoft.Core.CreateGroupsByProperties

Invoke the GroupByProperties action.

Microsoft.AllNodes

Return all nodes in the entire graph thus far.

Data-driven actions select items based only on the data in the input nodes and links. When matching categories using data-driven actions, inherited categories are included. The following table describes examples of data-driven actions:

Type

Description

Node:Both:Category

Return all nodes that have the category Category and are connected with the input nodes by a link that points in either direction.

Link:Both:Category

Return all nodes that are connected with the input nodes by a link that points in either direction and has the category Category.

Link:Backward:Category

Return all nodes that point to the input nodes with a link that has the category Category.

Link:Forward:Category

Return all nodes that point from the input nodes with a link that has the category Category.

Tips

  • Typically, there is a "default" action for a given set of input nodes, which is selected automatically by Architecture Explorer. To get the same behavior, use an empty action: //

  • Whitespace is not significant in DGQL, so you can format your query to fit on one line if necessary. This is useful when you use the –exec option with GraphCmd.

  • When debugging DGQL, use the action "Execute Expanded" in Architecture Explorer to help you see each step of the query and find the step that is not producing the expected results.

Example

The following DGQL statement performs a query as described in the following steps:

+ Id.Equals("Microsoft.Solution.ClassView") / "Microsoft.Solution.ClassView" / * / "Node:Both:CodeSchema_Class" / + CodeSchemaProperty_IsPublic.Equals("True")
  1. Click the Class View node in the first column of Architecture Explorer.

  2. Perform the action "Microsoft.Solution.ClassView", returning all the namespaces in the solution. 

  3. Use * to select all the namespaces.

  4. Select all nodes that have the category CodeSchema_Class and are related to those namespaces by a link in either direction. These will usually be containment links.

  5. Filter the resulting classes to only those that have the property CodeSchemaProperty_IsPublic="True".

Technically, the action "Microsoft.Solution.ClassView" is unnecessary because it is the "default" action for the Class View node. Therefore, you can replace that action with // to simplify the query and format it on a single line as follows:

+Id.Equals("Microsoft.Solution.ClassView")//*/"Node:Both:CodeSchema_Class"/+CodeSchemaProperty_IsPublic.Equals("True")

What else can I do?

Where can I get more information?

Category

Links

Forums

Blogs