NDepend

Improve your .NET code quality with NDepend

14 Visual Studio Web Development Productivity Tips

Visual Studio proposes quite a few handy tools to boost your productivity as a web developer. Here are some tips focused around web code edition and web application starting and debugging.

Short GIF is an excellent way to quickly learn Visual Studio productivity tips. See others related posts based also on short GIFs here:

1) Wrap selection with div

Once you did a selection you can wrap it with a <div>selection</div> element with the hotkey Shift+Alt.W, also available as a right click menu.

Visual Studio: Wrap with div (Shift+Alt+W)
Visual Studio: Wrap with div (Shift+Alt+W)

2) The Un-minify menu

If you right-click a minified content (js, css, json, html…) you can see a menu Un-minify:

Visual Studio: Un-Minify Menu
Visual Studio: Un-Minify Menu

3) Typing colon ‘:’ insert quotation marks around JSON property name

When typing the colon character ‘:’ the quotation marks are automatically added around the preceding JSON property name:

Visual Studio Json Edit: typing colon ':' insert the quotes
Visual Studio Json Edit: typing colon ‘:’ insert the quotes

4) Create a C# class from a copied JSON fragment

Once you’ve copied a JSON fragment to the clipboard, you can use the menu Edit > Paste Special > Paste JSON as Class to paste the fragment as a strongly typed C# or VB.NET class.

Paste Json as Class
Paste Json as Class

5) Drag and Drop an Image from the Solution Explorer to HTML Content

You can drag and drop an image from the Visual Studio Solution Explorer to HTML content. The <img> tag is then created with the proper relative path.

Visual Studio: Drag and Drop and Image to HTML
Visual Studio: Drag and Drop and Image to HTML

6) Encode image in base64

When the editor carret is over an <img> element, a light bulb appears on the left. Type Ctrl+. to open the bulb menu and select the menu Encode image in base64:

Visual Studio: Encode image in base64
Visual Studio: Encode image in base64

7) Insert image width and height attributes

The <img> light bulb menu also proposes the menu Insert width and height attributes. These image size attributes are used by the browser renderer to allocate the necessary area until the image gets loaded. This trick is important because it improves the page loading user experience. Indeed, with this tricks the page elements get their definitive location as soon as they appear.

Visual Studio: Insert Image Width and Height Attributes
Visual Studio: Insert Image Width and Height Attributes

8) Use Code Snippets

Code snippets are especially useful when editing HTML-like code thanks to the surround with possibility.

Just select the code element to surround then use the hotkey Ctrl+K, Ctrl+X to choose your snippet.

Visual Studio: Surround with a HTML code snippet
Visual Studio: Surround with a HTML code snippet

9) Create and Use your Own Code Snippets

You can access the Code Snippets Manager dialog from the menu Visual Studio > Tools > Code Snippets Manager… or with the hotkey Ctrl+K, Ctrl+B.

Visual Studio: Code Snippets Manager
Visual Studio: Code Snippets Manager

The easiest way to create your own snippet is to modify an existing one. Suppose that you want a snippet that add target=”_blank” on <a> link: <a href=”$” target=”_blank”>$selected$</a>.

To do so let’s modify the <a href=”$”>$selected$</a> default snippet just shown in the previous section. You can obtain the path to the a.snippet file from the Code Snippets Manager dialog.

Visual Studio: Get the path of a snippet file
Visual Studio: Get the path of a snippet file

The content of this file is:

Our new snippet shortcut will be atb (a target equals blank). Just modify the content of a.snippet this way and save it to a file named atb.snippet.

Then import the atb.snippet file:

Visual Studio: Import a custom snippet
Visual Studio: Import a custom snippet

Et voilà!

Visual Studio: Using a snippet imported!
Visual Studio: Using a snippet imported!

10) Start Chrome in Incognito Mode to Execute and Debug your Web Application

Starting Chrome in Incognito mode to execute Ctrl+F5 and debug F5 your web applications is quite useful. This way when testing your web application you avoid inheriting cookies from past sessions.

To start Chrome in Incognito mode you’ll need to add a new web browser entry. Click the menu Start > Browse with….

Visual Studio: Browse your WebApplication with
Visual Studio: Browse your WebApplication with

Then get the absolute path to chrome.exe by selecting the Chrome row: (it is C:\Program Files (x86)\Google\Chrome\Application\chrome.exe on my system)

Get the absolute path to chrome.exe
Get the absolute path to chrome.exe

Add Chrome Incognito in the list of browser. For that put the chrome.exe absolute path with the –incognito argument:

Visual Studio: Add Chrome Incognito in the List of Browsers
Visual Studio: Add Chrome Incognito in the List of Browsers

Finally set Chrome Incognito as the default browser et voilà!

Set Chrome Incognito as Default Browser to Start
Set Chrome Incognito as Default Browser to Start

11) Start Several Browsers to Execute and Debug your Web Application

In the Browse With dialog you can select more than one browser to start. This is pretty useful to test your application on several browsers:

Start your Web Application with Several Browsers
Start your Web Application with Several Browsers

12) Don’t Stop the Debugger when the Browser Window Is Closed

The default behavior of stopping the debugger when your test browser window is closed can be quite annoying. Yo might just want to re-use your existing debug session by opening a new browser window. To do so just uncheck Tools > Options > Projects and Solutions > Web Projects > Stop debugger when browser window is closed:

Visual Studio: Don't stop the debugger when the browser window is closed
Visual Studio: Don’t stop the debugger when the browser window is closed

13) Don’t Start a New Browser Window When Starting Debug

Often we don’t need a new a new browser window when starting a new browser debugging session. If you run an ASP .NET Core Application you can disable this behavior by unchecking Project properties > Debug > Launch browser:

ASP.NET Core Don't open a new browser window when starting
ASP.NET Core: Don’t open a new browser window when starting

If you run an ASP.NET application un check  Project Properties > Web> Don’t open a page. Wait for a request from an external application.

ASP.NET Application: Don't open a page
ASP.NET Application: Don’t open a page

Take care: disabling this behavior can be quite surprising for your colleagues so make sure to spread the word.

14) Install the Visual Studio Extension HTML Tools 2019 from Mads Kristensen

The extension HTML Tools 2019 from Mads Kristensen proposes quite a few handy tools that will improve your productivity as a web developer!

10 Visual Studio Files and Layout Productivity Tips

Nowadays most developers are working remotely. Hence the monitor(s) configuration might have changed, and might change frequently. In this context, it does matter to optimize the Visual Studio layout and documents access. Here are some tips.

Short GIF is an excellent way to quickly learn Visual Studio productivity tips. See others related posts based also on short GIFs here:

1) Save and Apply Windows Layout

The menu Window proposes 4 sub-menus to Save, Apply, Manage and Reset the Visual Studio windows layout. You can use this feature both to switch back and forth between several monitors configurations and also to switch between various activities (code writing vs. testing vs. code review …). The hotkey Ctrl+Alt+Number N instantly switches to the Nth layout.

Visual Studio Apply Window Layout
Visual Studio Apply Window Layout

2) Vertical Documents Tabs

You can place the documents tabs on the left or on the right. This is especially useful if you work with an ultra-wide monitor and have much more width space than height space.

Visual Studio Files Tabs Layout
Visual Studio Files Tabs Layout

