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: