© Dirk Strauss 2020
D. StraussGetting Started with Visual Studio 2019https://doi.org/10.1007/978-1-4842-5449-3_2

2. Working with Visual Studio 2019

Dirk Strauss1 
(1)
Uitenhage, South Africa
 

If you have been working with previous versions of Visual Studio, you will find that Visual Studio 2019 definitely does not break the mold. What I mean to say is that Visual Studio 2019 feels much the same as previous versions, and that’s a good thing.

While there are new features and enhancements in Visual Studio 2019, developers will find it really easy to work with from the start. If, however, you are new to Visual Studio, there are a few topics that deserve a closer look. This is what Chapter 2 is all about. We will be taking a look at the following:
  • Visual Studio project types and when to use them

  • Managing NuGet packages

  • Creating project templates

  • Creating and using code snippets

  • Using bookmarks and code shortcuts

  • The Server Explorer window

  • Visual Studio Windows

Chapter 2 is actually an extension of Chapter 1 in many respects. Things that didn’t make it into Chapter 1 are being discussed in Chapter 2. I do believe, however, that these are essential to working with Visual Studio and will benefit developers in their day-to-day coding.

Visual Studio Project Types

Visual Studio 2019 allows developers to create a new project in a couple of ways. The most obvious is when you start Visual Studio 2019. You will be presented with the Start screen as seen in Figure 2-1.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig1_HTML.jpg
Figure 2-1

Visual Studio 2019 Start screen

Here you will see recent projects that you can pin to the Start screen to always keep them available. If you right-click any of the recent projects, you will see a context menu pop up as shown in Figure 2-2.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig2_HTML.jpg
Figure 2-2

Context menu options on recent projects

You can remove the project from the list, pin or unpin it from the list, or copy the path to the project. Visual Studio 2019 has also made it quite easy to get to where you need to when working with projects. As seen in Figure 2-3, developers have a few options available to them when they are ready to start working with code.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig3_HTML.jpg
Figure 2-3

Get started section

Here you can start by grabbing code from GitHub or Azure DevOps, open a local Visual Studio project, open a local folder to edit code files, create a new project, or continue without code.

If Visual Studio is already open, you can create a new project from the menu bar by clicking the New Project button as seen in Figure 2-4. You can also hold down Ctrl+Shift+N.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig4_HTML.jpg
Figure 2-4

New Project Toolbar button

The Create a new project screen is displayed as seen in Figure 2-5, and you have a whole new experience here too when it comes to finding the project type that you want to create.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig5_HTML.jpg
Figure 2-5

Create a new project

You will see recent project templates displayed which is great should you need to get up and running with similar projects as what you have created before. You can also search for and filter project templates by language, platform, or project type as seen in Figure 2-6.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig6_HTML.jpg
Figure 2-6

Filter project templates

This allows you to quickly find what you are looking for.

Take note, though, that if you do not find what you are looking for, you may need to install a workload. To do this, click Install more tools and features. Refer to Chapter 1 to see how to use workloads in Visual Studio.

There are several project templates that you can choose from. Let’s see which ones there are and what project is suitable for specific situations.

Various Project Templates

Visual Studio 2019 has a whole host of project templates to choose from. I would even go as far as to say that it’s now even easier to find the template you need to use due to the filters in the Create a new project window. Let’s have a look at a few of these project templates net.

Console Applications

I remember that the first time that I wrote a single line of code was in a Console Application. This is a great template to use when you don’t need a UI for your application. The Console Application project template running on the .NET Framework can be seen in Figure 2-7.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig7_HTML.jpg
Figure 2-7

Console App (.NET Framework)

You will notice that this application is suited for running on Windows machines. But what if you need to run the Console Application across platforms such as Windows, Linux, and macOS? This is where .NET Core comes into play.

The Console Application project template running on .NET Core can be seen in Figure 2-8.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig8_HTML.jpg
Figure 2-8

Console App (.NET Core)

A few years ago (long before .NET Core was ever a thing), I needed to create an application that could be triggered on a schedule. The application’s executable would then be passed one of the several parameters that the application used to determine which database to connect to.

The application had to run without any user intervention to perform some sort of maintenance task. Due to the fact that no user intervention was needed, a Console Application best suited the use case. Be aware that a Console Application can accept user input, but for my purposes with this application, it was not necessary.

Windows Forms Application

In contrast to the Console Application, the Windows Forms application template is used when you need to create an app that has a UI. The project template (like the Console Application) can run on the .NET Framework or on .NET Core as seen in Figure 2-9.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig9_HTML.jpg
Figure 2-9

Windows Forms App (.NET Core and .NET Framework)

It is important to note that Windows Forms apps built on .NET Core will still only be able to run on Windows and is not able to run on Linux or macOS.