3) Sorting Files Tabs

When tabs are on the left or on the right, files are sorted per project. Per default, under each project tabs are sorted alphabetically. They can also be sorted by Sorted by Recently Opened First or Sorted by Recently Opened Last.

Visual Studio Tabs Sorting: Alphabetic order vs. Recently Opened First/Last
Visual Studio Tabs Sorting: Alphabetic order vs. Recently Opened First/Last

4) Code Editor Horizontal Split

You can split horizontally the edition of a file through Window > Split. This is especially useful when visualizing or editing two locations in a large file.

Visual Studio: Horizontal Split of Code Editor
Visual Studio: Horizontal Split of Code Editor

5) Code Editor Vertical Split

Vertical split is not as straightforward as horizontal split explained in the previous tip. Vertical split requires a two step process:

  1. First Window > New Window menu
  2. Second right-click the tab, New Vertical Document Group

I wish there was a button to switch back and forth from horizontal to vertical split.

Visual Studio: Vertical Split of Code Editor
Visual Studio: Vertical Split of Code Editor

6) Document Group

The previous tip was based on document group. Document group is primarily used to create horizontal or vertical groups of files edited.

Visual Studio Document Group
Visual Studio Document Group

Document groups is especially useful with ultra-wide monitor:

Visual Studio Vertical Document Group on Ultra-Wide Monitor
Visual Studio Vertical Document Group on Ultra-Wide Monitor

7) Document Group and Vertical Documents Tabs

Document group works well when tabs are shown on left or right. Projects and files are then grouped by Tab Group sections:

Visual studio Document Group with Left and Right Tabs
Visual studio Document Group with Left and Right Tabs

8) Open a File Recently Closed

The Go to All dialog can be triggered with Ctrl+t. Then just type r and the list shows recent files, including the files that have been recently closed.

Visual Studio: Open File Recently Closed
Visual Studio: Open File Recently Closed

9) Dock and Un-Dock a Window

To dock and un-dock a window just hold the key Ctrl and double click the window title bar. This is much faster than dragging the window with the mouse.

Visual Studio :Dock and Undock a Window
Visual Studio :Dock and Undock a Window

10) Compare Files with Visual Studio

Visual Studio proposes an excellent file diff tool. However this tool is not easily accessible so most of users ignore it. You can diff through command line with the devenv.exe /diff command

If a Visual Studio instance exists it’ll be used to host the diff view, else a new Visual Studio instance gets started to host the diff view.

Visual Studio: Code Diff
Visual Studio: Code Diff

The diff view can also be opened from within Visual Studio Command Window with this command:

Visual Studio: Command Window Code Diff
Visual Studio: Command Window Code Diff

The Visual Studio diff feature is used by NDepend when comparing against a baseline inside Visual Studio. NDepend creates a snapshot of your code base by zipping all source files at analysis time. The tool then proposes the menu Diff since Baseline when right clicking an item in the Solution Explorer or a code element in the Code Editor.

Source Diff with NDepend in Visual Studio
Source Diff with NDepend in Visual Studio

Conclusion

I hope that after spending a few minutes reading this post you’ll improve your productivity as a Visual Studio user 🙂

10 Visual Studio Navigation Productivity Tips

A large code base is a complex asset. Visual Studio is a complex environment. In this context developers spend a significant part of their time searching and navigating across code elements and the multiple IDE tools and options.

Fortunately Visual Studio proposes many features to simplify navigation that I am going to present.  Note that this post won’t go through the Find in Files Ctrl+Shift+F feature that I guess all developers already use.

Visual Studio: Find in Files
Visual Studio: Find in Files

Short GIF is an excellent way to quickly learn Visual Studio productivity tips. See others related posts based also on short GIFs here:

1) Title Bar Search Box

The Visual Studio title bar proposes a search box. This feature is quite convenient because it let’s search through various kinds of assets: code elements, files, Visual Studio commands, Visual Studio settings… For example in the GIF below:

  • We first search for the interface IAffiliateService
  • Then we type IAS to search again for the interface IAffiliateService: this is Camel Case searching and this is quite convenient to locate large identifier
  • Then we search for Go to: many Visual Studio commands are then matched
  • Finally we search for line number: several Visual Studio settings related to line numbering are then matched.

At first glance being able to search various kinds of assets is a bit weird but once you’ll get used to it this is quite helpful. Personally I use this box to mostly search through commands and settings and use Go to all to search in code.

Visual Studio: Search Box in Title Bar
Visual Studio: Search Box in Title Bar

2) Go to All

When it comes to searching for code elements Go to All (hotkey Ctrl+t) is my preferred Visual Studio feature. Unlike the title bar search box it cannot be used to search for Visual Studio commands or settings.

Go to All offers several filters to define the kind of element to search. These filters can be listed with Ctr+t and then ?:

Visual Studio: Go to All Filters

In the GIF below:

  • We first search for all code elements that start with IAffiliateService: both source files and interfaces are matched
  • Then we prefix the same research with the filter “t ” to narrow the search on types only.
  • Then again we use the Camel Case searching on type with “t IAS”
  • Finally we list filters by typing “?”
Visual Studio Go to All Ctrl+t
Visual Studio Go to All Ctrl+t

There are also two scopes tickbox to:

  • Search only in Current Document (Ctrl+Alt+C)
  • Include contents of external items (Alt+X)

There are also 3 settings:

Visual Studio: Go to All Settings
Visual Studio: Go to All Settings

3) Peek Definition and Go To Definition

When the code editor carret is over an identifier you can use the hotkeys:

  • Alt+F12 to peek the identifier definition
  • F12 to open the source file that contains the definition

I believe those two hotkeys must be in the toolbelt of all Visual Studio developers.

Visual Studio: Peek Definition (Alt+F12) Go To Definition (F12)
Visual Studio: Peek Definition (Alt+F12) Go To Definition (F12)

Now let’s present other navigation hotkeys available when the carret is over an identifier in the source code: they are all available through the right-click menu.

Visual Studio: Navigation Hotkeys
Visual Studio: Navigation Hotkeys

4) Find All References

When the code editor carret is over an identifier you can use the hotkey Shift+F12 to find all references:

Visual Studio: Find all References
Visual Studio: Find all References

Typically the Find all references results window is a vertical windows so I like to get rid of all columns except the code one to obtain a result easier to browse.

Visual Studio: Clear columns of Find all references
Visual Studio: Clear columns of Find all references

A Group-By combo box let’s choose among various options:

Visual Studio: Find all references Group-By combo box
Visual Studio: Find all references Group-By combo box

I hope that in the future (post Visual Studio 2019) this result list will be improved this ways:

  • I’d like to group by Project, Namespace, Type, Member but this grouping option is not available.
  • On the screenshot above we see an unnecessary [Containing Member: Unknow] row that consumes space without adding any value.
  • The parent rows are in bold, I am not sure why, this makes the source code row less readable.
  • The same way the reference counting (3) (1) shouldn’t be in bold.
  • The parent rows should be prefixed with the corresponding icon (project icon, class icon, method icon…).

5) CodeLens

Visual Studio Code Lens is an intuitive an immediate way to see all references of an identifier. It is only available at the identifier declaration, not at the identifier usage locations.

Visual Studio: Find References with Code Lens
Visual Studio: Find References with Code Lens

I remember when Code Lens was introduced a few years ago I didn’t like the extra vertical space between lines and that some extra info were added in the middle of source code. So I used to disable it. However with time I got used to it and learnt to like it because it also displays more information than just references (code changes, branch… see the details here).

6) Go to Base and Go to Implementation

When the code editor carret is over an identifier representing a class name or an interface name:

  • The shortcut Alt+Home (Go to Base) can be used to go to the base class(es) or implemented interfaces.
  • The shortcut Ctrl+F12 (Go to Implementation) can be used to go to derived classes or classes that implement the interface.
Visual Studio: Go to Base, Go to Implementation
Visual Studio: Go to Base, Go to Implementation

7) Call Hierarchy

When the code editor carret is over an identifier representing a member, the shortcut Ctrl+K Ctrl+T opens the Call Hierarchy Window. With this window you can browse callers and also callers of callers (recursive).

Visual Studio: Call Hierarchy
Visual Studio: Call Hierarchy

When it comes to call hierarchy I prefer to have a dependency graph view. The NDepend dependency graph is well suited for that. The GIF below illustrates this list of action:

  • Right click the definition of a method, a field, a type or a namespace.
  • Then click Show on Dependency Graph
  • Then click callers in the graph navigation bar
  • Then, if needed, adjust Group-By and Layout Horizontal / Vertical.
NDepend Call Graph
NDepend Call Graph

8) Navigate TODO comments in Task List

The Visual Studio Task List Window can display all comment lines starting with the predefined token TODO (case sensitive).

Visual Studio: TODO Task List
Visual Studio: TODO Task List

You can define your own set of tokens in Options > Environment > Task List:

Visual Studio Task List Settings
Visual Studio Task List Settings

9) Shortcut on a line of code

A shortcut can be placed to any line of code with the hotkey Ctrl+K-H. The same hotkey can be used to remove the shortcut.

These shortcuts are listed in the Task List Window. Notice that shortcuts are persisted and if you close and restart Visual Studio they will still be there.

Visual Studio: Shortcut on line of code
Visual Studio: Shortcut on line of code

Notice that this feature is different that the Bookmark feature already presented in 10 Visual Studio Ninja Code Editor Productivity Tips (item 10).

10) Go to Matching Brace

When the carret is over an opening brace or a closing brace { }, the hotkey Ctrl+} goes to the matching brace. This also work for these pairs: ( )  [ ] <>

Visual Studio: Go to Matching Brace
Visual Studio: Go to Matching Brace

Conclusion

I hope that you’ve learnt some tricks to improve your productivity.

It is important to train a bit and get used to all these features and which one to favor for which scenario.

  • Title Bar Search box is well suited to search across Visual Studio menus and options
  • Ctrl+t Go to All is well suited to search files and code element identifiers.
  • Then it is important to get used to all navigation features around the F12 key: F12 Go to Definition, Alt+F12 Peek Definition, Shift+F12 Find all References, Alt+Home Go to Base, Ctrl+F12 Go to Implementation

I mentioned the NDepend dependency graph in the Call Hierarchy tips. This tool can help a lot when it comes to navigating and understanding a large code base. Here is a short introduction video:

 

Top 10 Visual Studio Refactoring Tips

With the version 2019 Visual Studio is now mature when it comes to refactoring. This post proposes a tour of the top 10 most used refactoring actions in my opinion.

Short GIF is an excellent way to help get started with those Visual Studio tips. See others related posts based also on short GIFs here:

1) Renaming an Identifier

With Ctrl+R,R you can rename any code identifier: a variable, a field, a class… The renaming experience is pretty clean when only one source file is concerned since all references in file get updated live while typing the new name:

Renaming a variable in Visual Studio
Renaming a variable in Visual Studio

When renaming an identifier impacts several source files, like when renaming a class, several UI details improve the user experience:

  • In the top-right panel we see: Renaming X references in Y files
  • In the top-right panel we get the checkbox: Rename file, this is quite useful since often the file name and the class name are in-sync.
  • We get the possibility to preview all changes in all files in a Preview Change window.
Renaming a class in Visual Studio
Renaming a class in Visual Studio

2) Extract Method

The hotkey Ctrl+. triggers the Quick Actions and Refactorings menu. If you are not used yet to Ctrl+. I’d advise training especially this one because it is a powerful shortcut. You’ll see that most other refactoring presented here rely on the Ctrl+. hotkey.

If one or several instructions are actually selected in a method, the Extract method and Extract local function menus are proposed. A large tooltip is immediately shown to preview the changes. Then just click Enter and terminate the refactoring action by naming the NewMethod identifier.

Extract Method with Visual Studio
Extract Method with Visual Studio

3) Remove and Sort Usings

To make your code cleaner it is recommended to maintain for each source file the list of using ordered alphabetically with unnecessary usings removed. Both actions can be done automatically with Visual Studio top menu > Edit > Intellisense > Remove and Sort Usings. I wish a default shortcut was assigned to this common refactoring (of course you can still assign a shortcut to this action from Visual Studio top menu > Tools > Options > Keyboards.).

Remove and Sort Usings with Visual Studio
Remove and Sort Usings with Visual Studio

Actually it is possible to remove all unnecessary usings at once in a Visual Studio project or solution thanks to the bulb that appears in the code editor gutter when selecting an unnecessary using faded away.

Remove unnecessary usings with Visual Studio
Remove unnecessary usings with Visual Studio

4) Add Missing Usings when Pasting

When pasting some code it is quite irritating to get some errors because of some missing usings. Once the code has been pasted, you can click Ctrl+. to ask Visual Studio to add missing usings for you:

Add missing usings after pasting with Visual Studio
Add missing usings after pasting with Visual Studio

5) Generate Property from Constructor and Generate Constructor from Properties

Once again the magical Ctrl+. hotkey can be used when selecting a parameter into a constructor signature, to generate the corresponding property.

However I haven’t found a way to generate several properties in a row. I’d expect that selecting several parameters and then Ctrl+. would propose to generate several properties in a row but it is not the case, and there is no Create properties for all parameters menu.

Generate property from constructor with Visual Studio
Generate property from constructor with Visual Studio

The same way you can generate a constructor from the selected properties.

Generate constructor from selected properties with Visual Studio
Generate constructor from selected properties with Visual Studio

Both quick actions work with fields also.

6) foreach to LINQ

When the editor carret is over a foreach loop, the hotkey Ctrl+. proposes to convert the foreach loop to a LINQ query. This conversion is not always possible but it is smart enough. For example it can convert a if(condition){continue} within the loop into a where condition LINQ clause.

Notice that typically loops are faster than LINQ queries because the compiler can optimize loops while LINQ queries extensively rely on method calls. But in non-performance-critical code region LINQ queries is often a more readable, concise and maintainable way of writing code.

Converting a foreach loop into a LINQ query with Visual Studio
Converting a foreach loop into a LINQ query with Visual Studio

7) Extract Interface

When the editor carret is over a class name the hotkey Ctrl+. proposes a quick-actions list that includes: extract an interface from the class members. Ctrl+R,I can be used instead to directly show the Extract Interface dialog. The Extract Interface dialog proposes to define the interface name (per defaut set to “I{class name}”) and the member list to include in the interface.

Extracting an interface from a class with Visual Studio
Extracting an interface from a class with Visual Studio

