Tuesday, January 12, 2021

Visual Studio Code: .NET 5.0 Reusing the Current Browser Tab for Debugging

By default, each time a web service is run/debugged in Visual Studio Code, a new browser windows is opened.  Running the web service project Visual Studio Code: Creating a C#/WebApi Project with DotNet 5 three times launches (by default) a browser and opens three tabs (once per debug session):

For a Visual Studio Code web service project to not open a browser window each time the web service is debugged, the launch.json file under the .vscode folder needs to be modified. An example of the deafult launch.json is as follows:


To not open a browser window comment out the serverReadyAction attribute (lines 18-21).





Visual Studio Code: Disabling the Minimap

By default, when editing a file, Visual Studio code displays a minimap along the right side of the file being edited:


Visual Studio Code recently added the ability to hide the minimap via the View menu:


The Command Palette can also be used to toggle the minimap using ctrl-shift-P and enter the term minimap:


Appendix A: Visual Studio Code Minimap Documentation

The documentation for the minimap is found at Minimap. The documentation's explanation as to the purpose of the minimap is as follows:




Monday, January 11, 2021

Visual Studio Code: Fixing Error "Your connection is not private" (NET::ERR_CERT_AUTHORITY_INVALID)

 When debugging/running a web service or web application in Visual Studio Code or Visual Studio the following error will show up in the browser the first time an application is run immediately after the .NET 5 (or other) SDK is installed:


The text of the error is: 

Your connection is not private

Attackers might be trying to steal your information from localhost (for example, passwords, messages, or credit cards). Learn more

NET::ERR_CERT_AUTHORITY_INVALID

The error is caused because the certificates used during running/debugging provided by the .NET 5 SDK have not been trusted on the local host. The DotNet CLI provides a command-line for trusting these certificates:

dotnet dev-certs https --trust

The command above should be run from Visual Studio Code's Terminal window:


When the above command is invoked, the following dialog is displayed:


Click on Yes to trust the certificates. Restart the application being debugged/run in Visual Studio code and the error should disappear. 

Sunday, January 10, 2021

Visual Studio Code: Creating a C#/WebApi Project with .Net 5

The DotNet CLI worked for .NET Core and it works for .NET 5. The steps to create a C# web service (WebApi project) are as follows once .NET 5.0 is installed:

From a Visual Studio Code Terminal window invoke a command such as the following which creates a project named Learn: 

dotnet new webapi --name Learn

An example of invoking the following command from from Visual Studio Code's Terminal is as follows:


The dotnet new command created a folder, C:\Blog\DotNet5\Learn. Open that folder from Visual Studio Code (File menu | Open Folder):


Once the folder is open, Visual Studio Code will prompt to create the assets required to build and debug the project:

Select Yes from the dialog.

Visual Studio Code's Explorer shows the files contained in the folder:


The Learn.csproj file is the project file. Double clicking on the file in Explorer displays Learn.csproj in an edit window:


The project file, Learn.csproj, shows that the project type is a WebApi project of the .NET 5/.Net Core variety Microsoft.NET.Sdk.Web. The TargetFramework is net5.0 and the PackakageReferemce elements are NuGet packages used by the project.

The program.cs file is the entry point to the web service, meaning the code initially runs when the service is launched:


The entry point configures the web service and invokes the startup class (see Line 17). The startup class is aptly named Startup and is defined in Startup.cs. The purpose of the Startup class is to setup configuration information and invoke middleware used by the service.

The project contains a sample model, WeatherForecast.cs:


The project also contains a sample controller, WeatherForecast.cs, inside the project folder's Controller's folder:


The controller specifies the routes to be used by the service.

The project folder contains project-level configuration files:

The appsettings.json file contains project-level application settings and appsettings.Development.json contains project-level application settings which are only invoked when the service runs in the development environment. Both of the aforementioned applications settings files initial contain settings related to logging and the allowed hosts. A mature project would contain a application settings file per-environment (production, stage, qa, integration, etc.).

The .vscode folder contains files specific to how the code behaves when run under Visual Studio Code. The .vscode folder contains the files the launch.json and task.json. The task.json file contains tasks including how to build the project using Visual Studio Code:


The command to build in Visual Studio Code is ctrl-shift-b.

The launch.json file under the .vscode folder contains launch settings for when the service is run by Visual Studio Code:


Line 13 of launch.json (above) shows that the DLL invoked on launch is Learn.dll. The settings at Line 23 indicates that when running under Visual Studio Code, the environment is considered to be Development which means that the application settings in appsettings.Development.json takes precedence over appsettings.json.