This means that WPF and Windows Forms apps built on .NET Core will only run on Windows. There are no plans to make these application types cross-platform.

Why then use .NET Core for Windows Forms applications? Well, .NET Core applications are very, very fast. So it is well worth thinking about using .NET Core for Windows Forms applications.

It is possible to port Windows Forms applications to .NET Core 3.0. You will need to run a tool called the .NET Portability Analyzer to check if your application uses any APIs not currently supported in .NET Core. If it does, you will need to refactor your code to avoid those unsupported dependencies.

For a detailed step-by-step, refer to the Microsoft Developer channel on YouTube, and look for the video “How to Port Desktop Applications to .NET Core 3.0”. At the time of writing this book, the URL to this video was www.​youtube.​com/​watch?​v=​upVQEUc_​KwU.

Scott Hunter and Olia Gavrysh discuss this topic at the 7:56 minute mark.

Windows Service

If you ever need to create a Windows application that continually runs in the background, performing some specific task, your best choice would be to use a Windows Service template as seen in Figure 2-10.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig10_HTML.jpg
Figure 2-10

Windows Service (.NET Framework)

Imagine that the application needs to monitor specific activity (be that in a database or file system) and then write messages to an event log. A Windows Service is perfectly suited for this purpose.

Windows Services have an OnStart method that allows you to define what needs to happen when the service starts. By definition, Windows Services are long-running applications that need to poll or monitor the system it runs on. To enable the polling functionality, you will need to use a Timer component.

A common mistake is to use a Windows Forms Timer for a Windows Service. You must ensure that you use the timer in the System.Timers.Timer namespace instead.

The System.Timers timer (Figure 2-11) that you add to the Windows Service will raise an Elapsed event at specific intervals.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig11_HTML.jpg
Figure 2-11

Various Timer Namespaces

It is in this Elapsed event that you can write the code that your service needs to run in order to do what it needs to do.

Web Applications

If you need to create applications that are web-based, you will definitely be creating an ASP.NET Web Application. If you have a look at the project templates, you will notice that you can create an ASP.NET Web Application that runs on .NET Core as seen in Figure 2-12.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig12_HTML.jpg
Figure 2-12

ASP.NET Core Web Application template

If you do not need to create an ASP.NET Core Web Application, you can create a web application that runs on the .NET Framework as seen in Figure 2-13.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig13_HTML.jpg
Figure 2-13

ASP.NET Web Application template

As can be seen in the template description, these templates will allow you to create a regular Web Forms application, an MVC application or Web API application. If you need to run your application in a browser, then create an ASP.NET Web Forms or ASP.NET MVC application.

A Web API, on the other hand (sometimes also referred to as Web Services), is an application programming interface (API) that allows communication between various clients such as browsers, mobile devices, etc., and other software components such as a database. It can be used as a stand-alone application or as part of an ASP.NET Web Forms or MVC application.

Class Library

The last project template we will be looking at is the Class Library. It is worth noting that the Class Library will create a DLL that you can reuse in your applications. This is the purpose of a Class Library project.

There are many more project templates available in Visual Studio and are dependant on the workloads you have installed.

As you see in Figure 2-14, the Class Library can be based on .NET Core, .NET Framework, or .NET Standard.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig14_HTML.jpg
Figure 2-14

Class Library Projects

You might be wondering what the differences are between the various project templates. You will find a hint when you look at the tags. The Class Library running the .NET Framework will create a DLL that will only work on Windows machines.

The Class Library running .NET Core will create a library that will run on Windows, Linux, and macOS (it’s therefore cross-platform).

The Class Library running on .NET Standard will create a library that is guaranteed to run on all of the platforms supported in Visual Studio. The .NET Standard is a specification of all the APIs that work on all of the platforms. Therefore, if you create a Class Library on .NET Standard, it is guaranteed to run on desktop, mobile, Web, etc.

For more information regarding .NET Standard, have a look at the following article on Microsoft Docs: https://​docs.​microsoft.​com/​en-us/​dotnet/​standard/​net-standard

There are many more project templates to choose from, and the project templates you see will depend on the workloads that you have installed. Explore some of the different workloads available to you, and see what project templates are available to you after installing a particular workload.

Managing NuGet Packages

As a software developer, being able to reuse code is essential to any modern development effort. In fact, being able to share code is the cornerstone of a healthy development community. There are many developers that create extremely useful code libraries that can add functionality to your particular application.

This is where NuGet becomes an essential tool for developers to create, share, and consume useful code. As a developer, you can package a DLL along with other required content needed for the DLL to function correctly, into a NuGet package.

Essentially, NuGet is just a ZIP file with a .nupkg extension that contains the DLLs you have created for distribution. Included inside this package is a manifest file that contains additional information such as the version number of the NuGet package.