8) Move Type to Namespace

When the editor carret is over a type name, the hotkey Ctrl+. proposes the quick-actions list that includes: move to namespace. The Move to namespace dialog is smart enough to propose intellisense and auto-completion based on existing namespaces. However the type’s source file is not moved automatically to the folder corresponding to the namespace chosen, this must be done manually in the Solution Explorer. I hope this move will be done automatically in the future.

Move class to namespace with Visual Studio
Move class to namespace with Visual Studio

9) Add Parameter to a Method

You can add a named parameter to a method call location. Then the hotkey Ctrl+. proposes the refactoring Add parameters to the method called. The method signature is then refactored with the extra parameter but other calls of the method are left untouched. It means that now these other calls provoke a syntax error and must be fixed with the extra parameter.

Add parameter to a method with Visual Studio
Add parameter to a method with Visual Studio

10) Convert to interpolated string and simplify interpolation

When the carret is over a call to string.Format() call the hotkey Ctrl+. proposes the refactoring Convert to interpolated string. String interpolation with the syntax $”{parameter}” has been introduced with C#6 in 2015. Then if possible some elements like call to PadLeft() are grayed in code. This is a sign that the string interpolation can be simplified once again with the hotkey  Ctrl+. over those grayed elements.

Convert to interpolated string with Visual Studio
Convert to interpolated string with Visual Studio

Conclusion

Over the years thanks to massive effort put in Roslyn, Visual Studio got better and better when it comes to refactoring actions proposed out-of-the-box. Many more refactoring than those 10 are proposed: read the list of refactoring and list of quick-actions.

When we talk about Visual Studio and refactoring the case of Resharper immediately comes in the discussion. For more than a decade Resharper has been the tool of choice to improve the productivity with many refactoring actions and more great features. My independent opinion in the VS vs. R# debate (in 2020) is that R# is still a bit more powerful despite VS being now quite mature. However it seems to me that the fact that VS is now quite mature with refactoring is not popular enough, hence I hope this post can help spread the word. And if you ask, yes I still code with R# in VS despite R# slowing down a bit the IDE, but I find myself using it less often. Within the next years we can expect both VS improvements in terms of refactoring and R# improvements especially in terms of performance.


Actually the word refactoring has really two meanings:

  • Short and quick productivity refactoring actions as presented here.
  • Large scale refactoring that are necessary when the architecture of a legacy doesn’t fit anymore the planned evolution and maintainability requirements.

Large scale refactoring must be discussed extensively. The number one prerequisite for a successful large scale refactoring is a solid understanding of the legacy code architecture. This is where the tool NDepend with its new dependency graph and dependency matrix can really help. Here are two short videos that explain how:

12 Visual Studio Debugging Productivity Tips

In this post we assume the the reader knows the basics of debugging with Visual Studio:

  • F5 to start running with the debugger
  • F9 set breakpoint on the current line
  • F10 run till next breakpoint
  • F5 to resume the execution from a stopped program debugged
  • F11 step into the function (if the instruction pointer points to a function)
  • F10 step over the function (if the instruction pointer points to a function)
  • Shift+F11 step out the executed function
  • Pause execution
  • Attach to Process
  • Quick watch an element in source code with mouse hover
  • Debug Windows : Locals, Watch, Immediate, Modules, Stack Trace, Exception

Many developers handle their debugging sessions with this powerful-enough knowledge kit. However the Visual Studio Debugging tools have much more to offer. Here is a list of Visual Studio Debugging productivity tips. Note that those tips and shortcuts have been validated with Visual studio 2019 16.6 EN-US edition with no extension installed.

1) Run to Cursor

With the shortcut Ctrl+F10 you can tell the debugger to run until the line pointed by the cursor.

Run to Cursor Ctrl+F10
Run to Cursor Ctrl+F10

2) Run through here with a mouse click

When hovering the source code while debugging a Run execution through here green glyph appears. This glyph can be clicked.

Run Execution Through Here Glyph
Run Execution Through Here with a Mouse Click

3) Set next statement to here

The Run execution through here green glyph can be transformed into Set next statement to here by holding the key Ctrl. It is different than Run execution through here because the statement in between are not executed. Hence in the small animation below we can see in the Watch window that the reference obj remains null: the MyClass constructor in between hasn’t been executed.

Set next statement to here
Set next statement to here

4) Data breakpoint: Break when value changes

If you set a breakpoint to a non-static property setter it will be hit when changing the property value for all objects. The same behavior can be obtained for a single object thanks to the Locals (or Watch) window right click : Break When Value Changes menu.

This facility is illustrated with the animation above. The hit occurs only when obj2.Prop is changed, not when obj1.Prop is changed.

Note that a data breakpoint is bound to a live object during a debugging session. Hence it gets lost once the debugged process stops, it cannot be reused during future debugging session.

Note that the menu Break When Value Changes is also available when right clicking a field in the Locals window but unfortunately the debugger doesn’t break on field change, I am not sure if it’s a bug or a feature not yet implemented?

Data breakpoint: break when value changes
Data breakpoint: break when value changes

5) Conditional breakpoint

A condition can be attached to a breakpoint to break only in a certain scenario. In the animation below we define the breakpoint with condition i > 6 within the loop. Then we click Continue and can see that once the breakpoint is stopped, the i value is actually 7.

Conditional Breakpoint
Conditional Breakpoint

6) Trace breakpoint

Halting the program execution is the most common action upon a breakpoint hit. However you can choose instead to print some traces in the Output window without (or with) halting. This possibility is illustrated by the animation below where we trace the value of i from 0 to 9 in the Output window. Notice that a trace breakpoint has the diamond shape in the code editor gutter.

Note that both a condition and a trace action can be specified on a breakpoint.

Trace Breakpoint
Trace Breakpoint

7) Track Objects that Are Out-Of-Scope

In the Watch window objects are tracked by the name of their references in the currently executed scope. However when such tracked reference goes out-of-scope, it becomes meaningless in the context of the Watch window and it gets disabled, even though the referenced object is still live.

There are many situations where we’d like to continue tracking the state of an out-of-scope object. To do so, right click such reference in the Watch window, click the menu Make Object ID and add $1 in the items to watch (or $2 or $3… depending on how many object IDs you’ve already created).

The animation belows shows how to track the state of an out-of-scope object’s property getter that returns the actual date-time as a string. It shows well that when the reference obj goes out-of-scope in the context of Fct(), obj item to watch gets disabled and $1.Prop still gets updated.

Tracking an object whose reference goes out-of-scope
Tracking an object whose reference goes out-of-scope

8) View values returned by functions

The value returned by a function is sometime ignored by the source code. Or sometime this value is just not obviously accessible at debug-time.

Such returned value can be shown in the Debug > Windows > Autos windows. The pseudovariables $ReturnValue can also be used in the Immediate and Watch Windows to view the last function call returned value.

Note that the menu Debug > Windows > Autos is available only when the Visual Studio debugger is attached to a process and the program is halted by the debugger.

View the value returned by a function
View the value returned by a function

9) Reattach To Process

