Visual Studio 2019 Tricks and Techniques - Paul Schroeder - E-Book

Visual Studio 2019 Tricks and Techniques E-Book

Paul Schroeder

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Visual Studio 2019 (VS 2019) and Visual Studio Code (VS Code) are powerful professional development tools that help you to develop applications for any platform with ease. Whether you want to create web, mobile, or desktop applications, Microsoft Visual Studio is your one-stop solution. This book demonstrates some of the most sophisticated capabilities of the tooling and shows you how to use the integrated development environment (IDE) more efficiently to be more productive.
You’ll begin by gradually building on concepts, starting with the basics. The introductory chapters cover shortcuts, snippets, and numerous optimization tricks, along with debugging techniques, source control integration, and other important IDE features that will help you make your time more productive. With that groundwork in place, more advanced concepts such as the inner workings of project and item templates are covered. You will also learn how to write quality, secure code more efficiently as well as discover how certain Visual Studio features work 'under the hood'.
By the end of this Visual Studio book, you’ll have learned how to write more secure code faster than ever using your knowledge of the extensions and processes that make developing successful solutions more enjoyable and repeatable.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 370

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Visual Studio 2019 Tricks and Techniques

A developer's guide to writing better code and maximizing productivity

Paul Schroeder

Aaron Cure

BIRMINGHAM—MUMBAI

Visual Studio 2019 Tricks and Techniques

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Aaron Lazar

Publishing Product Manager: Richa Tripathi

Senior Editor: Nitee Shetty

Content Development Editor: Ruvika Rao

Technical Editor: Gaurav Gala

Copy Editor: Safis Editing

Project Coordinator: Francy Puthiry

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Vijay Kamble

First published: January 2021

Production reference: 1150121

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80020-352-5

www.packt.com

To my mother, Karen, and to the memory of my father, Robert, for creating the company that set our family on this path decades ago. To the memory of my brother, Michael, whose son, Robert, now connects a third generation of Schroeders to that very company.

– Paul Schroeder

To my loving family, Sherry, Katy, Kenzie, and Tee, for all their support and patience in all the craziness that is our life. Also, to my parents, Charles and Karen, who raised us to believe that through hard work and dedication, anything is possible, and for moving us out of a place that thought that computers were "a passing fad."

– Aaron Cure

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsImprove your learning with Skill Plans built especially for youGet a free eBook or video every monthFully searchable for easy access to vital informationCopy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Foreword

By combining Visual Studio Code and Visual Studio (VS), the brand is over two times more commonly used by developers than any other environment (Stack Overflow, 2019). What that means is that this topic is vital for 80% of all developers.

It also means that with this book, Paul Schroeder and Aaron Cure had the opportunity to provide something incredibly valuable and essential for developers, a vital reference for the global developer community.

I personally think there are two ways to learn in life: you can learn from your own failures and mistakes, or you can learn from someone else's failures and mistakes. I'll pick the second option, every time.

With this book, Paul and Aaron have cracked the code. Everything in here is a lesson learned. It's like you're getting all the advice that was learned from the mistakes and failures of thousands of developers... including (1) the developers who Paul and Aaron learned from (via books, articles, and advice), (2) the developers at Microsoft, who got feedback from customers and built the great features you'll find in VS (not to mention the customers who struggled and needed those features), (3) the developers in the community who helped create some of the amazing extensions covered in this book, and (4) the personal insights discovered directly by Paul and Aaron, through their combined experience of 40+ years in software development!

You now have a book (in your hands or on a screen) that not only teaches beginners how to use VS but is also useful for intermediate developers pursuing knowledge to become more effective. Simply put, this could very well be one of the greatest investments you make for your career. Even if you are a very experienced developer, you'll still gain a lot from this book... you'll learn a few new techniques and, more importantly, you'll have a cheat sheet to look back on as a reference.

New developers will rapidly learn about the different types of VS, the shortcuts, how to use the interface, how to use a repo, exploring data, and compiling/debugging. Meanwhile, experienced developers will pick up a few new tricks in those topics, and they will also learn (and have as a reference to come back to) how to better leverage code snippets, how to become a legend with templates, and how to take full advantage of extensions.

If you apply the snippets, templates, and extension practices found in this book, not only will you become a drastically more efficient and effective coder, but you'll also become your team's hero and thought leader!

What does all this mean? It means that if you're a developer, you owe it to yourself to learn from as many failures as you can. This book is born out of the mistakes and failures of thousands of developers who came before you. You would be wise to read it now and revisit it each year. If you do that, you'll get faster and better, every time.

