[20th anniversary of .NET] Best of C# : null operators

In this series, I’d like to share with you my best experiences with .NET / C# and the best evolutions the .NET team brings us over the time.

Today I’d like to talk about null operators 🙂 C# provides 3 operatrs to make it easier to with with nulls :

  1. Null conditional operator
  2. Null coalescing operator
  3. Null coalescing assignment (new in C# 8)

You can find more details about these operators in this great book => Amazon.fr – C# 10 in a Nutshell: The Definitive Reference – Albahari, Joseph – Livres

Null-conditional operator

The ?. operator is also called the Elvis operator and as originally introduced in C# 6. It allows you to call methods and access members like the . operator except that if the left operand is null, the expression is evaluate to null without throwing the killer exception ‘NullReferenceException‘.

string s = null;
string sUpper = sb?.ToUpper(); // sUpper is null

The only condition is that the final expression/assignment is capable of accepting a null (exit all value type) :

string s = null;
int lengthS = s?.Length; // Won't compile

Then use a Nullable :

string s = null;
int? lengthS = s?.Length; // Ok

Null-coalescing operator

The very useful ?? operator tells to return the value of the left operand if it’s not null, else return the specify value (right operand – example : default value)

string s = null;
string sDefault = s ?? "My default value"; // sDefault is "My default value"

Another good use of this operator is to check an assignment and rise an exception if null (example in ASP.NET controller or anywhere else) :

_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));