Since Visual Studio 2017 the Reattach to process Shift+Alt+P facility is proposed and it’s very handy. Once you’ve been attaching the debugger to a process Visual Studio remembers it and proposes to re-attach the debugger to the same process. Same is in italic because there is an heuristic here about the process identity:

  • If the process you’ve been attached to is still alive Reattach to process re-attach to it.
  • Else Visual Studio attempts to find a single process with the same previous process name and re-attach the debugger to it.
  • If several processes are found with this name, the Attach to Process dialog is opened with only those processes with same name shown
  • If no process with this name can be found the Attach to Process dialog is shown
Reattach To Process
Reattach To Process

Reattach To Process also works with debug session involving multiple processes. In this situation Visual Studio attempts to find all processes it has been attached to with the same heuristics explained above.

10) No-Side-Effect evaluation in Immediate Window and in the Watch Window

Sometime when evaluating an expression in the Immediate or in the Watch window some state gets changed. This behavior is often indesirable, you don’t want to corrupt the state of your debugged program just because you needed to evaluate the value of an expression. This situation is known as an Heisenbug , the term is a pun on the name of Werner Heisenberg, the physicist who first asserted the observer effect of quantum mechanics, which states that the act of observing a system inevitably alters its state.

To avoid changing any state you can suffix your expression with , nse (No-Side-Effect). This possibility is illustrated by the animation below (watch the _State value changing or not in the Watch window):

No Side Effect expression evaluation
No Side Effect expression evaluation

Here is ,nse used in the Watch window. This sample is less trivial than the previous one because of the Refresh evaluation button in the SideEffectFct() watched item.

No Side Effect expression evaluation in the Watch Window
No Side Effect expression evaluation in the Watch Window

11) Show Threads in Source

Debugging a multithreaded application is notoriously complex. Hopefully the Show Threads in Source button can help a lot.  It introduces marker icons in the editor gutter to keep track of the locations on which other threads are halted. This marker can be used to show the thread ids and eventually switch to another thread. Notice that a different marker glyph is shown if at least two threads are halted on the same location.

Show Threads In Source
Show Threads In Source

More tips to debug multithreaded applications are available in this Microsoft documentation: Get started debugging multithreaded applications (C#, Visual Basic, C++)

Here is the source code of this small demo if you’d like to play with it:

12) Debug source code decompiled from IL code

Often we depend on some black-box components: assemblies for which we don’t have the source code.

However when debugging a complex behavior it is convenient to observe and even debug the logic nested in black-boxes referenced. This is why since version 16.5 Visual Studio 2019 can generate some source code from compiled assemblies. Such source code is then debuggable. This feature is based on the OSS project ILSpy.

The decompilation menu can be proposed in the assembly right-click menu in the Modules window (as shown in the animation below) and in the Source Not Found or No Symbols Loaded dialogs.

Decompiling IL code to source code cannot be perfect because some source information is lost at compilation time. Hence this feature has a few limitations explained at the end of this official documentation: Generate source code from .NET assemblies while debugging.

Decompile IL code to source code that can be debugged
Decompile IL code to source code that can be debugged

Conclusion

Visual Studio shines but it especially shines when it comes to debugging. Here I tried to select some tips that are both quite hidden but often useful, I hope they will help improve your productivity.

 

 

10 Visual Studio Ninja Code Editor Productivity Tips

Among the multiple daily development tasks (planning, testing, refactoring, bug fix…) code edition is arguably the most satisfying one. Code edition can be even more satisfying and productive by mastering the following Visual Studio productivity tips. In my opinion these tricks are not optionals: they should be part of all Visual Studio developer skills.

1) Move one or several lines up and down

The line that contains the editing caret can be moved up and down with Alt+Up and Alt+Down.

The same way several lines selected can be moved up and down.

Move lines up and down with Alt+Up and Alt+Down
Move lines up and down with Alt+Up and Alt+Down

2) Rectangular Selection

Rectangular selection is very useful to quickly edit a code portion. This can be achieved with Alt+Shift+Arrows shortcuts.

Rectangular Selection with Alt+Shift+Up/Down/Left/Right.
Rectangular Selection with Alt+Shift+Arrows.

3) Multi-Lines Edition

Once mastering rectangular selection, it can be used to edit multiple lines at once:

Multiple Lines Edition
Multiple Lines Edition

4) Multi-Carets Edition

Often we need to repeat the same edition at multiple locations. To do so multiple carets can be defined with Ctrl+Alt+Mouse Click:

Multiple Carets with Ctrl+Alt+Mouse Click:
Multiple Carets with Ctrl+Alt+Mouse Click:

5) Multi-Carets Edition on Same Matches

Multiple carets can be set to next locations of the selected word. To do so first select the word and then use Ctrl+Shift+; .

Multiple carets can be set to all locations of the selected word with Ctrl+Shift+$ .

Same Match Selection
Same Match Selection

6) Expand / Contract Selection

You can expand the selection with Shift+Alt+= and contract it with Shift+Alt+.

Expand Selection
Expand Selection

7) Make Selection Uppercase / lowercase

You can Uppercase the selection with Ctrl+Shift+U and lowercase it with Ctrl+U

Make Selection Uppercase / lowercase
Make Selection Uppercase / lowercase

8) Outlining

The most important keyboard shortcut when it comes to outlining is Ctrl+M Ctrl+M. This shortcut expands / collapses the code portion that contains the caret.

Not all developers enjoy outlining and if you are one of those, you can discard it with Ctrl+M Ctrl+P.

Expand / Collapse Outlining
Expand / Collapse Outlining

9) Vertical Scrollbar Map Mode

The map mode is one of the most useful Visual Studio code editor facility. It does really help finding your way in source file.

Vertical Scrollbar Map Mode 
Vertical Scrollbar Map Mode

It can be set from Visual Studio > Tools > Options > Text Editor > All Languages > Scroll Bars > Behavior.

The width of the map can be: Narrow Medium Wide

Set Vertical Scrollbar Map Mode 
Set Vertical Scrollbar Map Mode

10) Bookmarks

When developing we often have to come back and forth through multiple locations in several source files. Fortunately you can concretely define this locations-set with bookmarks. Here are bookmarks shortcuts:

  • Ctrl+K, Ctrl+K to toggle a bookmark at caret position
  • Ctrl+K Ctrl+N go to Next bookmark
  • Ctrl+K Ctrl+P go to Previous bookmark
  • Ctrl+K Ctrl+L clear all bookmarks

Note that Visual Studio remembers bookmarks when closing it and restarting it.

Toggle Bookmarks with Ctrl+K, Ctrl+K
Toggle Bookmarks with Ctrl+K, Ctrl+K

11) Bonus: Visual Studio 2019 Clipboard Ring Preview

Ctrl+C copy some data to the clipboard. Actually Visual Studio maintains a clipboard ring to store several data.

With Visual Studio 2019 Ctrl+Shift+V shows a preview of the various data in the clipboard ring. This is quite useful to navigate through the copy history.

Visual Studio 2019 Clipboard Ring Preview
Visual Studio 2019 Clipboard Ring Preview

Conclusion: Visual Studio > Edit > Advanced

The Visual Studio menu Edit > Advanced is both a good start and a good reminder for code editor keyboard shortcuts.

There are more sub-menu including Bookmarks, Outlining, Intellisense and Multiple Carets.

Visual Studio Edit Advanced
Visual Studio Edit Advanced

I like the ninja-coder analogy because these tips must be repeated again and again as kata to be mastered in your daily coding routine.

