Once there was a time where Microsoft and Linux were enemies and who was developing in Windows didn’t develop for Linux and vice-versa. Time has passed and things have changed. And how they have changed!

Multi-platform development has evolved, Microsoft released .NET open source, and you can run it both on Linux and Mac (besides Windows, of course). You can use VS Code to develop your code in any of these platforms, and VS Code isn’t restricted to .NET Languages: you can develop in Python, Perl or even Clipper/Harbour, Cobol or Fortran. What a change!

Besides that, you can run a Linux distro directly in Windows, with no need of any VM, dual boot or Live CD. The key for that is WSL, the Windows Subsystem for Linux, that allows you to run a full Linux environment, including any Linux application without modification (you can even run Linux graphical apps with WSLg, that’s in test – the image below shows GIMP running on Windows)

And, just to make sure, it’s not an emulation of Linux. You are running the full distro directly on Windows. WSL uses a translation layer between Linux and Windows, to translate the calls between both OSs and WSL2 uses a Linux kernel for its magic. You can compare both versions of WSL here.

To develop in Linux, the first thing is to get Windows Terminal. This is the successor of the old Windows command line prompt and offers many improvements: customization, tabbed interface and it allows you to use multiple shell types: Windows command, Powershell, Linux prompt or even an Azure Cloud Shell. If you are using Windows 11, you already have it, as it’s installed by default. If you are still using Windows 10, you can get it from the Microsoft Store.

Once you have Windows Terminal installed, you must install WSL. Just open a command prompt window and type

wsl --install

This will install WSL in your machine. If that doesn’t work, you will have to install it manually, using the installation steps listed here.

With WSL installed, you need to install your preferred Linux distro. You can get it from the Microsoft Store:

Or you can install it directly from the command prompt. wsl --list lists all the available distros in your machine (you can install and use many distros) and wsl --list --online lists the available distros online:

To install an online distro, you must use

wsl --install -d <Distro>

If the distro isn’t available online or in the store, you still can install it, by getting the appx packages an manually installing it, as described here. One other way is to check if there is an alternate way to install it in WSL. For example, to install Linux Mint, you can go to the LinuxMintWSL Github and download the installer for it.

When you have WLS and the distros installed in your machine, you can click on the down arrow in the Terminal title bar and it will show them in the list, so you can select and open a command prompt for that distro:

The next step is to install dotnet 6.0. To do that, you should follow the instructions for your distro in

For Linux Mint (based on Ubuntu), you should run these commands on the bash prompt:

wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb

sudo apt-get update; \
  sudo apt-get install -y apt-transport-https && \
  sudo apt-get update && \
  sudo apt-get install -y dotnet-sdk-6.0

Once installed, you can get the installed version with

dotnet --version

Now, you can create and run a dotnet program in Linux. To show the available app types to create, you can run

dotnet new

This will list the common templates for a new app. To list all templates, you should use

dotnet new --list

We can create a new console app using this command:

dotnet new console -o simple-console

This command will create a new console app in the simple-console folder. We can change to this folder with cd simple-console and run the program with

dotnet run

This is already great but, unless you are already a VI or Emacs guru (which I am not 😃), you will have some trouble to modify it. I personally, think that the best way to modify a Linux program in WSL is to use VSCode. By typing code . in the command prompt, VS Code server will be downloaded and installed automatically and VSCode will open in your desktop