Packages uploaded to nuget.org are public and available to all developers that use NuGet in their projects. Developers can, however, create NuGet packages that are exclusive to a particular organization and not available publicly. We will have a look at hosting your own NuGet feeds later on. For now, let’s have a look at how to use NuGet in your own Visual Studio project.

Using NuGet in Visual Studio

Developers can access NuGet right from within Visual Studio, but you can also browse www.nuget.org to find packages to use in your applications. In the following example, we will be using NuGet from within Visual Studio to add functionality to our ShipmentLocator application.

I have added a login form to the ShipmentLocator application as seen in Figure 2-15. What I want to do is encrypt the password typed in by the user and compare that to the encrypted password in the database.

As a rule, you should never be able to decrypt a password. If you can decrypt a password, then so can others that have more malicious intentions. After user registration, the encrypted password is stored in a database. Login requests are then encrypted and compared with the encrypted password in the database. If it’s a match, they are successfully authenticated.

This is a very basic login screen but serves the purpose of illustrating how to use NuGet in your projects.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig15_HTML.jpg
Figure 2-15

Login form added

You can definitely roll your own solution when it comes to encryption. Another route to take is to check NuGet to see if there are any solutions available that you can use.

To add a NuGet package to your project, right-click the project in the Solution Explorer, and click Manage NuGet Packages from the context menu as seen in Figure 2-16.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig16_HTML.jpg
Figure 2-16

Manage NuGet Packages

From the NuGet Package Manager screen that is displayed, you can search for a NuGet package based on keywords you enter. As can be seen in Figure 2-17, I will be using a NuGet package called EncryptValidate that I created that provides encryption functionality.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig17_HTML.jpg
Figure 2-17

NuGet Package Manager

The NuGet Package Manager screen provides a lot of information about the package you are going to install. The current version number is displayed, license information, project URL, as well as the author and download count for the particular package.

The NuGet Package Manager also makes it easy for you to install previous versions of the NuGet package (Figure 2-18) if you find that the latest package does not work properly with your code.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig18_HTML.jpg
Figure 2-18

Installing previous versions

This allows you to easily roll back to a previous version should you need to. After installing the package, the NuGet Package Manager will indicate that this package has been installed as seen in Figure 2-19.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig19_HTML.jpg
Figure 2-19

NuGet Package Installed

Figure 2-20 shows the NuGet package in the Visual Studio references.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig20_HTML.jpg
Figure 2-20

References

With NuGet, everything you need to use the package is added to your project. Now that we have added the EncryptValidate package to our project, let’s start adding some code.
private bool ValidateLogin()
{
    var blnLogin = false;
    try
    {
        var password = txtPassword.Text;
        // This encrypted password would be read from a database
        var storedEncrPassw = ReadEncryptedValueFromDatabase;
        if (ValidateEncryptedData(password, storedEncrPassw))
        {
            blnLogin = true;
        }
    }
    catch (Exception ex)
    {
        _ = MessageBox.Show(ex.Message);
    }
    return blnLogin;
}
Listing 2-1

ValidateLogin method

The encrypted password is stored in the database. It is read in and stored in the storedEncrPassw variable. The clear-text password and the stored encrypted password are then validated. If validation succeeds, the user is logged in.

Remember, the code for this project is available on GitHub.

By adding a single NuGet package, we have added functionality to encrypt passwords, validate encrypted passwords, and encrypt and decrypt text using Rijndael, converting text to a SecureString object, reading the value from the SecureString object, and more. All this functionality has been added without having to write the logic ourselves.

This is the power that NuGet provides. It is definitely something you as a developer need to consider using if you do not already do so.

Hosting Your Own NuGet Feeds

Sometimes, you might need to create and share packages that are only available to a limited audience. Think of the developers inside your organization. Perhaps the company you work with does not allow the sharing of code with a public audience. Perhaps the code you want to share is really specific to your organization and not suitable for a public audience. Whatever the situation, NuGet supports private feeds in the following ways:
  • Local feed – On a network file share

  • NuGet.Server – On a local HTTP server

  • NuGet gallery – Hosted on an Internet server using the NuGet Gallery project, you can manage users and features to allow searching and exploring available packages similar to nuget.org.

There are also other NuGet hosting solutions that do support the creation of remote private feeds. Some of these are

For a full list of NuGet hosting products and for more information on creating your own NuGet feeds, have a look at the following link on Microsoft Docs: https://​docs.​microsoft.​com/​en-us/​nuget/​hosting-packages/​overview

Creating Project Templates

Sometimes developers create class libraries and code that they need to use over and over again across various new projects. What developers end up doing is copy and paste code into new class libraries. There is, however, an easier way to create projects that reuse code that you have previously written.