The Properties folder contains a launchSettings.json file which pertains to when the service is launched outside of Visual Studio Code:


Line 25 shows the HTTPS and HTTP URL used when the web service is launched. The environment, Development, is specified as Line 27. When run under Visual Studio Code this value is ignored in deference to the setting in .vscode\launch.json.

To run/debug the code, from Visual Studio Code, click on the Debug Hub:


From the Debug Hub click on the Start Debugging button:


When the Start Debugging button is clicked (above) a browser tab such as the following will be lauched:


The content in the above browser instance is not overly useful. To display something with meaning, change the URL to: https://localhost:5001/swagger

The above change to the URL displays the following:


To glean a glimpse of what Swagger can provided check out the documentation What Is OpenAPI?:

Appendix A: Dotnet New

The documentation for the DotNet CLI's new command is found at dotnet new. The available project templates described in the documentation are as follows:






Saturday, January 9, 2021

Visual Studio Code: DotNet CLI and the Terminal Window for the Color Blind

Visual Studio Code's Terminal window has numerous uses including invoking the DotNet CLI such as the following which creates a new webapi project: 


For those with limited color vision, the above example is unreadable. Visual Studio Code's settings file can be modified to make the Terminal windows readable for people who are color blind. 

The Visual Studio Code settings file, settings.json (see User and Workspace Settings) which, according to the documentation, is found at:

An example settings.json is as follows:


The following settings.json changes all colors to white thus allowing those of us with limited color vision to see the Terminal window (see code demarcated in boldface)

{
    "terminal.integrated.rendererType": "dom",
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "diffEditor.ignoreTrimWhitespace": true, 
    "workbench.colorCustomizations": {
        "terminal.background":"#1D2021",
        "terminal.foreground":"#FFFFFF",
        "terminalCursor.background":"#FFFFFF",
        "terminalCursor.foreground":"#FFFFFF",
        "terminal.ansiBlack":"#FFFFFF",
        "terminal.ansiBlue":"#FFFFFF",
        "terminal.ansiCyan":"#FFFFFF",
        "terminal.ansiGreen":"#FFFFFF",
        "terminal.ansiMagenta":"#FFFFFF",
        "terminal.ansiRed":"#FFFFFF",
        "terminal.ansiWhite":"#FFFFFF",
        "terminal.ansiYellow":"#FFFFFF",
        "terminal.ansiBrightBlack":"#FFFFFF",
        "terminal.ansiBrightBlue":"#FFFFFF",
        "terminal.ansiBrightCyan":"#FFFFFF",
        "terminal.ansiBrightGreen":"#FFFFFF",
        "terminal.ansiBrightMagenta":"#FFFFFF",
        "terminal.ansiBrightRed":"#FFFFFF",
        "terminal.ansiBrightWhite":"#FFFFFF",
        "terminal.ansiBrightYellow":"#FFFFFF"
      }    
}

The above settings set all colors to white safe for the background. This makes Visual Studio Code Terminal window legible:







Monday, January 4, 2021

PowerShell: Modules (Convert PSUnit.ps1 to a Module)

