visual studio карта кода
Совместное использование карт кода
карты кода можно сохранять как часть проекта Visual Studio, в виде изображения или XPS-файла.
совместное использование карт кода с другими пользователями Visual Studio
Чтобы сохранить карту как часть конкретного проекта, на панели инструментов Map нажмите кнопку поделиться > . DGML в, а затем выберите проект, в котором нужно сохранить карту.
Перед тем как предоставить общий доступ к карте пользователям Visual Studio Professional, разверните все группы, отобразите скрытые узлы и связи между группами и извлеките все удаленные узлы, которые нужно показать другим пользователям. В противном случае другие пользователи не увидят эти элементы.
При сохранении карты, находящейся в проекте моделирования или скопированной из такого проекта в другое место, может возникнуть следующая ошибка:
«Невозможно сохранить имяФайла вне каталога проекта. Связанные элементы не поддерживаются.»
Visual Studio выводит ошибку, но в любом случае создает сохраненную версию. Чтобы избежать этой ошибки, создавайте карту вне проекта моделирования. Затем ее можно сохранить в нужном месте. Простое копирование файла в другое место в решении и последующая попытка сохранения не помогают.
Экспорт схемы кода в виде изображения
при экспорте схемы кода в виде изображения ее можно скопировать в другие приложения, например Microsoft Word или PowerPoint.
На панели инструментов «схема кода» выберите общий доступ к > электронной почте как изображение или Копировать изображение.
Вставьте изображение в другое приложение.
Экспорт схемы в виде XPS-файла
При экспорте схемы кода в виде XPS-файла ее можно увидеть в средствах просмотра XML или XAML, таких как Internet Explorer.
На панели инструментов «схема кода» выберите общий доступ к > электронной почте как портативный компьютер XPS или Сохранить как портативный компьютер XPS.
Выберите место для сохранения файла.
Укажите имя для карты кода. Убедитесь, что для поля Тип файла выбрано значение XPS-файлы ( * XPS). Выберите Сохранить.
Карты кода для проектов C++
Если нужно создать более полные карты для проектов C++, установите в этих проектах параметр компилятора для просмотра информации (/FR). В противном случае отобразится запрос на установку этого параметра. При нажатии кнопки ОК этот параметр будет установлен только для текущей карты. Вы можете скрыть это сообщение для всех последующих карт.
При открытии решения, содержащего проекты Visual C++, обновление базы данных IntelliSense может занять некоторое время. В течение этого времени создание карт кода для файлов заголовков (h или) может оказаться невозможным #include до тех пор, пока база данных IntelliSense не завершит обновление. Вы можете наблюдать за ходом обновления в строке состояния Visual Studio.
чтобы просмотреть зависимости между всеми исходными файлами и файлами заголовков в решении, выберите архитектура > создать Graph включаемых файлов.
Чтобы просмотреть зависимости между открытым файлом и связанными с ним исходными файлами и файлами заголовков, откройте либо исходный файл, либо файл заголовка. Откройте контекстное меню в любом месте файла. Выберите пункт Создать диаграмму включаемых файлов.
Устранение неполадок в картах кода для кода C и C++
Для кода C и C++ не поддерживаются указанные ниже элементы.
Базовые типы не отображаются на картах, включающих родительскую иерархию.
Большинство пунктов меню Показать недоступны для кода C и C++.
Эти проблемы могут возникнуть при создании карт кода для кода C и C++:
Map dependencies with code maps
In this article, you’ll learn how to visualize dependencies across your code with code maps.
What are code maps?
In Visual Studio, code maps help you more quickly see how your program code fits together without reading through files and lines of code. With these maps, you can see the organization and relationships in your code, including its structure and its dependencies, how to update it, and estimate the cost of proposed changes.
You can map dependencies for code in these languages:
Visual C# or Visual Basic 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
For projects other than C# or Visual Basic, there are fewer options for starting a code map or adding items to an existing code map. For example, you cannot right-click an object in the text editor of a C++ project and add it to a code map. However, you can drag and drop individual code elements or files from Solution Explorer, Class View, and Object Browser.
Prerequisites
To create and edit code maps, you need Visual Studio Enterprise edition. However, in Visual Studio Community and Professional editions, you can open diagrams that were generated in Enterprise edition, but you cannot edit them.
Before you share maps created in Visual Studio Enterprise with others who use Visual Studio Professional, make sure that all the items on the map (such as hidden items, expanded groups, and cross-group links) are visible.
Add a code map
You can create an empty code map and drag items onto it, including assembly references, files and folders, or you can generate a code map for all or part of your solution.
To add an empty code map:
In Solution Explorer, open the shortcut menu for your top-level solution node. Choose Add > New Item.
In the Add New Item dialog, under Installed, choose the General category.
Choose the Directed Graph Document(.dgml) template and then select Add.
This template may not appear alphabetically, so scroll down to the bottom of the template list if you don’t see it.
A blank map appears in your solution’s Solution Items folder.
Similarly, you can create a new code map file without adding it to your solution by selecting Architecture > New Code Map or File > New > File.
Generate a code map for your solution
To see all the dependencies in your solution:
On the menu bar, choose Architecture > Generate Code Map for Solution. If your code hasn’t changed since the last time you built it, you can select Architecture > Generate Code Map for Solution Without Building instead.
A map is generated that shows the top-level assemblies and aggregated links between them. The wider the aggregate link, the more dependencies it represents.
Use the Legend button on the code map toolbar to show or hide the list of project type icons (such as Test, Web, and Phone Project), code items (such as Classes, Methods, and Properties), and relation types (such as Inherits From, Implements, and Calls).
This example solution contains Solution Folders (Tests and Components), Test Projects, Web Projects, and assemblies. By default, all containment relationships appear as groups, which you can expand and collapse. The Externals group contains anything outside your solution, including platform dependencies. External assemblies show only those items that are used. By default, system base types are hidden on the map to reduce clutter.
To drill down into the map, expand the groups that represent projects and assemblies. You can expand everything by pressing CTRL+A to select all the nodes and then choosing Group, Expand from the shortcut menu.
However, this may not be useful for a large solution. In fact, for complex solutions, memory limitations may prevent you from expanding all the groups. Instead, to see inside an individual node, expand it. Move your mouse pointer on top of the node and then click the chevron (down arrow) when it appears.
Or use the keyboard by selecting the item then pressing the plus key (+). To explore deeper levels of code, do the same for namespaces, types, and members.
For more details about working with code maps using the mouse, keyboard, and touch, see Browse and rearrange code maps.
To simplify the map and focus on individual parts, choose Filters on the code map toolbar and select just the types of nodes and links you are interested in. For example, you can hide all the Solution Folder and Assembly containers.
You can also simplify the map by hiding or removing individual groups and items from the map, without affecting the underlying solution code.
To see the relationships between items, select them in the map. The colors of the links indicate the types of relationship, as shown in the Legend pane.
In this example, the purple links are calls, the dotted links are references, and the light blue links are field access. Green links can be inheritance, or they may be aggregate links that indicate more than one type of relationship (or category).
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. To see specific types of links, use the checkboxes in the Filters pane to hide the types you aren’t interested in.
To get more information about an item or link, move the pointer on top of it until a tooltip appears. This shows details of a code element or the categories that a link represents.
To examine items and dependencies represented by an aggregate link, first select the link and then open its shortcut menu. Choose Show Contributing Links (or Show Contributing Links on New Code Map). This expands the groups at both ends of the link and shows only those items and dependencies that participate in the link.
To focus in on specific parts of the map, you can continue to remove items you aren’t interested in. For example, to drill into class and member view, simply filter all the namespace nodes in the Filters pane.
Another way to focus in on a complex solution map is to generate a new map containing selected items from an existing map. Hold Ctrl while selecting the items you want to focus on, open the shortcut menu, and choose New Graph from Selection.
The containing context is carried over to the new map. Hide Solution Folders and any other containers you don’t want to see using the Filters pane.
Expand the groups and select items in the map to view the relationships.
View dependencies
Suppose you have a code review to perform in some files with pending changes. To see the dependencies in those changes, you can create a code map from those files.
In Solution Explorer, select the projects, assembly references, folders, files, types, or members that you want to map.
You can also drag items from Solution Explorer, Class View, or Object Browser, into a new or existing code map. To include the parent hierarchy for your items, press and hold the Ctrl key while you drag items, or use the Include Parents button on the code map toolbar to specify the default action. You can also drag assembly files from outside Visual Studio, such as from Windows Explorer.
When you add items from a project that’s shared across multiple apps, like Windows Phone or Microsoft 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.
The map shows the selected items within their containing assemblies.
To explore items, expand them. Move the mouse pointer on top of an item, then click the chevron (down arrow) icon when it appears.
To expand all items, select them using Ctrl+A, then open the shortcut menu for the map and choose Group > Expand. However, this option isn’t available if expanding all groups creates an unusable map or memory issues.
Continue to expand items you are interested in, right down to the class and member level if necessary.
To see more items related to those on the map, select one and choose Show Related on the code map toolbar, then select the type of related items to add to the map. Alternatively, select one or more items, open the shortcut menu, and then choose the Show option for the type of related items to add to the map. For example:
For an assembly, choose:
Option | Description |
---|---|
Show Assemblies This References | Add assemblies that this assembly references. External assemblies appear in the Externals group. |
Show Assemblies Referencing This | Add assemblies in the solution that reference this assembly. |
For a namespace, choose Show Containing Assembly, if it’s not visible.
For a class or interface, choose:
Option | Description |
---|---|
Show Base Types | For a class, add the base class and the implemented interfaces. For an interface, add the base interfaces. |
Show Derived Types | For a class, add the derived classes. For an interface, add the derived interfaces and the implementing classes or structs. |
Show Types This References | Add all classes and their members that this class uses. |
Show Types Referencing This | Add all classes and their members that use this class. |
Show Containing Namespace | Add the parent namespace. |
Show Containing Namespace and Assembly | Add the parent container hierarchy. |
Show All Base Types | Add the base class or interface hierarchy recursively. |
Show 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. |
For a method, choose:
Option | Description |
---|---|
Show Methods This Calls | Add methods that this method calls. |
Show Fields This References | Add fields that this method references. |
Show Containing Type | Add the parent type. |
Show Containing Type, Namespace, and Assembly | Add the parent container hierarchy. |
Show Overridden Methods | 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. |
For a field or property, choose:
Option | Description |
---|---|
Show Containing Type | Add the parent type. |
Show Containing Type, Namespace, and Assembly | Add the parent container hierarchy. |
The map shows the relationships. In this example, the map shows the methods called by the Find method and their location in the solution or externally.
To simplify the map and focus on individual parts, choose Filters on the code map toolbar and select just the types of nodes and links you are interested in. For example, turn off display of Solution Folders, Assemblies, and Namespaces.
Создание визуальной карты стека вызовов во время отладки (C#, Visual Basic, C++, JavaScript)
Для визуального отслеживания стека вызовов при отладке можно создать карту кода. Вы можете вести заметки на карте, чтобы следить за деятельностью кода и сосредоточиться на поиске ошибок.
Сведения о командах и действиях, которые можно использовать при работе с картами кода, см. в статье Просмотр и переупорядочение карт кода.
Карты кода можно создавать только в выпуске Visual Studio Enterprise.
Вот краткий обзор карты кода.
Сопоставление стека вызова
В проекте Visual Studio Enterprise C#, Visual Basic, C++ или JavaScript запустите отладку, выбрав Отладка > Начать отладку или нажав клавишу F5.
Текущий стек вызовов выделен в новой карте кода оранжевым цветом:
При возобновлении отладки карта кода обновится автоматически. Изменение элементов или макета карты никак не влияет на код. Можно свободно переименовать, изменить или удалить любой элемент в сопоставлении.
Чтобы получить дополнительные сведения об элементе, наведите на него указатель мыши и прочитайте подсказку. Можно также выбрать элемент Условные обозначения на панели инструментов, чтобы узнать, что означает каждый значок.
Сообщение Диаграмма может быть составлена с использованием более старой версии кода в верхней части карты кода означает, что код мог измениться с момента последнего обновления карты. Например, вызов в сопоставлении может уже не существовать в коде. Закройте сообщение, а затем попытайтесь повторить сборку решения, прежде чем повторно обновлять сопоставление.
Отображение внешнего кода
По умолчанию в сопоставлении отображается только ваш код. Чтобы просмотреть внешний код на карте, выполните следующие действия.
Щелкните правой кнопкой мыши в окне Стек вызовов и выберите в контекстном меню пункт Показать внешний код.
Или снимите флажок Включить только мой код, выбрав в Visual Studio Сервис (или Отладка) > Параметры > Отладка.
Управление макетом карты
Изменение макета карты никак не влияет на код.
Для управления макетом карты используется меню Макет на панели инструментов карты.
С помощью меню Макет можно выполнять следующие задачи.
Добавление примечаний к коду
Вы можете добавить комментарии для отслеживания операций, выполняемых в коде.
Чтобы добавить комментарий, щелкните правой кнопкой мыши карту кода и выберите Изменить > Новый комментарий, а затем введите комментарий.
Чтобы добавить новую строку в комментарий, нажмите клавиши SHIFT+ВВОД.
Обновление сопоставления путем добавления следующего стека вызовов
При выполнении приложения до следующей точки останова или входе в функцию новые стеки вывозов добавляются на карту автоматически.
Добавление связанного кода в сопоставление
Теперь, когда у вас есть карта, при работе с C# или Visual Basic можно добавлять на нее элементы, такие как поля, свойства и методы, для отслеживания операций в коде.
Для перехода к определению метода в коде дважды щелкните метод на карте или выберите его и нажмите клавишу F12 либо щелкните его правой кнопкой мыши и выберите пункт Перейти к определению.
Чтобы добавить отслеживаемые элементы на карту, щелкните метод правой кнопкой мыши и выберите нужные элементы. Последние добавленные элементы отображаются зеленым цветом.
По умолчанию при добавлении элементов в сопоставление также добавляются узлы родительской группы, соответствующие, например, классу, пространству имен или сборке. Эту функцию можно отключать и включать с помощью кнопки Включить родительские элементы на панели инструментов карты кода или нажав клавишу CTRL во время добавления элементов.
Продолжайте формировать сопоставление, чтобы увидеть дополнительный код.
Поиск ошибок с помощью сопоставления
Визуализация кода поможет вам быстрее находить ошибки. Например: предположим, что вы ищете ошибку в программе для рисования. Когда вы создаете линию и пробуете отменить ее создание, ничего не происходит до тех пор, пока не будет нарисована следующая линия.
Использование карты совместно с другими пользователями
Вы можете экспортировать карту, отправлять ее другим пользователям с помощью Microsoft Outlook, сохранять ее в решении и проверять в системе управления версиями.
Чтобы предоставить общий доступ к карте или сохранить карту, нажмите кнопку Поделиться на панели инструментов карты кода.