Enter Visual Studio project templates. These templates allow developers to speed up their development by including previously written code in new projects. Let’s assume that we have created a project called ProjectUtilities (as seen in Figure 2-21) that contains various helper methods.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig21_HTML.jpg
Figure 2-21

ProjectUtilities Project

This Class Library is something that we will need to use over and over in various projects. So I have decided to create a project template from it.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig22_HTML.jpg
Figure 2-22

Export Template

From the Project menu, click Export Template as seen in Figure 2-22.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig23_HTML.jpg
Figure 2-23

Export Template Wizard

The Export Template Wizard is displayed as seen in Figure 2-23. This allows you to specify which template you need to create. The options are to create a Project template or to create an Item template. A Project template is what we are after in this example, but you can also create an Item template. This will allow you to add the code via the Add New Item dialog box in Visual Studio.

For this example, however, we keep the Project template option selected and select the project to export from the drop-down list. This drop-down lists all the projects in my Visual Studio solution. Select the ProjectUtilities project, and click the Next button.

The next window displayed is where one can enter various template options (Figure 2-24). Here I can give the template a suitable name and description, specify the icon and preview images, and select to import the template into Visual Studio automatically. Click Finish to create the new project template.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig24_HTML.jpg
Figure 2-24

Add Template Options

The next time I create a new project in Visual Studio, I can search for my Custom project template (Figure 2-25) and have it available for me to select.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig25_HTML.jpg
Figure 2-25

Add a new project

Creating and Using Code Snippets

Code snippets in Visual Studio are small blocks of reusable code that you can insert into your code file by using a shortcut and tabbing twice or by using the right-click menu.

As an example (Figure 2-26), open a C# code file in Visual Studio and type the word try and hit the tab key twice.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig26_HTML.jpg
Figure 2-26

Inserting a try code snippet

This will insert a try-catch into your code file and allow you to enter the specific exception type being handled as seen highlighted in Figure 2-27.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig27_HTML.jpg
Figure 2-27

The inserted try-catch block

If you want to see all the available code snippets, you can open the Code Snippets Manager (Figure 2-28) by going to the Tools menu and clicking Code Snippets Manager.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig28_HTML.jpg
Figure 2-28

Code Snippets Manager

You can also hold down Ctrl+K, Ctrl+B to open the Code Snippets Manager window. Clicking each code snippet will display the description, shortcut, snippet type (expansion or surrounds with), and author. While some shortcuts are obvious (do, else, enum, for, and so on), others are not and might take some getting used to remembering to enter the shortcut and tabbing twice to insert the snippet.

If you can’t remember the shortcut, you can invoke the snippets by hitting Ctrl+K, Ctrl+X (as seen in Figure 2-29) while inside the code file you are editing. This will display a menu in place that will allow you to search for and select the specific code snippet you want to use.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig29_HTML.jpg
Figure 2-29

Ctrl+K, Ctrl+X to invoke a code snippet

You can also right-click and select Snippets and then Insert Snippet from the context menu. The last way that you can insert a code snippet is via the menu bar by going to Edit, IntelliSense and clicking Insert Snippet. Visual Studio also allows developers to create their own code snippets. Let’s have a look at that process next.

Creating Code Snippets

If there is one thing I wish, is that there was a nice interface baked into Visual Studio for creating and adding code snippets. Perhaps one day, but for now we have to do it the old-fashioned way.