In this case, you won’t have VS Code for Linux running. When you are using VS Code from WSL, something different happens: VS Code will be split into two parts, a server (which runs on Linux) and a client (that runs on Windows). You will be editing the files on Windows, but saving them in Linux. You can see in VS Code status bar, at the bottom WSL: Mint, indicating that we are editing files in WSL. If you open a terminal in VS Code with Ctrl+`, you will see that it’s a bash prompt and not a command line or a Powershell prompt.

We can edit program.cs to show the OS version with:

Console.WriteLine($@"Hello World! 
Operating System: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}");

When we save and run the program we will get

This is still great, but I doubt that’s what you want to do when your are developing a Linux app. Many times, we’ll want to develop a web api to serve our data. For that, we must change to the parent folder and create a new app with

dotnet new webapi -o webapi

If you change to the webapi folder and run it with dotnet run, you will see the endpoints for the API:

In our case, if we open a browser window and type

https://localhost:7219/swagger

We will see the swagger interface for our api:

We can test it and see that it works fine:

But we can also use the curl command to get the data. In the bash prompt, we can type

curl -X 'GET' \
  'https://localhost:7219/WeatherForecast' \
  -H 'accept: text/plain'

to get the api data (I got this command line from the swagget test window). If you do that, you will see a certificate error. We didn’t set the certificate for the web site, and we can bypass that with the -k flag:

curl -k -X 'GET' \
  'https://localhost:7219/WeatherForecast' \
  -H 'accept: text/plain'

As you can see, we are getting the json data for the weather forecast sample. You can still consume the api from our console app. All we have to do is change the program.cs file to

using System.Text.Json;

var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback =
              (message, cert, chain, errors) => 
              { return true; };
using var client = new HttpClient(handler);
var json = await client.GetStringAsync("https://localhost:7219/weatherforecast");
var forecasts = JsonSerializer.Deserialize<List<WeatherForecast>>(json);
if (forecasts == null)
    return;
foreach (var forecast in forecasts)
    Console.WriteLine($"{forecast.date:dd/MM/yyyy}  {forecast.temperatureC}  {forecast.summary}");

public class WeatherForecast
{
    public DateTime date { get; set; }
    public int temperatureC { get; set; }
    public int temperatureF => 32 + (int)(temperatureC / 0.5556);
    public string? summary { get; set; }
} 

If you run the program, you will see something like this:

We are consuming the API from our console program in Linux, but we are running .NET, we can run the same program in Windows. One nice thing in WSL is that we can run Windows apps from Linux. If you type

explorer.exe .

It will open Windows Explorer with the current path open. If you copy the address in the address bar, you will see:

\\wsl.localhost\Mint\home\bruno\LinuxProg\simple-console

As you can see, the Linux folder is considered a new network. We can map the drive in Windows to use it, with a command like this one:

net use y: \\wsl.localhost\Mint

If you open a command prompt and type this command, you will have the y: drive available to use. You can then change to the program folder and type dotnet run to run the same program in Windows. If you do that, you will see that we can run the same program we’ve created in Linux in the Windows command prompt and consume the API that is still running in Linux.

As you can see, with .NET you can run the same program in Linux or in Windows and you can interact with the APIs that are running in Linux. You will be using the tools that you still know. You can even access one file system from the other seamlessly (the Windows file system is mounted in /mnt/c/ in Linux). You will be using the same C# language that you know and, most of the time, you don’t even need to know Linux APIs – .NET will take care of that for you.

The full code of this article will be in https://github.com/bsonnino/LinuxProg

Visual Studio Code is a free, multi-platform IDE and has multiple features, like multi-language support, syntax, highlighting, Git integration, among others. It’s open source and can be downloaded here.

One thing that contributes to its success is the fact that anyone can develop an extension for it and add new features to it. In fact, there are thousands of different extensions and, most it’s almost sure that, if you are searching something to do with it, there is an available extension to do it: themes, formatters, highlighters, code editors, or even an integrated interface to work with your favorite tool. You just have to open the extension manager, search what you want and install it.

Although Visual Studio Code has the same name of its older brother, it’s an entirely different code base: while Visual Studio is a .NET application, Windows-only (there is Visual Studio for Mac, based on MonoDevelop and Xamarin Studio, which is another code base), Visual Studio Code is based on the Monaco Editor, a code editor for the web, written in Typescript and it’s a multi-platform Electron app.

The extensions for VS Code are completely different from the Visual Studio ones: they are written in TypeScript (or JavaScript) and run only in VS Code, you cannot install them in Visual Studio.

To develop an extension to VS Code, you must have Node.js and Git installed and install Yeoman and the VS Code Extension Generator:

npm install -g yo generator-code

Then, we can create our extension with

yo code

The code generator will ask questions to direct you to generate the correct extension:

You can choose:

? What type of extension do you want to create? New Extension (TypeScript)
? What's the name of your extension? SortLines
? What's the identifier of your extension? sortlines
? What's the description of your extension? Sorts Selected Lines
? Initialize a git repository? Yes
? Bundle the source code with webpack? No
? Which package manager to use? npm

The last question allows you to open the new extension with VS Code:

You can press F5 to compile the extension and open a new instance of VS Code, where you can type Shift+Ctrl+P and type Hello World and the extension will show a message:

Two files are important in the extension: package.json and src\extension.ts. Package.json is the extension manifest, where you will say how your extension will be presented to the world: its name, which commands it implements and information for the marketplace: icon, license, colors, etc. Our extension has this information:

"name": "sortlines",
"displayName": "SortLines",
"description": "Sorts Selected Lines",
"version": "0.0.1",
"engines": {
  "vscode": "^1.64.0"
},
"categories": [
  "Other"
],
"activationEvents": [
  "onCommand:sortlines.helloWorld"
],
"main": "./out/extension.js",
"contributes": {
  "commands": [
    {
      "command": "sortlines.helloWorld",
      "title": "Hello World"
    }
  ]
},

You can recognize the name, displayName and description from your answers when you created the extension. The categories property shows the categories in which your extension fits. In our case, we will stay with Other.

The activationEvents property shows how the extension will be activated. In our case, it will be with the command sortlines.helloWorld. If we were creating a different extension, like an extension for a HTML parser, we could use the onLanguage event.

The main property indicates the entry point for your extension. As we are using TypeScript and it will be transpiled to JavaScript, we are indicating the js file in the out directory. The contributes property indicates where the extension will contribute with VS Code. Our extension will add a command in the command palette, but if the extension would add a new language support to VS Code, we could use the languages property.

The command will have the command identifier and the command title, that will appear in the command palette.

The main code is at src\extension.ts, where we will program what our extension will do. Its basic structure is this:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "sortlines" is now active!');

  // The command has been defined in the package.json file
  // Now provide the implementation of the command with registerCommand
  // The commandId parameter must match the command field in package.json
  let disposable = vscode.commands.registerCommand('sortlines.helloWorld', () => {
    // The code you place here will be executed every time your command is executed
    // Display a message box to the user
    vscode.window.showInformationMessage('Hello World from SortLines!');
  });

  context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {}

It declares two methods, activate, called when the extension is being activated and deactivate, called when the extension is deactivated, You use this method when there is some cleanup to be done. If there is no cleanup necessary, you can remove this method.

Let’s start changing the extension  for our needs. Initially, let’s change the package.json file to set our new title and add the commands we need:

"activationEvents": [
    "onCommand:sortlines.sortDescending",
    "onCommand:sortlines.sortAscending"
],
"main": "./out/extension.js",
"contributes": {
    "commands": [{
            "command": "sortlines.sortDescending",
            "title": "Sort Lines: Sort Descending"
        },
        {
            "command": "sortlines.sortAscending",
            "title": "Sort Lines: Sort Ascending"
        }
    ]
},

We are defining two commands: sortDescending and sortAscending. Now we must declare them in the code:

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "sortlines" is now active!');

  // The command has been defined in the package.json file
  // Now provide the implementation of the command with registerCommand
  // The commandId parameter must match the command field in package.json
  registerCommand(context, 'sortlines.sortDescending', () => {
    vscode.window.showInformationMessage('You are sorting the lines descending!');
  });
  registerCommand(context, 'sortlines.sortAscending', () => {
    vscode.window.showInformationMessage('You are sorting the lines ascending!');
  });
}

function registerCommand(context: vscode.ExtensionContext, command: string , func : () => void) {
  const disposable = vscode.commands.registerCommand(command, func);

  context.subscriptions.push(disposable);
}

I have refactored the code and created a new function, registerCommand, that will register the command and the callback function that will be invoked when the command is invoked. For now, we will only show the information messages. If you run the extension and open the command palette in the new instance of VS Code, you will see something like:

Selecting one of the options will show the information message. Now, let’s create the code to sort the selected lines in the editor:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  registerCommand(context, 'sortlines.sortDescending', () => sortSelection(true));
  registerCommand(context, 'sortlines.sortAscending', () => sortSelection(false));
}

function sortSelection(isDescending: boolean) {
  //get the active text editor
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    return;
  }
  //get the selection start and end
  const selection = editor.selection;
  const start = selection.start;
  const end = selection.end;
  // the new selection will extend 
  // from start of the first selected line 
  // to the end of the last selected line
  const newSelection = new vscode.Selection(start.line, 0, end.line + 1, 0);
  // get the selected text
  const text = editor.document.getText(newSelection);
  // split the text into lines
  const lines = text.split('\r\n');
  // sort the lines
  lines.sort((a, b) => isDescending ? b.localeCompare(a) : a.localeCompare(b));
  // replace the text with the sorted lines
  editor.edit((editBuilder) => {
    editBuilder.replace(newSelection, lines.join('\n'));
  });
  // set the new selection
  editor.selection = newSelection;
}

function registerCommand(context: vscode.ExtensionContext, command: string, func: () => void) {
  const disposable = vscode.commands.registerCommand(command, func);
  context.subscriptions.push(disposable);
}

For that, we will use the VS Code Api. We will create a sortSelection function, that will get the current selection, extend it to get the full first and last lines, sort them and replace the text with the sorted lines. The first step is to get the active editor with window.activeTextEditor, then get the current selection and extend it from the first character of the first selected line to the first character of the line just after the last selected line. Then, we sort the lines and replace the selected lines with the sorted lines and set the new selection.

When you run this extension and select some lines in your editor (the sample code has a list of artists obtained from the Chinook database, so you can try it), if you press Shift+Ctrl+P and select the sort, your selected lines will be sorted:

You can see that it works fine, except for one small glitch: if you sort the lines in the ascending order (that doesn’t happen in descending order), a blank line will be inserted in the first line of the selection, and that’s not what we want. That gives us the opportunity of testing another feature of the development of an extension for VS Code: debugging. Let’s debug the extension and check what’s happening:

We can set a break point in the line where the lines will be sorted, select some lines of text in the debugged editor and select the sort ascending. The debugger will stop in that line and we can see what’s happening, by analyzing the lines variable:

There is an extra line in the lines variable due to the last line, that will be sorted and will come first in the selection. And why that doesn’t happen in the descending order ? The empty line will come last and it will add only the last new line character, which will separate the last line of the selection and the next line, not selected.

That’s an easy fix: we can use the trim method to remove the trailing newline and the last line won’t be created when splitting the text:

const lines = text.trim().split('\r\n');

Now, we can run the extension and see that things work fine. There is one last thing to do here: add two keybindings to our extension: we will use Ctrl+K Ctrl+A for the sort ascending and Ctrl+K Ctrl+D for sort descending. For that, we will go to the Contributes section in the package.json file:

"contributes": {
    "commands": [{
            "command": "sortlines.sortDescending",
            "title": "Sort Lines: Sort Descending"
        },
        {
            "command": "sortlines.sortAscending",
            "title": "Sort Lines: Sort Ascending"
        }
    ],
    "keybindings": [{
            "command": "sortlines.sortDescending",
            "key": "ctrl+K ctrl+D",
            "when": "editorHasSelection"
        },
        {
            "command": "sortlines.sortAscending",
            "key": "ctrl+K ctrl+A",
            "when": "editorHasSelection"
        }
    ]
},

We set the command, the keybinding and when the command will be enabled (in this case, we will only enable the keybinding when there is selected text in the editor. Now, if you run the extension, select some text and press Ctrl+K Ctrl+D or Ctrl+K Ctrl+A, you will have the lines sorted.

Our extension is ready and the last step is to install it in VS Code (you can also upload it to the Marketplace, so it will be available for everyone). For that, you need to install the vsce tool. This tool allows you to package the extension, creating a VSIX file that can be installed locally or shared with other users, or publish the extension to the marketplace, so anyone can use it. You can install the tool with

npm install -g vsce

Once installed, you can use the publish or package commands to do what you want with the extension. For now, we’ll just package our extension, so you need to open a terminal window (you can do it in VS Code with Ctrl+`), change to your extension folder and type

vsce package

When you do that, you get an error:

You must edit your readme file to show what your extension will do. This is a markdown file, where you will put the features of your extension.

Once you have edited your readme file, you can package your extension and a VSIX file will be created. You can then go to the Extensions tab, select the “…” icon and select “Install from VSIX”. You’ll have the extension installed in your VS Code. You can distribute the extension to other members of your team by sharing the VSIX file. If you want to publish your extension, you can do it by using the publish command.

As you can see, creating an extension for VS Code is relatively easy, and that’s why there are so many extensions for it

All the source code for this extension is at https://github.com/bsonnino/VSCodeExtension