Kata is a Japanese word meaning literally “form” referring to a detailed choreographed pattern of martial arts movements made to be practised alone, and also within groups and in unison when training. It is practised in Japanese martial arts as a way to memorize and perfect the movements being executed

Why not take 8 minutes now with this background theme and practice?

Be curious: there are many more Visual Studio facilities that will help becoming a ninja coder, first one being code snippets.

10 Visual Studio Solution Explorer Productivity Tips

The Visual Studio Solution Explorer panel is like home for Visual Studio users. It presents all projects, source files and items thanks to a treeview layout.

This panel is quite sophisticated and it is likely that you don’t use all the power of this great tool. Here are some tips:

1) Automatically Track active Item in Solution Explorer

On a large Visual Studio solution with hundreds or thousands of source files, the Visual Studio Solution Explorer button Sync with Active Document is often clicked to find your way.

Visual Studio Solution Explorer Sync with Active Document

This sync can be done automatically. For that you just need to check: Visual Studio  >  top menus   >  Tools  >  Options…  >  Projects and Solutions  > General  >  Track Active Item in Solution Explorer.

Track Active Item in Solution Explorer
Track Active Item in Solution Explorer

2) Improve Visual Studio Startup Performance

Visual Studio startup is faster with these 3 settings:

  • Allow parallel project initialization checked
  • Reopen documents on solution load unchecked
  • Restore Solution Explorer project hierarchy state on solution load unchecked

This tip is especially useful to accelerate Visual Studio Startup when opening a large solution.

Improve Visual Studio Startup Performance
Improve Visual Studio Startup Performance

3) Search in Visual Studio Solution Explorer

The shortcut Ctrl+; set the focus in the Visual Studio Solution Explorer search textbox and you can start typing your search term(s). If the Solution Explorer panel is not visible this shortcut makes it visible. When displaying search results the treeview hierarchy is kept so you know the location of matched items.

The search setting Search within file contents is set by default but can be turned off to restreint the search on file name only.

Search in Visual Studio Solution Explorer
Search in Visual Studio Solution Explorer

The search setting Search within external items is set by default to match files in External Dependencies folders. Turning it off prevents searching within the C/C++ External Dependencies folder. This setting is not related to C#, VB.NET and F# projects.

Search within external items
Search within external items

4) Browse Types, Methods and Fields

In Visual Studio Solution Explorer a source file item can be expanded to browse type(s), methods and fields declared in the source file. Types, methods and fields items are shown in the same order of their declarations in the source file. These items can be double-clicked to open the source declaration and right-clicked to show the related menus.

Visual Studio Solution Explorer Types, Methods and Fields Items
Visual Studio Solution Explorer Types, Methods and Fields Items

5) Filter File Opened or Pending Changes

Two filters are proposed:

  • Open Files Filter: This filter is especially useful when a code review or a change spawn on many files.
  • Pending Changes Filter: Often a refactoring session spawn on several files and this filter lets keep track of file changed.

It is also possible to create your own filter as explained in this documentation: Extend the Solution Explorer filter

Open Files or Pending Changes Filters
Open Files or Pending Changes Filters

6) Quickly Set the Startup Project

Most developers I know setup the startup project this way: 1) find the project in the Solution Explorer 2) right click the project and find in the long list of menus the Set as Startup Project menu.

Here is a quicker way : select the Solution item, Alt+Enter shortcut to view the Solution Property Pages dialog, there you can quickly chose the startup project in a combo-box and even define multiple startup projects:

Quickly Set the Startup Project
Quickly Set the Startup Project

7) Preview Selected Items on Project

When the checkbox Preview Selected Items is checked, when selecting a source file it is automatically opened in the preview tab. This feature is widely used but what you might not know is that this feature also work to open project files XML content!

Preview Selected Item Works on Project Item
Preview Selected Item Works on Project Item

8) Scope to a Single Project

Often a development session only concerns a single project. You can restreint the Visual Studio Solution Explorer to only a single project with the project right-click menu Scope to This.

Scope to a Single Project
Scope to a Single Project

9) Multiple Solution Explorer Views

I wish that the Scope to This facility shown above would be available when right-clicking several projects to restreint the focus on a few projects, but it is not.

However it is possible to work with multiple solution explorer views, each one scoping to a project. To do so right-click a project and click the menu New Solution Explorer View. Notice that extra Solution Explorer View(s) are not persisted. When you close and re-open Visual Studio they are not here anymore.

New Solution View
New Solution View

10) Switch to Folder Views

Most of the time the Visual Studio Solution Explorer displays assets structured in a logical way. For example solution folders used to group projects don’t necessarily represent real OS file system folders. It is often useful to switch to a physical presentation of the solution folders and files. This can be achieved with the Switch Views combo box.

Solution Explorer Folder View
Solution Explorer Folder View

11) Bonus: Explore Solution Architecture

The new NDepend powerful dependency graph is like a second Solution Explorer that focuses on the solution architecture. Folders and files can be drag-and-dropped from the Visual Studio Solution Explorer to the graph.

Drag and Drop from the Visual Studio Solution Explorer to the NDepend Dependency Graph
Drag and Drop from the Visual Studio Solution Explorer to the NDepend Dependency Graph

There are many more facilities presented in the videos below:

  • It can handle live very large solutions made of dozens or hundreds of projects.
  • Right clicking a solution explorer item like a project or a source file shows a menu to generate a graph of the item’s child, callers and callees.
  • Box size in the graph is proportional to the number of lines of code to get an intuitive view.
  • Items in the graph can be searched, expanded and collapsed the same way as in the Visual Studio Solution Explorer.
  • The graph has a navigation bar to quickly generate call graph, coupling graph, class diagram, graph of dependency cycles, graph of changes since baseline and more.

 

Don’t rely on someone else to protect your software

This morning I stumbled on this post Decompilation of C# code made easy with Visual Studio on the Visual Studio blog. Basically VS will soon be able to not only decompile third-party code but also generate some sort of PDB information that will make the decompiled code debuggable. The promise is no more  “No Symbols Loaded” or “Source Not Found” from within debugging session in VS and personally I found this awesome.

However most of this post’s comments are like “how do I protect my code from being decompiled then?!” and “Microsoft does not care about its customers’ intellectual property.”. These comments are absurd. Since its inception in 2002 .NET compiled code can be decompiled and read crystal clear with popular tools like .NET Reflector, IL Spy, dotPeak… This is a direct consequence of having IL/byte code and a CLR with a JIT compiler. I wonder to which extend those that wrote these comments are aware of that?

Protect your Intellectual Property

The first step is to make sure that your EULA forbid from decompiling your code, something like:  Licensee may not reverse-engineer, decompile, disassemble, modify, or translate the Product, or make any attempt to discover the source code of the Product;

The second step is to obfuscate your compiled code. Since 2002 those that want to protect their compiled code from decompilation just have to obfuscate it. There are mature free tools like ConfuserEx and paid tools available. This is what we do within our .NET shop since 2007 with success.

Also with .net native and AOT (Ahead of Time compilation) one can add a whole new layer of complexity by skipping the IL code and compile directly to machine code (e.g. X64 instructions).

But keep in mind that Obfuscators and AOT only protect the intellectual property to some extent. Your code best kept secrets are still executable in both scenarios, it means they are still there. Someone skilled ready to spend a large amount of time to reverse engineer your code can still have access to your intellectual property.