This is through the use of an XML file. The basic snippet template XML looks as in Listing 2-2.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns:="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title></Title>
        </Header>
        <Snippet>
            <Code Language="">
                <![CDATA[]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
Listing 2-2

Basic Snippet Template

Let’s assume that we have created a Custom project template that includes a logging class in our helper classes.

Refer to the previous section regarding Creating Project Templates.

This logging class will always be added to all new projects going forward, and I have to include it in the catch block of every try. The code for the logging class is basically as in Listing 2-3.
public static class Logger
{
    public static void Log(string message)
    {
        // Perform some sort of logging
    }
}
Listing 2-3

Basic Logging Class

Inside my code, I would like to be able to automatically add the code to log the error every time I insert a try-catch. The code snippet (Listing 2-4) file I create must, therefore, import the namespace as well as expand or surround the required code. Replacement parameters have also been defined in the snippet file for the Exception type by surrounding the word to replace (namely, expression) with the $ characters.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns:="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>Try Catch Log</Title>
            <Author>Dirk Strauss</Author>
            <Description>Creates a try catch that includes logging.</Description>
            <Shortcut>tryl</Shortcut>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
                <SnippetType>SurroundsWith</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
              <Literal>
                 <ID>expression</ID>
                 <ToolTip>Exception type</ToolTip>
                 <Function>SimpleTypeName(global::System.Exception)</Function>
              </Literal>
            </Declarations>
             <Code Language="CSharp">
                <![CDATA[
                try
                {
                    $selected$
                }
                catch ($expression$ ex)
                {
                    Logger.Log(ex.Message);
                    $end$
                          throw;
                }
                ]]>
            </Code>
            <Imports>
                <Import>
                    <Namespace>ProjectUtilities</Namespace>
                </Import>
            </Imports>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
Listing 2-4

Custom Try-Catch Snippet

It is also worth noting that the code snippet might be XML, but the file extension must be .snippet for Visual Studio to be able to import it. If you refer back to Figure 2-28, you will notice an Import button on the Code Snippets Manager screen.

Click that button; browse for and import your newly created code snippet for the custom try-catch. You will notice that I have defined the shortcut as tryl for try-catch log.

This time, if you type the tryl shortcut into your code window, you will see that the description and title of the custom try-catch is displayed as seen in Figure 2-30.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig30_HTML.jpg
Figure 2-30

Custom try-catch to include logging

When you hit the tab key twice, the custom code snippet is inserted, and the required namespace, ProjectUtilities, which we created earlier as a project template, is imported along with the code snippet. This can be seen in Figure 2-31.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig31_HTML.jpg
Figure 2-31

Added try-catch including namespace

This new code snippet is now available in all your future projects. Your C# code snippets live in the Documents folder in C:Users[USERNAME]DocumentsVisual Studio 2019Code SnippetsVisual C#My Code Snippets.

The code snippet schema reference is available on Microsoft Docs at the following link: https://​docs.​microsoft.​com/​en-us/​visualstudio/​ide/​code-snippets-schema-reference?​view=​vs-2019

More often than not, you will be creating your own code snippets based off of an existing code snippet. This allows you to reuse functionality you know is working in the existing snippet and include it in your own.

Code snippets are definitely a very powerful productivity feature in Visual Studio.

Using Bookmarks and Code Shortcuts

At some point in your career, you will most likely be working on a very large code base. Do this for a while, and you will get bogged down with remembering where a specific bit of code is or where you need to go to get to a specific portion of logic.

Visual Studio can assist developers in bookmarking certain sections of code as well as adding shortcuts to other areas of code. Let’s have a look at what bookmarks and shortcuts are and when to use which.

Bookmarks

Let’s say that you are busy finishing up for the day, but just before you check in your code, you notice that there is some code that doesn’t look quite right. It is a method that has a single return statement and you know that you can use an expression body for methods.

You really don’t have the time to play around further because you have already passed the point that you needed to leave for home. So in order to not forget to have a closer look at this tomorrow, you decide to bookmark the method.

Place your cursor at the line of code you want to return to, and hold down Ctrl+K, Ctrl+K and Visual Studio will add a bookmark as seen in Figure 2-32.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig32_HTML.jpg
Figure 2-32

Bookmark in Visual Studio

The bookmark is added to the side of the code editor and is indicated by a single black bookmark icon.

In order to see all the bookmarks in your project, you can hold down Ctrl+K, Ctrl+W or go to the View menu item and select Other Windows and then click Bookmark window.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig33_HTML.jpg
Figure 2-33

Bookmarks window

The Bookmarks window is displayed as seen in Figure 2-33. From the toolbar in the Bookmarks window, you can group bookmarks in folders, navigate between bookmarks, navigate between bookmarks in the current folder, toggle a bookmark on the currently selected line in code, disable all bookmarks, and delete bookmarks.

There is however another feature not so obvious by looking at this Bookmarks window, and that is the ability to rename bookmarks. To rename a bookmark, click a selected bookmark, and you will see that the name (in this case “Bookmark4”) becomes editable.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig34_HTML.jpg
Figure 2-34

Renamed bookmark

Now you can rename your bookmark to something more relevant to what you need to remember as seen in Figure 2-34. Go ahead and add some more bookmarks to other random areas of code. Your Bookmarks window will end up looking rather full.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig35_HTML.jpg
Figure 2-35

Bookmarks collection

Now click the delete button on the Bookmarks toolbar. The bookmark is deleted without any confirmation from the user.

This is something I can sort of understand. Imagine how irritating it would be having to confirm every delete, especially when you want to remove only a subsection of bookmarks from your collection.

It is for this reason that I use bookmarks only as a short-term solution to remind me to go and perform some action in code or to refactor something I think needs refactoring.

For me, a bookmark is something I will come back to within the next day or so. Something I don’t want to put off doing. It is, therefore, a temporary placeholder to something I need to revisit.

But what if I wanted to go and add a more permanent pointer to some logic in code? This is where code shortcuts come in. Let’s have a look at this next.

Code Shortcuts

The ability to add code shortcuts in Visual Studio is more helpful when you need to quickly jump to a certain section of code regularly. To add a shortcut to a specific section of code in Visual Studio, you need to place your cursor on the line of code you need to revisit and type Ctrl+K, Ctrl+H.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig36_HTML.jpg
Figure 2-36

Code Shortcut Added Indicator

Visual Studio will then add the shortcut as seen in Figure 2-36. To view all the shortcuts added to your project, hold down Ctrl+, Ctrl+T or go to the View menu, and select Task List to open the Task List window as seen in Figure 2-37.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig37_HTML.jpg
Figure 2-37

The Task List

In some ways, I prefer the Task List more than using bookmarks because I can quickly add items to revisit by adding //TODO: in my code. With your Task List open, go to any place in your code, and add the following comment.
// TODO: Remember to do something here
Listing 2-5

TODO Comment

Now have a look at your Task List. You will notice that the TODO comment has been added to your Task List as seen in Figure 2-38.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig38_HTML.jpg
Figure 2-38

TODO comments in the Task List

This is a nice and quick method for adding reminders to your code so that you can easily refer to them and navigate to them by double-clicking the item in the Task List. You can, therefore, use the Task List to take you directly to the predefined location in code.

In Visual Studio, TODO is what we call a predefined token. Therefore, a comment in your code that uses a predefined token will appear in your Task List. The tokenized comment is made up of the following:
  • The comment marker, which is //

  • The predefined token (TODO in our example)

  • The rest of the comment

The code in Listing 2-5 is, therefore, a valid comment using a token and will appear in the Task List. Visual Studio includes the following default tokens:
  • HACK

  • TODO

  • UNDONE

  • UnresolvedMergeConflict

These are by no means case sensitive and will appear in your Task List if following the form in Listing 2-5. You can also add your own custom tokens. Let’s see how to do that next.

Adding Custom Tokens

I like the idea of TODO to add items to my Task List, but I would also like to add a custom token to add an entry in my Task List that is a nice to have feature. Something that is less restrictive than a TODO, because that implies that this action must be completed.

I do not want to have a bunch of TODO entries for items that are simply nice to have features. For this reason, I want to add a custom token called NOTE that is simply a reminder to look at something, if and when I have the time.

To add the custom token, go to the Tools menu, and click Options. Under Environment, select Task List as seen in Figure 2-39.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig39_HTML.jpg
Figure 2-39

Add Custom Tokens

In the Name text box, add the word NOTE and set the priority to Low. Then click the Add button. The custom token NOTE is added as can be seen in Figure 2-40.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig40_HTML.jpg
Figure 2-40

The Custom Token Added

Adding a NOTE to your code will pop up in your Task List as a low priority task as seen in Figure 2-41.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig41_HTML.jpg
Figure 2-41

Adding a NOTE token comment

Being able to add custom tokens in Visual Studio, as well as applying a priority to each, allows you to be very specific with comments that contain tokens. This way you can greatly increase the ease and efficiency of navigating through a large code base.

The Server Explorer

As the name suggests, the Server Explorer provides a quick and easy way of accessing servers. You can use it to test connections and view SQL Server databases or any databases that have the ADO.NET provider installed.

You can access the Server Explorer by holding down Ctrl+Alt+S or by going to the View menu and clicking Server Explorer.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig42_HTML.jpg
Figure 2-42

Server Explorer

As seen in Figure 2-42, the Server Explorer offers access to Event Logs, Message Queues, Performance Counters, and Services on my local machine (MSI). It also provides access to my Azure subscriptions.

I have a local instance of SQL Server installed, so now I can connect to this instance right from within Visual Studio by clicking Connect to Database.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig43_HTML.jpg
Figure 2-43

Choose Data Source

This will display a window allowing you to choose a data source as seen in Figure 2-43. You can connect to various types of data sources, but we are only interested in Microsoft SQL Server for now. Select that from the list and click Continue.

The next window (Figure 2-44) allows you to define your connection to the database. Here you need to specify the server name, the authentication type, and if SQL Server Authentication is selected, provide the username and password.

This will then allow you to select a database from the list to connect to. To check if the connection settings are correct, you can click the Test Connection button.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig44_HTML.jpg
Figure 2-44

Add Connection

After adding the database to your Server Explorer, you will see the instance added to your list from where you can expand the various nodes to view Tables, Views, Stored Procedures, etc., as seen in Figure 2-45.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig45_HTML.jpg
Figure 2-45

Database Added to Server Explorer

By double-clicking a table, Visual Studio will display the table designer for you along with a create table T-SQL statement as seen in Figure 2-46.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig46_HTML.jpg
Figure 2-46

Table Designer

From this window, you can easily update the table. The create table statement in Figure 2-46 is listed in Listing 2-6.
CREATE TABLE [dbo].[menu] (
    [itemName] VARCHAR (50)   NOT NULL,
    [category] VARCHAR (50)   NOT NULL,
    [price]    DECIMAL (5, 2) NULL,
    CONSTRAINT [PK_menu] PRIMARY KEY CLUSTERED ([itemName] ASC)
);
Listing 2-6

Create Table Statement

We can now modify the menu table by altering the T-SQL statement as follows (Listing 2-7).
CREATE TABLE [dbo].[menu] (
    [itemName] VARCHAR (50)   NOT NULL,
    [category] VARCHAR (50)   NOT NULL,
    [price]    DECIMAL (5, 2) NULL,
    [priceCategory]    VARCHAR (5) NULL,
    CONSTRAINT [PK_menu] PRIMARY KEY CLUSTERED ([itemName] ASC)
);
Listing 2-7

Modified Create Table Statement

I want to add a price category field to the table. When I modify the create table statement, I see the changes reflected in the table designer as seen in Figure 2-47.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig47_HTML.jpg
Figure 2-47

Table Design Updated

The changes have not been applied to my table yet. For this to update the table, I need to click the Update button.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig48_HTML.jpg
Figure 2-48

Preview Database Updates

This will now allow me to preview the database updates about to be applied as seen in Figure 2-48. If you do not want to let Visual Studio update the table, you can have it generate the script by clicking the Generate Script button. Alternatively, you can go ahead and click the Update Database button.

This will then start the process of updating the database table with the changes you made.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig49_HTML.jpg
Figure 2-49

Data Tools Operations

After the update is complete, you can see the results in the Data Tools Operations window as seen in Figure 2-49. From here, you can view the script as well as view the results.

Running SQL Queries

The Server Explorer also allows developers to run SQL queries, right from within Visual Studio. Go ahead and right-click a table (Figure 2-50), and click New Query from the context menu.

Take note that the context menu changes depending on what item you have right-clicked in the Server Explorer. When right-clicking a table, you will see items related to a SQL table. When right-clicking a View, you will see items specific to the View such as Show Results and Open View Definition. When right-clicking a Stored Procedure, the context menu will display the Execute command.

../images/487681_1_En_2_Chapter/487681_1_En_2_Fig50_HTML.jpg
Figure 2-50

Run a SQL Query

Copy the SQL query in Listing 2-8. You will obviously have had to create the table first using the CREATE statement in Listing 2-7.
SELECT
        itemName
        , category
        , price
        , priceCategory
FROM menu
Listing 2-8

SQL Select Statement

When you have pasted the SQL statement (Figure 2-51), execute it by clicking the run button, by holding down Ctrl+Shift+E or executing it with the debugger by holding down Alt+F5.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig51_HTML.jpg
Figure 2-51

Running a Select Statement

If you are used to pressing F5 in SQL Server Management Studio, you might find yourself starting the Visual Studio debugger instead of running the query. I simply find it easier to click the run button and avoid my muscle memory faux pas.

Adding an additional item to the table is easily done by running the INSERT statement in Listing 2-9.
INSERT INTO [dbo].[menu]
        ([itemName],[category],[price],[priceCategory])
        VALUES
        ('bread','breads',2.50,'baker')
Listing 2-9

Insert Statement

If we run the SELECT statement again, you will see that the entry has been added to the table as seen in Figure 2-52.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig52_HTML.jpg
Figure 2-52

New Item Inserted

From the results displayed in Figure 2-52, we can see that by adding the priceCategory column, we have a few NULL fields in the menu table. Let’s change that by running the SQL statement in Listing 2-10.
UPDATE menu
SET priceCategory = 'DELI'
WHERE category IN ('meats', 'salads', 'soups')
Listing 2-10

SQL Update Statement

When we look at the table data after the UPDATE statement (Figure 2-53), you will see that the table has been updated to display the correct priceCategory values for the items contained in the table.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig53_HTML.jpg
Figure 2-53

Table Updated

While running SQL statements isn’t mind-blowing, it is very convenient being able to do all this without ever leaving Visual Studio. The Server Explorer definitely offers much more functionality than illustrated in this chapter. Dig around it a bit more, and see what the Server Explorer can do for your productivity.

Visual Studio Windows

I have often maintained that developers get stuck in a rut when it comes to working with Visual Studio. They tend to stick to what they know and keep on doing things that way until the cows come home.

This isn’t necessarily a bad thing, but developers might miss out on some of the awesome tools and features available to them that Visual Studio provides right out of the box. In this section, I want to briefly discuss two of the items found under the View, Other Windows menu as seen in Figure 2-54.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig54_HTML.jpg
Figure 2-54

Other Windows in Visual Studio

Here are too many windows to discuss all in this chapter, but I will touch on two that I find very useful.

C# Interactive

How often have you wanted to test a small bit of code just to see if it works correctly? Well, with C# Interactive, you can do just that without having to debug your entire solution. Found toward the bottom of the View, Other Windows menu, C# Interactive is almost hidden. But gems usually are and you’re going to love using it if you don’t already.

Click C# Interactive, and paste the following code in Listing 2-11. After pasting the code into C# Interactive, hit the Enter key to run the code.
var numList = new List<int>() { 153, 114, 116, 213, 619, 18, 176, 317, 212, 510 };
var numResults = numList.Where(x => x > 315);
foreach(var num in numResults)
{
   Console.WriteLine(num);
}
Listing 2-11

Running a LINQ Query

The results are immediately displayed below the code you pasted. Your C# Interactive window should now look as in Figure 2-55.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig55_HTML.jpg
Figure 2-55

C# Interactive Code Results

C# Interactive is what we refer to as a REPL (Read-Eval-Print Loop). Being able to input expressions that are evaluated and results returned makes on the spot debugging possible in Visual Studio.

C# Interactive supports IntelliSense, so you get the same kind of editor experience as in Visual Studio. For a list of available keyboard shortcuts, REPL commands, and Script directives that C# Interactive supports, just type in #help and press the Enter key.

Code Metrics Results

The project that we have been using in this chapter is really not complex at all. It is really just to illustrate the concepts in this book. If you take a more complex project, one of the projects you have worked on at work, this next screen will look a lot different.

Code Metric Results (Figure 2-56) is a set of measurements that allow developers to gain a better insight into the code that they are producing.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig56_HTML.jpg
Figure 2-56

Code Metrics Results

The image in Figure 2-56 are the results for the ShipmentLocator application we have been using throughout this chapter. It’s not really complex at all, so the metrics might seem all fine.

Please note that when you first open the Code Metrics Results screen, it will be blank. You need to click the Calculate Code Metrics for Solution button in the top left corner of the window.

Looking at the same screen (Figure 2-57) for a more complex project (one of my old legacy projects), the metrics are quite different.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig57_HTML.jpg
Figure 2-57

Code Metrics Results on a large project

Each metric in the window refers to a specific software measurement that was performed. These are the code metrics that Visual Studio calculates:
  • Maintainability Index

  • Cyclomatic Complexity

  • Depth of Inheritance

  • Class Coupling

  • Lines of Code

The advantage of these metrics makes it possible for developers to understand what portions of code need to be worked on or more rigorously tested. It also allows developers to identify potential risks in their software. Ratings in this window are also color coded so that developers can quickly identify trouble spots.

Maintainability Index

This will be a value between 0 and 100 and represents how easy it is to maintain the code. The higher the value, the more maintainable your code is.

Cyclomatic Complexity

This metric measures the structure of your code and how complex it is. It uses the number of code paths it finds that flow through the program to calculate this score. A higher number indicates a complex control flow and is, therefore, harder to test and maintain. The numbers displayed in Figure 2-56 and Figure 2-57 are totaled for each project in the solution. Here it makes sense to expand the hierarchy and drill down to the individual methods to see where the problem areas lie.

Depth of Inheritance

As the name suggests, this metric measures the number of classes that inherit from each other. This goes all the way down to the base class. This means that a high number indicates a deep inheritance which is bad. This is because any changes to a base class have the potential to result in breaking changes further up in the derived classes. Here you will be wanting to see a lower score.

Class Coupling

Class Coupling basically measures how many classes a single class uses. Here, a high number is bad, and a low number is good. Class Coupling has been shown to accurately predict software failures. With a high coupling score, the maintenance and reusability of the class become really difficult because it depends on too many other types.

Lines of Code

The lines of code here are based on the count of the IL code. So this isn’t a true count of lines of code in the source file. Nevertheless, you will probably agree with me that a high count indicates that a lot is happening. Expanding the projects and viewing the code counts for individual methods will allow you to see which methods are trying to do too much. A high line count will indicate a method that is harder to maintain. Try to refactor these methods and simplify them.

Send Feedback

The Visual Studio team definitely takes feedback seriously. So much so that it drives much of what they do to improve Visual Studio.

If you are experiencing a problem in Visual Studio 2019, click the feedback button as seen in Figure 2-58.
../images/487681_1_En_2_Chapter/487681_1_En_2_Fig58_HTML.jpg
Figure 2-58

Send Feedback button

You can now report a problem or suggest a feature right from inside Visual Studio 2019.

As a developer, we should take the time to report issues we come across. This can be anything from crashes to slow performance or something else unexpected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.156.35