This post demonstrates how to create a PowerShell module (PSUnit.psm1) and consume/test the functions exported by the module (PSUnitTest.ps1).  The source code for the scripts presented here is contained in a comprehensive post PowerShell: A Practical Example (Logging and Testing). Modules can be compiled code (DLL's) or can be composed PowerShell. For this post, the modules is implemented in using PowerShell and therefore uses the standard PowerShell module file extension psm1. 

The basic unit testing framework was originally presented as script, PSUnit.ps1, in post PowerShell: Unit Test Functions and Accessing the Invoking Code's Line Number. The PSUnit.ps1 script was composed of  a class, PSUnit, and it corresponding functions that support unit tests (AreEqual, IsTrue, etc.). The script also contained functions whose sole purpose was to test the unit test framework and test the PSUnit class. The PSUnit class and unit test functions were used to populate the module, PSUnit.psm1. The functions designed to test unit test framework are contained in PSUnitTest.ps1 which consumes the module PSUnit.psm1.

The PSUnit.psm1 module contains the class PSUnit which implements the following non-hidden (PowerShell's equivalent to public) methods

  • IsFalse: throws an exception if the value under test is not $false 
  • IsTrue: throws an exception if the value under test is not $true
  • AreEqual (comparing objects): throws an exception if the two values under validation is not equal
  • AreEqual (comparing double): throws an exception if the two values under validation is not equal based off of a specified difference tolerance (see PowerShell: Unit Tests Compare Doubles for Equality).
  • AreEqualCollection: throws an exception if the two collections under validation is not equal (see PowerShell: Interfaces). Each element in the collection is comparted individually.
The PSUnit overloaded PSUnit methods AreEqual was discussed in PowerShell: Constructor and Method Overloading. The PSUnit class is not exported from the PSUnit.ps1 module. A set of wrapper functions are exported from the PSUnit.psm1 module. These wrapper functions  pass the invoking script filename and invoking line number to methods of the PSUnit class (see PowerShell: Unit Test Functions and Accessing the Invoking Code's Line Number) as $MyInvocation.ScriptName and $MyInvocation.ScriptLineNumber do not return values when invoked by the methods of a class. The functions exported by the PSUnit.psm1 module are
  • IsFalse: wraps method PSUnit.IsFalse
  • IsTrue: wraps method PSUnit.IsTrue
  • AreEqual: wraps method PSUnit.AreEqual (object parameter type overload)
  • AreEqualDouble: wraps method PSUnit.AreEqual (double parameter type overload)
  • AreEqualCollection: wraps method PSUnit.AreEqualCollection

Exporting Functions

The PSUnit.psm1 module file uses the Export-ModuleMember cmdlet to export functions (see lines 242-247):



The Export-ModuleMember cmdlet is reviewed in Appendix A: Export-ModuleMember.

Importing Functions

The PSUnitTest.ps1 script file imports the PSUnit.psm1 module using the Import-Module cmdlet (see line 1):


The Import-Module cmdlet is reviewed in Appendix B: Import-Module.

Appendix A: Export-ModuleMember

Microsoft documentation for the cmdlet Export-ModuleMember can be found at Export-ModuleMember. The description given for Export-ModuleMember in the documentation is as follows:

Appendix B: Import-Module

Microsoft documentation for the cmdlet Import-Module can be found at Import-Module. The description given for Import-Module in the documentation is as follows:



Sunday, January 3, 2021

PowerShell: Interfaces

A rudimentary unit test class, PSUnit, was introduced in PowerShell: Unit Test Functions and Accessing the Invoking Code's Line Number. This current post extends the PSUnit class to support the testing of collections and arrays by making use of an well known interface, ICollection. All the code associated with the PSUnit class is found in the post PowerShell: A Practical Example (Logging and Testing).

It would not be feasible to implement an AreEqual class for every collection exposed by .NET and therefore accessible to PowerShell. Examples of the plethora of collection available include:

  • Namespace System.Collections 
    • Array
    • Queue
    • Stack and 
  • Namespace System.Collections.Generic 
    • LinkedList<T>
    • List<T>
    • Queue<T> 

.NET collections are derived from a set of common interfaces including System.Collection.ICollection. Interfaces define a set of methods and properties that class is required to implement. A practical approach to testing collections is to compare the values in the collection but using interfaces. This means that an AreEqual method that compares using ICollection can test any class that implements ICollection. The ICollection interface is documented at ICollection Interface. The documentation demonstrating the classes that implement the ICollection Interface include, but are not limited to, the following:


The above list of classes is just a subset of the classes derived from System.Collection.ICollection,

The documentation for ICollection shows the properties and methods required to be implemented by classes derived from this interface:


The ICollection interface inherits from the IEnumerable interface as the documentation demonstrates:


This means that any class that implement ICollection and its properties (Count, IsReadOnly) and methods (Add, Clear, Contains, CopyTo, and Remove) must also implement the properties and methods of IEnumerable (method GetEnumerator).

The PSUnit methods used to compare collections are shown below. The AreEqualCollection method of the PSUnit class is implemented at lines 147 to 187 in the code snippets below:



 

The first two parameters of AreEqualCollection are of type ICollection which means the method can be used to test arrays, lists, and dozens of collections types. Line 161 above shows the AreEqualCollection  method using the Count property of interface ICollection. Lines 174 to 176 show calling GetEnumerator from ICollection's base-interface, IEnumerable. The GetEnumerator method returns an IEnumerator instance which in lines 179-186 iterates through the the collection values to be compared.

The function AreEqualCollection wraps the AreEqualCollection method of the PSUnit class. The AreEqualCollection function is  shown below:


The code to test the AreEqualCollection function is as follows:



As stated previously, all code from this post can be found in PowerShell: A Practical Example (Logging and Testing.