The ultimate way to protect your intellectual property is to provide your services as online SaaS. This way nobody will ever have access to your code. For example the whole SEO industry is based on guessing what Google and others web search engine are doing. These algorithms are protected because nobody except Google employees have access to them. In many scenarios Saas means also that one forces his clients to share their sensitive data, since they are processed on one’s server, and in many scenario this is not applicable. By spying your data Google and Facebook knows you better than you do, but it seems that only a fraction of the humanity disagree with that. Ok I digressed…

Protect your software from hackers

Keep in mind that Obfuscators and AOT don’t protect your code from hackers. It is still easy for any solid hacker to crack your license-checking-layer and provide a free version of your software online as a warez. The only possible protection from hackers that have access to your code are integrity checks. An integrity check is made of two parts:

  1. A layer that detects if some bytes of your compiled code have been tweaked (typically with a custom or standard hash function)
  2. A subtle malfunction of your software that prevents to use it if the compiled code has been tweaked.

The whole point of an integrity check is to consume the time of the hacker. This is why the word subtle is in bold, the malfunction is not a random exception to provoke a fail-fast, the malfunction must be something that appears minutes after the integrity check failed and finally makes the software totally unusable (like a massive memory leak – clearing some data – freezing some UIs – firing a timer to close the user session after a random number of minutes…)

By multiplying the integrity checks and the subtle corresponding malfunctions one can only hope to discourage a talented hackers to waste days, weeks or months to crack his software. But be aware that these guys are primarily driven by challenges… The good news is that with .NET there are tons of possible ways to write subtle integrity checks.

Conclusion

Protecting the intellectual property and the software itself is a difficult task. Don’t complain to Microsoft or anyone else that they should offer an out-of-the-box tool for that. If such a mainstream protection tool existed it would be a challenge for the best talented hackers and it wouldn’t resist long anyway.

The question you should ask for is: is it worth spending resources to protect my assets instead of spending these resources to make my paid clients even more happy. This is a difficult trade-off that must be carefully thought out. But always keep in mind that you must not rely on someone else to protect your software.

4 Predictions for the Future of .NET

In May 2019, Microsoft officially announced .NET 5, the future of .NET: it will be based on all the .NET Core work already achieved. Here is the schedule announced:

On one hand the future of .NET has never been so bright. On the other hand this represents a massive move for all .NET development shops, especially for those that still target .NET Framework 4.x that won’t evolve anymore. But not everything is clear from this announcement. Such massive move will have many collateral consequences that we can only guess by now. Certainly many points are not yet cast in stone and still debated.

Hence for large .NET legacy code bases some predictions must be made to plan now a seamless and in-time migration toward the future of .NET. So let’s do some predictions: it’ll still be interesting to come back in a few years and see how good or bad they were.

.NET Standard won’t evolve much

.NET Standard was introduced as a common API set that all .NET flavors must implement. .NET Standard superseded PCL (Portable Class Library). Now that several .NET frameworks will be unified upon .NET Core bases, and that the .NET Framework 4.x won’t support future versions of .NET Standard anymore, it sounds like the need for more .NET standard API will decrease significantly. Actually .NET Framework 4.8 doesn’t even support latest .NET Standard 2.1: “.NET Framework 4.8 will remain on .NET Standard 2.0 rather than implement .NET Standard 2.1”.

However .NET Standard is certainly not dead yet: it is (and will be for years to come) an essential tool to compile code into portable components that can be reused across several .NET flavors. However with this unification process the future of .NET Standard is compromised.

Visual Studio will run on .NET 5 or 6 (and in a x64 process)

It has to. Imagine the consequences if in 3 years from now (2019 Q4) the main Microsoft IDE for .NET professional developments still run on .NET Framework v4.8:

  • Engineers working on VS would lack access to all new .NET APIs, performance improvements and langage improvements. They would remain locked in the past.
  • As a consequence they wouldn’t use their own tool (dogfooding) and dogfooding is a key aspect of developing tools for developers.
  • Overall the message sent wouldn’t be acceptable for the users.

On the other hand, if you know a bit how VS works, imagine how massive this migration is going to be. For more than a decade there have been a lot of complaints from the community about Visual Studio not running in a 64 bits process. See some discussions on reddit here for example. If I remember well this x64 request was the most voted one when VS feedback was still handled by UserVoices. Some technical explanations have been provided by Microsoft like those ones provided 10 years ago! If in 2019 Visual Studio still doesn’t run in a x64 process, this says a lot on how large and complex such migration is.

It seems inevitable that this time the Visual Studio legacy will evolve toward what will be the future of .NET. One key benefit will be to run in a x64 process and have plenty of memory to work with very large solutions. Another implication is that all Visual Studio extensions, like our extension, must evolve too. Here at NDepend we are already preparing it but it will take time, not because we’ll miss much API (we’ll mostly miss AppDomain) but because:

  • We depend on some third-parties that we’d like to get rid of to have full control over our migration, and overall code.
  • For several years we’ll have to support both future Visual Studio versions and Visual Studio 2019, 2017 and maybe 2015 that runs on .NET Framework v4.x (btw we still support VS 2013/2012/2010 but this will have to be discarded to benefit from .NET Standard reused DLLs)

We cannot know yet if Visual Studio vNext will run on .NET 5 or if it’ll take more years until we see it running upon .NET 6?

Btw here are 2 posts Quickly assess your .NET code compliance with .NET Standard and An in-depth analysis of .NET Core 3.0 support for WPF and Winforms APIs that can help plan your own legacy migration.

.NET will propose a cross-platform UI Framework: WPF or a similar XAML UI Framework

On October 4, 2019 Satya Nadella revealed why Windows may not be the future of Microsoft’s business. In August 2019 Microsoft provided a .NET Cross Platform UI Framework Survey. Clearly a .NET cross-platform UI Framework is wanted: the community is asking for it. So far Microsoft closed the debate about WPF: WPF won’t be multi-platform.

Let’s also be crystal clear. This (WPF cross platform) is a very hard project. If the cost was low, this would be a very different conversation and very likely a different outcome. We have enough trouble being compatible with OpenSSL and that’s just one library.  Rich Lander – Dec 5, 2018

But given the immense benefits of what WPF running cross-platform would offer, I wouldn’t be surprise to see WPF become cross-platforms within the next years. Or at least a similar XAML UI framework. Moreover WPF is now open-source so who knows…

The Visual Studio UI is mostly based on WPF hence one of the benefit of having WPF cross-platform would be to have a unique cross-platform Visual Studio: the same way Microsoft is now unifying .NET Frameworks, they could unify the Visual Studio suite into a single cross-platform product.

Xamarin Forms and Avalonia are also natural candidates to be the .NET cross-platform UI Framework. But it seems those frameworks doesn’t receive enough love from the community, this is my subjective feeling. Also we have to keep in mind that Microsoft did a survey and that the community is massively asking for it.

Blazor is promised to a bright future

If you didn’t follow the recent Blazor evolution, the promises of this technology are huge:

  • Run .NET code in all browsers (like Silverlight)
  • with no browser plugin needed (unlike Silverlight)
  • with near-native performance
  • with components compiled to a compact binary format

This is all possible thanks to the WebAssembly (Wasm) format supported by most browsers.

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

Blazor was initially a personal project created by Steve Sanderson from Microsoft. It was first introduced during NDC OSLO in July 2017: the video is worth being watched, also read how enthusiastics are the comments. However Blazor is not yet finalized and still has some limitations: it doesn’t offer yet a decent debugging experience and the application size to download (a few MBs) is still too large because dependencies have to be loaded too. Those ones are currently being addressed (see here for debugging and here for download size, runtime code will be trimmed and cached and usage of CDN (Content Distribution Network) is mentioned).

The community is enthusiast, the technology is getting mature and there is no technological nor political barrier in sight: the Blazor future looks bright. Don’t miss the Blazor FAQ to learn more.

Identify .NET Code Structure Patterns with no Effort

The two pillars of code maintainability are automatic testing and clean code structure.

  • Testing is used to regularly challenge code correctness and detect regression early. Testing can be easily assessed with numbers like code coverage ratio and the amount of assertions tested.
  • A clean code structure prevents the phenomenon of spaghetti code, entangled code that is hard to understand and hard to maintain. However assessing the code structure cannot be achieved through numbers like for testing. Moreover the structure emerges from a myriad of details buried in many source files and thus appropriate tooling is needed.

For most engineers, code dependency graph is the tool of choice to explore code structure. Boxes and arrows graph is intuitive and well adapted to visualize a small amount of dependencies. However to visualize complex portion of code the Dependency Structure Matrix (DSM) is more adapted. See below the same set of 34 namespaces visualized with the NDepend Dependency Graph and the NDepend Dependency Matrix.

NDepend dependency graph
NDepend dependency graph

 

NDepend Dependency Matrix
NDepend Dependency Matrix

If the concept of dependency matrix is something new to you, it is important to note that:

  • The Matrix headers’ elements represent graph boxes
  • The Matrix non-empty cells correspond to graph arrows. Numbers on the cells represents a measure of the coupling in terms of numbers of methods and fields involved. In a symmetric matrix a pair of blue and green cell is symmetric because both cells represents the same thing: the blue cell represents A uses B and the green cells represents B is used by A.

Here is a 5 minutes introduction video if you are not familiar with the dependency matrix:

Clearly the graph is more intuitive, but apart the two red arrows that represent two pairs of namespaces mutually dependent this graph tells few things about the overall structure.

On the other hand the matrix algorithm naturally attempts to layer code elements, exhibit dependency cycles, shows which element is used a lot or not… Let’s enumerate some structural patterns that can be visualized at a glance with the dependency matrix:

Layers

One pattern that is made obvious by a DSM is layered structure (i.e acyclic structure). When the matrix is triangular, with all blue cells in the lower-left triangle and all green cells in the upper-right triangle, then it shows that the structure is perfectly layered. In other words, the structure doesn’t contain any dependency cycle.

On the right part of the snapshot, the same layered structure is represented with a graph. All arrows have the same left to right direction. The problem with graph, is that the graph layout doesn’t scale. Here, we can barely see the big picture of the structure. If the number of boxes would be multiplied by 2, the graph would be completely unreadable. On the other side, the DSM representation wouldn’t be affected; we say that the DSM scales better than graph.

Notice that NDepend proposes 2 rules out of the box to control layering by preventing dependency cycles to appear: ND1400 Avoid namespaces mutually dependent and ND1401 Avoid namespaces dependency cycles.

Interestingly enough, most of graph layout algorithms rely on the fact that a graph is acyclic. To compute layout of a graph with cycles, these algorithms temporarily discard some dependencies to deal with a layered graph, and then append the discarded dependencies at the last step of the computation.

Cycles

If a structure contains a cycle, the cycle is displayed by a red square on the DSM. We can see that inside the red square, green and blue cells are mixed across the diagonal. There are also some black cells that represent mutual direct usage (i.e A is using B and B is using A).

The NDepend’s DSM comes with the option Indirect Dependency. An indirect dependency between A and B means that A is using something, that is using something, that is using something … that is using B. Below is shown the same DSM with a cycle but in indirect mode. We can see that the red square is filled up with only black cells. It just means that given any element A and B in the cycle, A and B are indirectly and mutually dependent.

Here is the same structure represented with a graph. The red arrow shows that several elements are mutually dependent. But the graph is not of any help to highlight all elements involved in the parent cycle.

Notice that in NDepend, we provided a button to highlight cycles in the DSM (if any). If the structure is layered, then this button has for effect to triangularize the matrix and to keep non-empty cells as closed as possible to the diagonal.

High Cohesion / Low-Coupling

The idea of high-cohesion (inside a component) / low-coupling (between components) is popular nowadays. But if one cannot measure and visualize dependencies, it is hard to get a concrete evaluation of cohesion and coupling. DSM is good at showing high cohesion. In the DSM below, an obvious squared aggregate around the diagonal is displayed. It means that elements involved in the square have a high cohesion: they are strongly dependent on each other although. Moreover, we can see that they are layered since there is no cycle. They are certainly candidate to be grouped into a parent artifact (such as a namespace or an assembly).

On the other hand, the fact that most cells around the square are empty advocate for low-coupling between elements of the square and other elements.

In the DSM below, we can see 2 components with high cohesion (upper and lower square) and a pretty low coupling between them.

While refactoring, having such an indicator can be pretty useful to know if there are opportunities to split coarse components into several more fine-grained components.

Too many responsibilities

The popular Single Responsibility Principle (SRP) states that: a class shouldn’t have more than one reason to change. Another way to interpret the SRP is that a class shouldn’t use too many different other types. If we extend the idea at other level (assemblies, namespaces and method), certainly, if a code element is using dozens of other different code elements (at same level), it has too many responsibilities. Often the term God class or God component is used to qualify such piece of code.

DSM can help pinpoint code elements with too many responsibilities. Such code element is represented by columns with many blue cells and by rows with many green cells. The DSM below exposes this phenomenon.

Popular Code Elements

A popular code element is used by many other code elements. Popular code elements are unavoidable (think of the String class for example).

A popular code element is not a flaw. However it is advised that popular elements are interfaces and enumerations. This way consumers rely on abstractions and not on implementations details. The benefit is that consumers are less often broken because abstraction are less subject to change than implementations.

A popular code element is represented by columns with many green cells and by rows with many blue cells. The DSM below highlights a popular code element.

Something to notice is that when one is keeping its code structure perfectly layered, popular components are naturally kept at low-level. Indeed, a popular component cannot de-facto use many things, because popular component are low-level, they cannot use something at a higher level. This would create a dependency from low-level to high-level and this would break the acyclic property of the structure.

Mutual dependencies

You can see the coupling between 2 components by right clicking a non-empty cell, and select the menu Open this dependency.

If the opened cell was black as in the snapshot above (i.e if A and B are mutually dependent) then the resulting rectangular matrix will contains both green and blue cells (and eventually black cells as well) as in the snapshot below.

In this situation, you’ll often notice a deficit of green or blue cells (3 blue cells for 1 green cell here). It is because even if 2 code elements are mutually dependent, there often exists a natural level order between them. For example, consider the System.Threading namespaces and the System.String class. They are mutually dependent; they both rely on each other. But the matrix shows that Threading is much more dependent on String than the opposite (there are much more blue cells than green cells). This confirms the intuition that Threading is upper level than String.