Ed Price Senior Program Manager (of Architectural Publishing)Microsoft | Azure Architecture Center (http://aka.ms/Architecture)Co-author of four books, including Hands-On Microservices with C# 8 and .NET Core 3 (from Packt)

Contributors

About the authors

Paul Schroeder is a versatile application developer, speaker, author, and managing director at MSC Technology Consulting (MSCTek.com). Along with a multi-decade professional IT career, Paul has a bachelor's degree in computer science and an MBA, and has earned an MCSD certification for web development.

Whether coding or not, Paul enjoys spending time with his marvelous and talented wife, Robin, herself a Xamarin developer/speaker who creates Bluetooth mesh mobile applications.

Drawn to code generation, Paul is the inspiration behind CodeGenHero™, an innovative Visual Studio extension, covered in Chapter 14, Be Your Team's Hero with CodeGenHero. You are encouraged to register for a free trial at CodeGenHero.com so that you, too, can save oodles of time on software projects. Follow Paul at @PaulBSchroeder.

Firstly, thank you to our technical reviewers, Robin Schroeder and Eric Mead, whose feedback and testing was invaluable. Likewise, to the whole team at Packt whose patience and persistence made this book possible.

Shoutout to James Wall, an MSC employee whose determined effort helped bring the concept of CodeGenHero™ to life. Likewise, thanks to Patrick Goode, an employee who brought fresh ideas to support the completion of that journey.

I'd like to express gratitude to Microsoft, for creating the tooling and products that empower me to help numerous organizations and make an excellent living.

Finally, thanks COVID-19, for making this such an awful year that I finally made time to write a book – good riddance, 2020!

Aaron Cure is a principal security consultant for Cypress Data Defense specializing in penetration testing, secure SDLC, static code review, and secure architectures. His certifications include CISSP, GPEN, GMOB, GWAPT, and GSSP-NET. As a global speaker and instructor, Aaron is passionate about helping developers understand and write safe and secure code.

Aaron transitioned to programming after a decade as a Russian linguist and a satellite repair technician in the Army. He was an early adopter of technologies such as Mono and NHibernate for cross-platform development. Besides .NET, he has programmed in PHP, Python, Perl, TCL/TK, and Java.

Currently, Aaron programs almost entirely in VS Code and .NET Core with projects transitioning to .NET 5.

I'd like to thank our reviewers, Robin Schroeder and Eric Mead, for reviewing all of our words and code and providing invaluable feedback.

I'd also like to thank my co-author, Paul Schroeder, for beginning this adventure with me, and like our last hike together, dragging me to the finish line.

About the reviewers

Robin Schroeder has been writing code professionally for over two decades. She is currently a cross-platform mobile Xamarin developer, software consultant, girls, coding club volunteer, and public speaker. She finds herself bouncing between all flavors of Visual Studio on a regular basis.

To my brilliant husband, Paul, who has loved elegant code generation since before we fell in love 18 years ago. I am so thankful to be able to rely on your support to reach my career goals, so humbled to see what a great father you are to our kiddos, and so proud to have been able to support this amazing project and your vision of CodeGenHero.

Eric Mead has more than 15 years of experience in software development, primarily in the financial and agriculture industries. His primary focus is .NET Framework; however, he also has a considerable amount of experience in frontend frameworks such as Angular and React. As a co-founder of Puma Security, he is a software architect who writes static source code analysis rules and contributes to the open source version. Eric has held positions as a software consultant, business intelligence developer, and senior software developer. Eric holds a bachelor of science degree in computer engineering from Iowa State University, with an emphasis on software engineering and information security. 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Section 1: Visual Studio IDE Productivity Essentials

Chapter 1: Flavors of Visual Studio

Technical requirements

Quick reference cheat sheet

Visual Studio 2019 (Windows)

Features of VS 2019 Enterprise edition

Visual Studio 2019 for Mac

GitHub Codespaces

Summary

Chapter 2: Keyboard Shortcuts

Technical requirements

Windows shortcuts

Shortcuts that work in both Windows and Visual Studio

Intermediate-level shortcuts

Keyboard mapping schemes

Choosing a keyboard mapping scheme

Customizing your own keyboard mapping schemes

Creating an individual shortcut

Viewing existing shortcuts

Importing an entire keyboard mapping scheme

Learning keyboard shortcuts

Installing the Learn the Shortcut extension

Default Learn the Shortcut behavior

Justification for investing time

Summary

Further reading

Chapter 3: IDE Tips and Tricks

Technical requirements

Having fun with the file tabs

Pinning documents

Vertical documents

Horizontal and vertical groups

Traversing your solution

Navigating through active windows or tabs

Using Quick Launch

Track Active Item

Live sharing

Preview Features

Faster editing

Column Mode

Multi-caret selects

Toolbox

Cleaner code

Code Formatting

Code Cleanup

Summary

Chapter 4: Working with a Repository

Technical requirements

Automating Git commands

Git commands quick reference

Working with source control

Creating a repository

For Windows

For VS Code

For Mac

Cloning a repository

For Windows

For VS Code

For Mac

Getting updates (Fetch and Pull)

For Windows

For VS Code

For Mac

Adding files

For Windows

For VS Code

For Mac

Creating a .gitignore file

Committing (and pushing) your code

For Windows

For VS Code

For Mac

Stashing (and applying) your code

Understanding branch and merge

Creating a branch

Working with pull requests

Summary

Chapter 5: Working with Snippets

Technical requirements

Snippet basics

Inserting snippets

Code Snippets Manager dialog

Examining a custom snippet's XML definition

Deploying snippets

Importing a custom snippet

Summary

Further reading

Chapter 6: Database Explorers

Technical requirements

Managing databases in Visual Studio 2019 for Windows

Working with SQL Server Object Explorer

Interacting with databases in VS Code

Getting connected

Creating our database

Expanding the database

Summary

Chapter 7: Compiling, Debugging, and Versioning

Technical requirements

Installing Docker

Exploring compilation flags and options

Visual Studio 2019 for Windows

Visual Studio Code

Visual Studio 2019 for Mac

Conditional compilation

Regions

Pre-build and post-build events

Investigating advanced debugging

Breakpoints

The Immediate window

Who's watching?

Remote debugging

Remote debugging Docker in Visual Studio 2019 for Windows

What about remote debugging in VS Code?

Visual Studio 2019 for Mac, too!

Discovering versioning

Versioning in traditional full framework .NET projects

Versioning in .NET Core

Summary

Section 2: Customizing Project Templates and Beyond

Chapter 8: Introduction to Project and Item Templates

Technical requirements

Understanding item templates

Knowing when to use project templates

Template tags

When to use templates

Looking at a sample scenario

Running the project

Examining the project

Valuing templates

Summary

Further reading

Chapter 9: Creating Your Own Templates

Technical requirements

Exporting a custom project template

Using the exported project template

Identifying issues with the project template

Fixing problems in the template definition

Understanding template parameters

Reimporting the fixed template

Exporting project items

Summary

Chapter 10: Deploying Custom Templates

Technical requirements

Installing the Visual Studio SDK component

Introducing the client-server project

Client-server sample code

Creating the VSIX deployment package

Reviewing the deployment project

Examining the template project

Making template wizards

Using the VSIX deployment package

Testing the project template

Publishing to the Visual Studio Marketplace

Distributing instructions for the Dotnet Core CLI

Summary

Section 3: Leveraging Extensions for the Win

Chapter 11: Overviewing Visual Studio 2019 Extensions

Technical requirements

What are extensions?

Visual Studio Marketplace

Creating extensions

Creating extensions in Visual Studio 2019 for Windows

Creating extensions in Visual Studio 2019 for Mac

Roslyn analyzers

Summary

Chapter 12: Overviewing VS Code Extensions

Technical requirements

What are VS Code extensions?

VS Code in the Visual Studio Marketplace

Creating an extension

Generating a basic extension

Making our extension work for us!

Publishing your extension

Summary

Chapter 13: CodeMaid is Your Friend

Technical requirements

A brief history of CodeMaid

Configuring CodeMaid

Reorganizing to reduce merge conflicts

User profile and solution settings

Learning about cleanup actions

The narrowing gap

Exploring CodeMaid Spade

McCabe Cyclomatic Complexity

Build Progress

Summary

Chapter 14: Be Your Team's Hero with CodeGenHero

Technical requirements

Understanding the core concepts of code generation

Metadata and templates

Introducing CodeGenHero™

Installing CodeGenHero™

Example project overview

Scaffolding a solution – .NET Core CLI

The CodeGenHero™ solution

Creating a metadata source

Configuring a blueprint

Choosing templates

Configuring template parameters

Mapping target projects

Integrating generated code

Handling change with CodeGenHero™

How does it work?

Changing the database schema

Merging changes

Summary

Chapter 15: Secure Code with Puma Scan

Technical requirements

Understanding common application security vulnerabilities

A1:2017-Injection

A6:2017-Security Misconfiguration

A7:2017-Cross-Site Scripting (XSS)

A9:2017-Using Components with Known Vulnerabilities

A10:2017-Insufficient Logging and Monitoring

Finding vulnerabilities for fun and profit

Automating vulnerability detection with Puma Scan

Installing Puma Scan in Visual Studio 2019

Installing Puma Scan in VS Code

Running Puma Scan and viewing the results

Extending Puma Scan with custom sinks

Using Puma Scan in a DevSecOps pipeline 

Summary

Appendix

Other Popular Productivity Extensions

Presenting some great Visual Studio 2019 for Windows extensions

Conveyor by Keyoti

Ozcode – Magical C# debugging

Open Command Line

ReSharper

Visual Studio Spell Checker

Sharing our favorite Visual Studio Code extensions

Increment selection

CamelCase

C# extensions

The vscode-icons and vscode-icons-mac extensions

Beautify

The vscode-spotify extension

Choosing useful Visual Studio 2019 for Mac extensions

LiveXAML for Xamarin.Forms

MFractor

NuGet package management extensions

MvvmCross Template Pack

Summary

Other Books You May Enjoy

Preface

Visual Studio 2019 for Windows, Visual Studio Code, and Visual Studio 2019 for Mac are full-featured integrated development environments (IDEs) for building and debugging modern web, mobile, desktop, and cloud applications. They can be used to write applications that target .NET 5.0 or .NET Core for Linux, macOS, and Windows. Likewise, they support containerized development with Docker, mobile apps with Xamarin, desktop using WPF or Windows Forms, and game development with Unity.

In this book, we cover numerous productivity tips, shortcuts, and snippets that you need to make the most of your coding time. For newer developers, the book includes content to help determine the right flavor of Visual Studio for your needs. Also, instructions on how to work with Git source control, databases, and debugging are included. For more advanced professionals, lesser-known capabilities such as how to create and deploy your own custom project and item templates are explained in detail. Everyone can appreciate the considerable coverage of extensions that extend and enhance the features and functionality available out of the box with Visual Studio.

Using several hands-on exercises, we go beyond the basics of working with Visual Studio 2019. Through these exercises and extensions, you will see how to clean code, how to generate code, and also how to secure code. The examples used in this book are simple and easy to understand. There are numerous images and clear step-by-step directions for guidance. Throughout this book, you will travel down a path that both enhances existing skills and helps you master a few new ones. By the end, you will have a deeper knowledge of the Visual Studio IDE and, hopefully, be ready to put these techniques into practice.

Who this book is for

This book is for any C# and .NET developer who wants to increase their productivity and write code fast by fully utilizing the power of the Visual Studio IDE. It helps take your understanding of Visual Studio 2019 to the next level. Those who want to delve deeper and peek under the hood to learn what Visual Studio does behind the scenes will be satisfied. Application architects will learn techniques that improve standardization across multiple projects and reduce ramp-up time. Additionally, coders who want to see how the development process can be reimagined using code generation and secure code scanning technology will be impressed.

Users of any IDE flavor will benefit from this book, including Visual Studio 2019 for Windows, Visual Studio Code, and Visual Studio 2019 for Mac. Several chapters include specific content for each version. A few chapters contain hands-on exercises that target only Visual Studio 2019 for Windows.

The material in the first and third sections of this book is appropriate for developers of any skill level (Visual Studio IDE Productivity Essentials and Leveraging Extensions for the Win). Those newer to developing with Visual Studio may find the content in the third section of the book interesting but a bit abstract (Customizing Project Templates and Beyond).

What this book covers

Chapter 1, Flavors of Visual Studio, is primarily for those new to programming or .NET development. This chapter describes the key factors to consider when deciding which version of Visual Studio is right for you.

Chapter 2, Keyboard Shortcuts, shows how most tasks can be performed directly from the keyboard, without a mouse. It pulls back the curtain on the magic of keyboard shortcuts in Visual Studio 2019 for Windows and teaches you how to customize the tool.

Chapter 3, IDE Tips and Tricks, demonstrates ways to organize code files and quickly navigate in the IDE/solution files. How to access preview features and use Live Sharing is covered, as well as tips for faster code insertion and editing.

Chapter 4, Working with a Repository, provides all the basic knowledge you need to know to work with Git source control via Visual Studio. It covers how to create/clone a repo as well as how to add files, get updates, and commit code. Branching, merging, and pull requests are also topics.

Chapter 5, Working with Snippets, explains how to use snippets that come pre-installed with Visual Studio, how to manage them with the Code Snippets Manager dialog, and even how to make and import your own custom creations.

Chapter 6, Database Explorers, teaches you how to manage databases in Visual Studio 2019 for Windows as well as Visual Studio Code, and how to create a database, table, and data rows. Then, you'll see how to select and export that data.

Chapter 7, Compiling, Debugging, and Version Control, explores conditional compilation symbols, breakpoints, and immediate and watch windows. How to install Docker is covered before remote debugging is performed in a hands-on exercise using a Docker container. An automated approach to versioning assemblies wraps up this chapter.

Chapter 8, Introduction to Project and Item Templates, is a primer for the chapters that follow. It includes information on when to use templates and how template tags work. The sample project that is used in subsequent chapters is introduced here.

Chapter 9, Creating Your Own Templates, demonstrates how to export and import custom project templates to/from Visual Studio. You will create a new project using a custom template, provided in the download accompanying this book, identify and fix issues with it, and then learn how to make your own project item template.

Chapter 10, Deploying Custom Templates, contains more advanced content leveraging knowledge gained in the two prior chapters. You are guided step by step through an exercise that examines VSIX deployment package creation for a sample client-server solution. By the end, a multi-project template, complete with an IWizard UI implementation, is ready to go. Simply add a new project, enter a database connection string, and out pops a working Web API server sending data down to a WPF client. Information on how to distribute your custom templates to the marketplace rounds out this chapter.

Chapter 11, Overviewing Visual Studio 2019 Extensions, eases in with an introduction to extensions and searching for them in Visual Studio Marketplace. Learn how to manage them and how to create them in both Windows and Mac. Finish with a tour of Roslyn analyzers and create one that analyzes code related to the extension created in the prior exercise.

Chapter 12, Overviewing VS Code Extensions, is dedicated to extensions in Visual Studio Code. How to create extensions is covered through a step-by-step exercise that is designed to put a licensing header at the top of code files. The chapter ends with how to create a VSIX installer file to share the extension or deploy it to the marketplace.

Chapter 13, CodeMaid Is Your Friend, extolls the benefits of organized code, along with a brief history of this popular extension, CodeMaid. Cleanup actions and features such as CodeMaid Spade are explored along with the many configurable options available.

Chapter 14, Be Your Team's Hero with CodeGenHero™, studies a unique perspective on code generation. You are guided through an example project where many classes are auto-generated, including the web API and client-side data access components. Key topics such as how to configure a metadata source, blueprints, choosing templates, configuring parameters, and merging output results are covered. Changing the database schema and regenerating the source code adds a finishing touch.

Chapter 15, Secure Code with Puma Scan, helps you understand common application security vulnerabilities such as SQLi, XSS, and security misconfiguration. It talks about how to find vulnerabilities for fun and profit before automating vulnerability detection using the Puma Scan extension. How to extend Puma Scan with custom sinks is discussed as well as how to incorporate it into a DevSecOps pipeline.

Chapter 16, Other Popular Productivity Extensions, is a great, light way to close out this book. This chapter provides an overview of great extensions for Visual Studio, favorite extensions for Visual Studio Code, and some useful extensions for Visual Studio for Mac. Whereas prior chapters on extensions went deep with exercises, this one goes wide. Information is provided on 15 different extensions that can improve your developer experience.

To get the most out of this book

You will need Microsoft Visual Studio 2019 or Visual Studio Code installed on your system. Choosing the right version of Visual Studio 2019 is covered in the first chapter. Some of the chapters cover all three major flavors of Visual Studio. A few chapters are more partial to Visual Studio for Windows and some exercises contain sample code that uses the full .NET Framework v4.7.2.

Although not strictly required, installing the following workloads with Visual Studio for Windows will allow you to walk through all examples:

ASP.NET and web development.NET desktop development.NET Core cross-platform developmentVisual Studio extension development

In chapters that require special setup or attention, specific instructions are provided at the outset. For example, the chapters on CodeGenHero™ and Puma Scan contain plenty of screenshots to communicate the material, but registration for free trial versions is necessary to walk through the step-by-step exercises.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at www.packt.com.Select the Support tab.Click on Code Downloads.Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for WindowsZipeg/iZip/UnRarX for Mac7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Visual-Studio-2019-Tricks-and-Techniques. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

Please visit the following link to check the CiA videos: https://bit.ly/3oxE5QM.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800203525_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

<Header>

    <Title>API Method Timer</Title>

    <Shortcut>apitimer</Shortcut>

    <Description>Leverages System.Diagnostics.Stopwatch to log how long it took to execute a method.</Description>

</Header>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<LanguageTag>C#</LanguageTag>

<PlatformTag>windows</PlatformTag>

<ProjectTypeTag>console</ProjectTypeTag>

<ProjectTypeTag>desktop</ProjectTypeTag>

<ProjectTypeTag>TipTrick</ProjectTypeTag>

Any command-line input or output is written as follows:

$ git config --global init.defaultBranch main

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "To see the installed keyboard mapping schemes in Visual Studio 2019 for Windows, navigate to the Tools Menu | Options | Environment | Keyboard dialog."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: Visual Studio IDE Productivity Essentials

This section provides the foundational knowledge all developers using Visual Studio should know in order to improve their productivity. Beyond the basics, some of the lesser-known features of the integrated development environment (IDE) are uncovered. Numerous hands-on exercises dive deep into how Visual Studio works behind the scenes.

This section has the following chapters:

Chapter 1, Flavors of Visual StudioChapter 2, Keyboard ShortcutsChapter 3, IDE Tips and TricksChapter 4, Working with a RepositoryChapter 5, Working with SnippetsChapter 6, Database ExplorersChapter 7, Compiling, Debugging, and Version Control

Chapter 1: Flavors of Visual Studio

Microsoft Visual Studio is an Integrated Development Environment (IDE) from Microsoft. Over its more than twenty-year history, it has been used by developers to develop all kinds of computer programs, web applications, web APIs, and mobile apps. A 2019 survey by Stack Overflow found Visual Studio and its cousin, Visual Studio Code (VS Code), to be two of the most popular development environments among all survey respondents (see https://insights.stackoverflow.com/survey/2019):

Figure 1.1 – Stack Overflow 2019 survey

Note on Stack Overflow 2020 survey results

Although Stack Overflow's 2020 survey results were available at the time of writing, they did not seem to include the same specific question on development environments.

Visual Studio provides robust coding and debugging capabilities as well as extensive integration for deployment and source control needs. You can use it to program anything from a desktop business application, to a web site, mobile application, or Unity game.

If you are new to programming or .NET development, it is important to understand that there are several options to consider before starting. This chapter's primary focus is to cover some key factors you should consider when deciding which product "flavor" of Visual Studio is right for you, including the following:

Primary operating system (Windows, macOS, or Linux)Target framework (.NET full framework, .NET Core)Team size and budgetApplication type (Windows, web, mobile, server, or console)Cross-platform portability requirementsChosen programming language (such as C#, VB, Python, Ruby, or NodeJS)

The reason why we must examine the aforementioned points in detail is because Microsoft has combined what are actually multiple, separate, products under a single marketing umbrella. This can make choosing between these products confusing and so we will take a moment to clearly identify each version, differentiate their features, and provide some guidance on which version may be best for your purposes.

Technical requirements

The code for this book is available on GitHub at: https://github.com/PacktPublishing/Visual-Studio-2019-Tricks-and-Techniques/tree/main/.

Please check the following link for CiA videos: http://bit.ly/3oxE5QM.

Quick reference cheat sheet

With so many options, how does a developer know which version to use? The following is a list of simplified suggestions to help you choose a particular flavor:

If you are using a PC and are brand new to software development, start with VS 2019 Community.If you are using a PC as an experienced developer, or have a well-funded company footing the bill, consider the VS 2019 Professional or VS 2019 Enterprise editions.If you're primarily a web developer planning to use NodeJS and TypeScript, try VS Code.If you're developing cross-platform iOS/Android mobile apps, consider using VS for Mac.

Have you already decided on which version to use?

If you have already figured out which version of Visual Studio is right for you, then feel free to skip this chapter's content. Alternatively, if you are an experienced developer, skim this material looking for new tidbits, such as GitHub Codespaces.

For those readers that need more information to decide, let's begin digging into the details of the most long-lived product flavor, Visual Studio for Windows.

Visual Studio 2019 (Windows)

Let's start with Visual Studio 2019 (VS 2019), a Windows-based IDE (pronounced AYE-dee-ee). Some people will refer to this product as the full version. This version only runs on Windows (not cross-platform), but it does support both .NET "full framework" and .NET Core (cross-platform) project targets. Something all versions of Visual Studio do exceptionally well is work with diverse programming languages (including C, C++, Visual Basic. NET, C#, F#, JavaScript, TypeScript, Python, Ruby, and Node.js).

Different tiers of features are offered, depending on your needs and budget. Current versions of VS 2019 include a free Community edition as well as paid Professional, Enterprise, and Test Professional versions. The Community and Professional editions are nearly identical when it comes to operational features and, for most development tasks, any version of Visual Studio will work.

The Community version is depicted in the screenshot that follows and you will find virtually no difference between its appearance and that of the other versions:

Figure 1.2 – VS 2019 Community – Windows

Even with multiple options, choosing a Visual Studio edition is much easier today than in the past. Previously, certain project types could only be loaded in one edition or another, and many add-ins would not run in certain editions. Complex licensing issues compounded these problems, making it more difficult to choose.

Today, even the free Community edition is a powerful environment with much to offer. Many of the popular features, such as peeking at definitions, multi-targeting of release targets, and refactoring are supported in all editions.

More succinctly, the major versions of VS 2019 are as follows:

Community – Free for students, open source contributors, and individualsProfessional – The best choice for small teamsTest Professional – An option for dedicated Quality Assurance (QA) rolesEnterprise – Offers extra features (mentioned later in this chapter) and works well for teams of any size

In the past, the Community version, originally labeled "Express," was a very limited version that allowed only basic application development but would not allow for particular target types (such as Visual Studio plugins), and would also not allow a number of plugins to run. While some of these limitations seemed minor, they were enough to create negative perceptions of the platform among some developers and sour development community sentiment on the Community version. In recent years, Microsoft has removed many of the original restrictions and enabled so much functionality in this version that the experience is now very similar to the Professional version.

Traditionally, the Professional version was the lowest tier version for "true" developers. Because of the limitations of other versions, this was the only way to do "actual" development. This version tier is (and always has been) a full-featured IDE with all the bells and whistles you would expect in a professional development tool.

A key difference is that VS 2019 Community is free, while the Professional version retails for about $1,199 for the first year's subscription and $799 annually for renewal thereafter. However, there are license restrictions that limit use of Visual Studio Community to teams of less than five developers. Also, it cannot be used by commercial organizations with over $1 million US dollars in annual revenue.

For those whose focus is purely QA, and not development, Test Professional is another option to consider. It provides an integrated testing toolset for QA teams, but does not include an IDE to build applications. Instead, this product flavor focuses on the creation and execution of tests and test suites. It also integrates nicely with Visual Studio Team Foundation Server (VSTFS) and Azure DevOps (ADO).

Finally, the Enterprise version of VS 2019 is available for organizations with more than 25 developers, or those seeking to take advantage of advanced features only available at this highest tier. This level includes advanced functionality such as memory profilers, Snapshot Debugger, Live Unit Testing, architectural layer diagrams, and architecture validation. An overview of some of these capabilities is provided next.

Features of VS 2019 Enterprise edition

The following provides a brief overview of a few features that are specific to the Enterprise version of VS 2019. These items may help you decide whether this is the right flavor of the IDE for your needs:

Performance profiling tools: VS 2019 provides a dozen or more profiling tools that can help diagnose different kinds of performance issues. Common metrics you may want to analyze include CPU usage, memory usage, and database performance. Some of these tools require the Enterprise edition, and some do not. Use this link to investigate the specific tools that match your needs: https://docs.microsoft.com/en-us/visualstudio/profiling/profiling-feature-tour?view=vs-2019.Live Unit Testing: While you are coding, Live Unit Testing automatically runs unit tests in the background and shows your code coverage live in Visual Studio. It provides a line-by-line visual indicator of test coverage as well as the status of passing/failing tests. As you modify code, this feature dynamically executes tests and provides immediate notification when changes cause tests to fail.Snapshot Debugger: If you are using Azure Application Insights, the Snapshot Debugger can be used to capture the state of source code and variables from a live, running, application. This can be helpful for troubleshooting exceptions that occur in a production environment. If you do not have the Enterprise edition of Visual Studio, you can view debug snapshots in the online portal, but using the Enterprise edition provides a more robust debugging experience.Live Dependency Validation: Another feature, only available in the Enterprise edition, is Live Dependency Validation. This lets teams validate architectural dependencies to ensure that they respect defined architectural constraints. In complex multi-layer applications, this can help ensure code dependencies flow in the right direction, which is important for maintainability. This can be useful on project teams with junior developers who may not fully understand the design. Detailed coverage of the Live Dependency Validation feature is beyond the scope of this chapter, but this video link provides a basic overview: https://channel9.msdn.com/Events/Visual-Studio/Visual-Studio-2017-Launch/T123.

Visual Studio Installer

To use certain features, like Code Map and Live Dependency Validation components, you must run the Visual Studio Installer, select the Individual components tab, and scroll down to the Code tools section. From there, select the Code Map and Live Dependency Validation components, as shown in the following screenshot. When you are ready, click the Modify button:

Figure 1.3 – Visual Studio Installer

Note

To be accurate, Visual Studio's Community and Professional editions do allow you to open diagrams that were generated using the Enterprise edition, albeit in read-only mode.

Despite their differences, from a functionality standpoint, the look and feel of all the editions are pretty much the same. Menus, tools, and functional controls are all implemented consistently, perform the same functions, and are mostly indistinguishable from one another.

Use the following link to review specific differences between versions: https://visualstudio.microsoft.com/vs/compare/.

In short, whichever version you choose, the experience should be nearly the same. For most development tasks, it makes no difference which version you are running: they all have the basic software development life cycle tools to create, debug, and run web, mobile, console, library, and just about any other project you can devise.

Visual Studio 2019 for Mac

If Windows isn't your primary operating system, Microsoft also offers Visual Studio for Mac, which unsurprisingly runs on Apple's macOS operating system. Historically, this product evolved from what was known as Xamarin Studio prior to Microsoft's acquisition of Xamarin in 2016.

Visual Studio 2019 for Mac supports development in C#, F#, Razor, HTML, CSS, JavaScript, TypeScript, XAML, and XML. It also supports ASP.NET Core and .NET Core development, Azure Functions, Azure Connected Services, and the ability to publish to Azure. Like its Windows parallel, the Mac version comes in Community, Professional, and Enterprise versions. It has support for using Docker containers, Unity game programming, and mobile app development using Xamarin and C#:

Figure 1.4 – Visual Studio 2019 – Mac

Note

One notable feature missing from VS 2019 for Mac, VS Code (discussed next), and .NET Core in general, is the ability to create cross-platform desktop applications (such as WPF, Windows Forms, and UWP). While there are several possible alternatives (Electron, Avalonia UI, Uno Platform, and so on), none truly stand out as a native interface like WPF on Windows with Visual Studio.

For convenience, the following figure shows a feature comparison between Visual Studio 2019 for Mac and VS 2019 (Windows). The few differences between these products lie in Mac's lack of support for some types of Windows desktop, Python, and Node.js development:

Figure 1.5 – Visual Studio 2019 Comparison

Note

The full image is available in Chapter 1, Flavors of Visual Studio at https://static.packt-cdn.com/downloads/9781800203525_ColorImages.pdf

Alternatively, use this link to see a comparison between the two versions: https://visualstudio.microsoft.com/vs/mac/#vs_mac_table.

One of the most glaring shortcomings of Visual Studio for Mac is its lack of robust source control integration functionality. Developers often compensate for this using third-party tools such as Litracens, SourceTree, gmaster, and so on. That said, the Visual Studio for Mac experience improves with each release and includes more support for different application types. With the differences between the Mac and Windows versions shrinking, it is conceivable that within a few releases, the Mac and Windows experiences of Visual Studio will become nearly identical to VS Code.

Commonly referred to as VS Code, the Visual Studio Code product had humble beginnings as a text editor with support for optional plugins, similar to Atom or Sublime Text. Many developers consider it a lightweight tool specifically geared toward building and debugging modern web and cloud applications. However, it has grown into a full cross-platform (covering Linux, macOS, and Windows) editor that is free for both private and commercial use. It runs cross-platform, supports multiple programming languages, and has basic features such as syntax highlighting and code-completion aids (IntelliSense), as well as support for more advanced features such as debugging, refactoring, and code snippets, provided by plugins:

Figure 1.6 – VS Code – Windows

Both the popularity and the capabilities of VS Code have increased dramatically since Microsoft open-sourced this product back in late 2015. The integrated terminal is one thing many developers like about VS Code. This feature can be very convenient as you do not have to switch between applications to perform command-line tasks.

The ease of writing plug-ins, such as OmniSharp for debugging support, is credited with evolving this tool into (almost) a full-fledged IDE with support for many C# application types (including .NET Console, .NET Standard, and .NET MVC), as well as a number of other languages such as Java, Python, Ruby, and NodeJS. It supports common development operations including debugging, task running, and version control. It remains simplified to provide just what a developer needs for quick code-build-debug cycles.

The following screenshot depicts VS Code running on Linux, superimposed over a screenshot of VS Code running on macOS. Noteworthy is the striking similarity between the Windows, Mac, and Linux versions of VS Code. This makes for a consistent experience between platforms and makes shifting between them feel quite natural:

Figure 1.7 – VS Code on Mac (upper-left) and Linux (lower-right)

Microsoft has really