Null-coalescing assignment (C# 8)

The ??= operator assigns a variable only if it’s not null. So it’s a sugar syntax to replace this :

if (s != null) s = "Hello world";

with this :

s ??= "Hello world";

Add data attributes in Razor view with HTML helper method

With HTML 5 and JS frameworks heavily using data attributes within HTML tags, Razor views could cause you a headache without this little tip for attributes.

For example Data attributes have a syntax like « data-* ». If you add the hyphen within the name of an attribute in your anonymous class, Razor engine will interprets it simply as a minus sign … and won’t compile !

To add a Data attribute (or any other attribute with a hyphen within the name) within an HTML helper, you should replace the hyphen with an underscore. Hence, Razor engine will understand this and converts it to a hyphen in the HTML output.

@Html.DropDownList("Country", ViewData["Countries"] as SelectList, new { @class = "selectpicker", data_style = "btn-form-control" })

The HTML output will be:

<select id=”Country” name=”Country” class="selectpicker" data-style=”btn-form-control” />

Migrer vos applications vers .NET 5 avec l’assistant de migration (partie 1)

Même si toutes ne savent pas comment, les sociétés qui développent des logiciels souhaitent suivre le rythme effréné des montées de version, que ce soit des OS, des frameworks ou des bibliothèques. L’objectif est de ne pas être larguer, de pouvoir parfois gagner en performances, résoudre quelques problèmes de sécurité du framework ou encore permettre d’utiliser des technologies plus modernes (HTTP 2, etc) lors de ces passages.

Pour que les équipes de développement, l’objectif sera surtout de suivre les évolutions, d’identifier les breaking change, de refactoriser le code et également de garder la motivation de maintenir, ce qui deviendra quoiqu’on en veuille : ‘une vieille application à maintenir’.

Pour la société, l’objectif sera surtout de minimiser le coût de cette montée de version, qui si elle n’apporte pas de valeur ajoutée pour les utilisateurs (hormis de meilleurs performances et une sécurité parfois renforcé, concernant le framework en lui-même aka cela n’améliorera pas votre code dans ce domaine par magie) permet d’avoir sur le marché des ressources plus à même d’intervenir sur des technologies récentes qu’anciennes.

MAIS … la stratégie est souvent de faire un POC de mise à niveau d’un projet ‘pas trop gros’, et de se dire ‘voici une application A’, on essaye, et si ça ne coûte pas trop cher on fera l’application B, C, etc. Le biais dans lequel l’entreprise risque de tomber est qu’elle pensera que calculer le temps d’upgrade d’un premier projet, sur lequel l’équipe essuie tous les plâtres de la migration, pourra servir de référence de charges/coûts pour les suivantes. C’est du bon sens … mais c’est ce qui se passe tous les jours, dans d’autres domaines dans les sociétés …

En résumé, la migration d’un projet vers .NET Core 5 prendra beaucoup du temps et la décision sera de ne pas migrer les projets amenant une montagne de ‘vieilles applications à maintenir’ à être maintenu par des personnes dont la motivations égalera celle d’un paresseux au repos. Mais tada … Microsoft à créer l’upgrade assistant pour vous afin de vous aider au maximum à pouvoir évaluer la migration et vous assister dans cette tâche, surtout sur les parties simples et fastidieuses d’une migration de code. Mais attention, cet outil est votre assistant et le magicien c’est vous, pas lui !

Installation

L’assistant de migration est un outil dotnet (dotnet tool) qu’il suffit d’installer de cette manière :

image

Troubleshooting

Erreur “Impossible de charger l’index de service pour la source “/ “Unable to load the service index for source”

Cette erreur arrive lorsque vous avez déclaré un source Nuget dans votre configuration Nuget dont l’outil n’arrive pas à accéder (mauvaise URL, credentials outdated, etc).

image

Dans ce cas, rien de plus simple vous avez deux options :

1. Utilisez l’argument --ignore-failed-sources dans la ligne de commande

2. Supprimer la source dans votre fichier de configuration Nuget qui se trouve dans :

image

Visual Studio Core for PowerShell 7

With the release of “PowerShell Core 7”, now just “PowerShell 7”, the VS Code team just released a major update of the PS extension for VS Code.

In short, what’s new :

  • ISE Compatibility module
  • Syntax Highlighting, Multi-Line Editing and Back Search in the Integrated Console
  • Performance Improvements
  • Take care of some breaking change

You can find the full announcement here : https://devblogs.microsoft.com/powershell/visual-studio-code-for-powershell-7/

How to install PowerShell Core 7 on Windows and Linux

PowerShell is a must have skill for a developer or system administrator working in the Microsoft ecosystem, but not only. With the release of the version 7 of PowerShell Core, the improvements and new features make more us more powerful to to what we need to be do for our clients.

The PowerShell team announced PowerShell 7 here. PowerShell 7 is now built on .NET Core 3 and brings back many APIs required by modules built on .NET Framework, so now they work with .NET Core runtime and PowerShell 7 ! This is a huge improvement for what we can do with PS.

Here is how you can install and update PowerShell Core 7 on Windows and Linux (preview) from officiel documentation :

Windows 10 install

1. On Windows 10, you can execute this simple command line to install PS Core 7 with a PS instance (with administrator rights) :

iex « & { $(irm https://aka.ms/install-powershell.ps1) } –UseMSI -Quiet »

image

Note : If you install a previous version of PowerShell Core (PS6 for example) and you use –Quiet option, it will fail to install PS7. In that case, remove the –Quiet option and follow the installer UI instructions.

2. To launch a PSC7 instance, either right click in a directory ‘PowerShell 7 > Open here’ or just type ‘pwsh’ :

image

image

Linux install

PowerShell 7 supports the following operating systems on x64, including:

  • Windows 7, 8.1, and 10
  • Windows Server 2008 R2, 2012, 2012 R2, 2016, and 2019
  • macOS 10.13+
  • Red Hat Enterprise Linux (RHEL) / CentOS 7+
  • Fedora 29+
  • Debian 9+
  • Ubuntu 16.04+
  • openSUSE 15+
  • Alpine Linux 3.8+

Note : latest version 19.10 is not supported :
image

1. In a bash terminal, just execute the following command line :

wget https://aka.ms/install-powershell.sh; sudo bash install-powershell.sh; rm install-powershell.sh

2. To launch a PSC7 instance in the bash just type ‘pwsh’ :

PS 7 works fine even on a low Memory/CPU computer Smile

For Linux, you can see the documentation here : https://docs.microsoft.com/fr-fr/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7.

aOS Nouméa 28/02/2020 : session Serverless avec les Azure Functions disponible

Pour faire suite à l’aOS Nouméa qui s’est déroulé le 28/02/2020, j’ai eu l’occasion de présenter le « Serverless avec les Fonctions Azure » et la puissance qu’elles représentent dans une architecture Cloud / Nano Services.

Je vous laisse voir ou revoir les slides de cette session sur SlideShare :

aOS Nouméa 2020 – 28/02/2020 – Le Serverless avec Azure Function de Julien Chable

Session Machine Learning et .NET avec ML.NET au Diginova 2019

Pour cette session en compagnie de Christopher Maneu (Microsoft France R&D), j’ai eu le plaisir de pouvoir parler de ML.NET, cette bibliothèque que l’on a déjà implémenté dans un produit et qui fonctionne à merveille (ou presque quand ce ticket aura été corrigé) et qui permet à tout développeur d’intégrer du Machine Learning dans ses applications .NET.

Ce duo avec Christophe a permis de comparer les solutions et de préciser les différents scénarios d’utilisation des services et framewok que Microsoft met à disposition des développeurs (ACS, CNTK, ML.NET) : quand l’utiliser, les scénarios connectés/déconnectés d’ACS et ML.NET, quel effort de montée en compétence pour les développeurs (SDK + apprentissage du Machine Learning), etc.

Un sujet extrêmement intéressant qu’il a fallut traiter en peu de temps .. .mais qui sera traiter plus en profondeur au prochaine Afterworks Microsoft 😉

IMPORTANT NOTE : .NET Core Container Images now Published to Microsoft Container Registry

THIS IS AN IMPORTANT ANNOUNCEMENT: Microsoft is now publishing .NET Core container images to Microsoft Container Registry (MCR).

Note that Microsoft will continue to maintain Docker Hub repo pages so that you can discover and learn about .NET Core images. The Docker Hub website URLs you’ve used for Microsoft repos will continue to work, and forward to updated locations on Docker Hub.

Important :

  • Microsoft also made other changes to the images we publish, described in this post.
  • You will need to change FROM statements in Dockerfile files and docker pull commands as a result of these changes. 3.0 references need to be changed now. Most 1.x and 2.x usages can be changed over time. The new tag scheme is decribed in this post and are provided at the microsoft-dotnet-core repo, Microsoft new home on Docker Hub.

For more informations, please refer to this post on .NET Blog.

Reminder : .NET Core 1.0 and 1.1 will reach END OF LIFE on June 27, 2019

.NET Core 1.0 was released on June 27 2016 and .NET Core 1.1 was released on November 16 2016. As an LTS release, .NET Core 1.0 is supported for 3 years and .NET Core 1.1 fits into the same support timeframe as .NET Core 1.0.

So in short : .NET Core 1.0 and 1.1 will reach end of life and go out of support on June 27, 2019.

After this date of June 27, 2019, .NET Core updates will no longer include updated packages or Docker container images for .NET Core 1.0 and 1.1. But wait, no panic and this is for the best, upgrade from .NET Core 1.x to .NET Core 2.1 or 2.2.

.NET Core 2.1 is a long-term support (LTS) release so makes it your minimum standard for your development, even if I encourage you to use .NET Core 2.2. Why .NET Core 2.1 at least and not .NET Core 2.0 ? Because .NET Core 2.0 has already reached end-of-life, as of October 1, 2018

Upgrade to .NET Core 2.x

The supported upgrade path for .NET Core 1.x applications is via .NET Core 2.1 or 2.2. Instructions for upgrading can be found in the following documents (equally apply to .NET Core 2.1) :

The migration is quick and easy but be sure to bulletproof your application with heavy testing, I already found several minor issues while migrating from 1.1 to 2.1.


La présentation de l’aOS Tahiti 2019 est disponible

J’ai eu le plaisir avec Sylver et Patrick de pouvoir organiser un évènement aOS (Azure, Office 365, SharePoint) à Tahiti le 06 Mars 2019 dans les locaux de SF2i Polynésie. Un franc succès ! Merci à eux !

Un évènement qui devrait se reproduire l’année avec une dimension un peu plus importante 😉

Voici ma présentation :