Steve Fenton https://www.stevefenton.co.uk Mon, 25 May 2020 20:42:23 +0000 en-GB hourly 1 https://wordpress.org/?v=5.4.1 https://www.stevefenton.co.uk/wp-content/uploads/2017/06/cropped-wheel-32x32.png Steve Fenton https://www.stevefenton.co.uk 32 32 140638488 C# 9 Covariant Return Types https://www.stevefenton.co.uk/2020/05/csharp-9-covariant-return-types/ Tue, 26 May 2020 05:30:22 +0000 https://www.stevefenton.co.uk/?p=8511 Just a quick note on a neat feature in C# 9 that will allow sub-classes to return a covariant return type… what?! Okay, it allows you to return a more specific, or narrower type. For example, we used to have to return the same type… // parent class... public virtual Literature GetLiterature(...) { return new […]

The journal C# 9 Covariant Return Types was first published at Steve Fenton.

]]>
Just a quick note on a neat feature in C# 9 that will allow sub-classes to return a covariant return type… what?! Okay, it allows you to return a more specific, or narrower type.

For example, we used to have to return the same type…

// parent class...
public virtual Literature GetLiterature(...) 
{
    return new Literature();
}

// child class... returns a Book : Literature
// but the return type is still Literature
public override Literature GetLiterature(...)
{
    return new Book();
}

Well, now you can return the narrower type.

// parent class...
public virtual Literature GetLiterature(...)
{
    return new Literature();
}

// child class...
public override Book GetLiterature(...)
{
    return new Book();
}

The Book has to be a kind of Literature, but it allows the more specific type to be returned, rather than pretending we don’t know as much as we do.

This will actually save you having to reach for generics for this common case.

The journal C# 9 Covariant Return Types was first published at Steve Fenton.

]]>
8511
Turn an Old Phone into a Programmable Keyboard https://www.stevefenton.co.uk/2020/05/turn-an-old-phone-into-a-programmable-keyboard/ Mon, 25 May 2020 20:41:08 +0000 https://www.stevefenton.co.uk/?p=8569 It seems like everyone has a high-quality, expensive, programmable deck on their desk these days. Elgato’s Stream Deck, with it’s glowing LCD buttons, comes in flavours that cost between £100 and £200 (depending on how many buttons you want). It’s beautiful bit of kit that glows its way into the hearts of tech geeks everywhere. […]

The journal Turn an Old Phone into a Programmable Keyboard was first published at Steve Fenton.

]]>
It seems like everyone has a high-quality, expensive, programmable deck on their desk these days. Elgato’s Stream Deck, with it’s glowing LCD buttons, comes in flavours that cost between £100 and £200 (depending on how many buttons you want). It’s beautiful bit of kit that glows its way into the hearts of tech geeks everywhere. If you’re on a budget, though, you can hack together some neat shortcuts using just an old phone, and Touch Portal.

Touch Portal is a desktop app, and a mobile app, that chat to each other to let you perform one tap shortcuts. There are a number of built in utilities you can run, but with batch file and PowerShell available – the only limit is your imagination. I run it in USB mode, so it’s just a case of plugging in the phone that has the Touch Portal app installed and selecting the USB mode in the desktop app (it’s in the bottom-left corner).

Touch Portal is freemium, so you can use two screens for free, and pay a small amount (around £10-£15) to go Pro and use the app without limits.

Touch Portal Desktop App

Adding buttons is pretty simple. You can visually compose logic and actions using an interface no unlike MIT’s Scratch to do a variety of tasks. One of the key simple tasks is keyboard shortcuts. I have a collection of shortcut buttons in pages for Microsoft Teams and for Microsoft Visual Studio. They let me do things like mute and unmute myself with a bit button, so I don’t have to remember all the handy Microsoft Teams Shortcut Keys. For Visual Studio I have a one-tap “Run Tests”, plus some common refactoring shortcuts.

Touch Portal Mobile App

Running Batch Files or PowerShell

To run a batch file or PowerShell script, you just point to the script location on your machine. Simples. It’s best to start from an already working script file, so develop that first and then point at it. I use the “Start Script and Wait” task to launch the script.

Now, in terms of getting feedback, the output from the scripts is appended to the Touch Portal log file in %APPDATA%\TouchPortal\log.txt. What you may want to do, though, is pop yourself a little dialog. It’s a bit of a hack, but a simple way to show a dialog from a PowerShell script is to import Presentation and pop a MessageBox:

Add-Type -AssemblyName PresentationCore,PresentationFramework
[System.Windows.MessageBox]::Show('The test data has now been copied to all locations')

The ability to run scripts effectively makes it possible to do anything. Between this and the simple-to-build keyboard shortcuts, this is a great alternative to a hardware programmable keyboard.

The journal Turn an Old Phone into a Programmable Keyboard was first published at Steve Fenton.

]]>
8569
C# 9 Non-Null Parameters https://www.stevefenton.co.uk/2020/05/csharp-9-non-null-parameters/ Mon, 25 May 2020 05:30:42 +0000 https://www.stevefenton.co.uk/?p=8509 This neat C# 9 feature can be summed up in a tiny snippet of code. You know that code analysis warning that tells you that the argument passed might be null… wouldn’t it be nice if you could refuse to accept null? Well, you can. This is the before… public Book(string firstName, string lastName) And […]

The journal C# 9 Non-Null Parameters was first published at Steve Fenton.

]]>
This neat C# 9 feature can be summed up in a tiny snippet of code. You know that code analysis warning that tells you that the argument passed might be null… wouldn’t it be nice if you could refuse to accept null?

Well, you can. This is the before…

public Book(string firstName, string lastName)

And this is the after, with bangs after the parameter name to say “this can’t be null”.

public Book(string firstName!, string lastName!)

Ideally, this would have been the default way back when, but we live and learn and can now bang-up our parameters and kill of nulls high up in our stack, if they have to exist at all.

The journal C# 9 Non-Null Parameters was first published at Steve Fenton.

]]>
8509
C# 9 Record Types https://www.stevefenton.co.uk/2020/05/csharp-9-record-types/ Sat, 23 May 2020 05:30:10 +0000 https://www.stevefenton.co.uk/?p=8507 We have taken a quick look at C# 9 Initializers and Immutability and C# 9 Non-Destructive Mutation. Let’s now look at the full transformation from an old class to a super character-light record type. Our original record type is very much just a class with two auto-properties. It looks different to a normal class because […]

The journal C# 9 Record Types was first published at Steve Fenton.

]]>
We have taken a quick look at C# 9 Initializers and Immutability and C# 9 Non-Destructive Mutation. Let’s now look at the full transformation from an old class to a super character-light record type.

Our original record type is very much just a class with two auto-properties. It looks different to a normal class because we have the data keyword in there.

public data class Book {
    public string Author { get; init; }
    public string Title { get; init; }
}

Most of the text in this code file is “not the stuff I wrote”. It’s the stuff that expands out when I tab out from a snippet.

Because this is such a common code-shape, the C# team has made it possible to not even type it out. If we assume on a record that we want the properties to be public and that we want them to have an auto get and init then we end up with just this…

public data class Book {
    string Author;
    string Title;
}

This is a simple case and we’ve gone from 102 characters to 60 characters. My keyboard will last almost twice as long.

You can perform a similar trick if you want to force the parameters with a constructor.

public data class Book (string Author, string Title) { }

Or you can mix and match…

public data class Book (string Title) {
    string Author;
}

And finally, in the spirit of putting less stress on your hardware keys, new-ing up an object can now be done with less typing and less repetition.

Book book = new ("The Monk");

Note that I didn’t say new Book. We all know I want a book because I literally typed the type at the start of the line. Nice.

The journal C# 9 Record Types was first published at Steve Fenton.

]]>
8507
C# 9 Non-Destructive Mutation https://www.stevefenton.co.uk/2020/05/csharp-9-non-destructive-mutation/ Fri, 22 May 2020 05:30:26 +0000 https://www.stevefenton.co.uk/?p=8505 There are some phrases in programming that feel like they belong in a superhero movie. Non-destructive mutation is just such as phrase. It refers to a concept in functional programming that means when you want to change the state of an object, you create a copy with the change – rather than changing the original. […]

The journal C# 9 Non-Destructive Mutation was first published at Steve Fenton.

]]>
There are some phrases in programming that feel like they belong in a superhero movie. Non-destructive mutation is just such as phrase. It refers to a concept in functional programming that means when you want to change the state of an object, you create a copy with the change – rather than changing the original.

Firstly, we need to use the new C# 9 record type, which is just a class preceded by the data keyword. Let’s continue the book example from the C# 9 Initializers and Immutability article.

public data class Book {
    public string Author { get; init; }
    public string Title { get; init; }
}

Book book = new Book {
    Author = "Mathew Lewis",
    Title = "The Monk"
};

Book anotherBook = book with { Title = "The Bravo of Venice" };

By creating the second book with the with keyword, we can choose to change one or more properties. The original book isn’t changed, we still have that. We also have our new book. That’s non-destructive mutation in C# 9 in a nutshell.

Now, the with keyword will create a shallow copy, going field by field and assigning the properties. That means reference type properties will end up being shared state by default. This matches what you would expect if you have used structs in C#. However, you can implement your own copy constructor (it just needs to be a constructor that takes an argument of the same type, a Book in our example). So, you can deep-copy if that’s what you need to do.

The journal C# 9 Non-Destructive Mutation was first published at Steve Fenton.

]]>
8505
C# 9 Initializers and Immutability https://www.stevefenton.co.uk/2020/05/csharp-9-initializers-and-immutability/ Thu, 21 May 2020 05:30:55 +0000 https://www.stevefenton.co.uk/?p=8503 There is currently a compromise in C# that means you can enable object initialization with getters and setters, or you can prevent external code mutating state by hiding the setter… but not both. C# 9 gives us both with the init keyword. Let’s look at before… public class Book { public string Author { get; […]

The journal C# 9 Initializers and Immutability was first published at Steve Fenton.

]]>
There is currently a compromise in C# that means you can enable object initialization with getters and setters, or you can prevent external code mutating state by hiding the setter… but not both.

C# 9 gives us both with the init keyword.

Let’s look at before…

public class Book {
    public string Author { get; set; }
    public string Title { get; set; }
}

You can initilize this object, but also change it’s state afterwards:

Book book = new Book {
    Author = "Mathew Lewis",
    Title = "The Monk"
};

// Oh no - we don't want to allow this
book.Title = "The Bravo of Venice";

To prevent any mutation after the initialization, we just switch in init for get.

public class Book {
    public string Author { get; init; }
    public string Title { get; init; }
}

We can now use the object initializer, but we can’t change the state afterwards. Hooray!

The journal C# 9 Initializers and Immutability was first published at Steve Fenton.

]]>
8503
C# 9 Simplified Console Apps https://www.stevefenton.co.uk/2020/05/csharp-9-simplified-console-apps/ Wed, 20 May 2020 05:30:13 +0000 https://www.stevefenton.co.uk/?p=8500 At Microsoft Build 2020, an interesting new “see less boilerplate” feature from C# 9 was demonstrated. It removes all the code to create the class and static Main method, letting you just start typing your code. It makes your code way-less-nested (okay, two levels), but doesn’t miss any of your usual features. For example, args […]

The journal C# 9 Simplified Console Apps was first published at Steve Fenton.

]]>
At Microsoft Build 2020, an interesting new “see less boilerplate” feature from C# 9 was demonstrated.

It removes all the code to create the class and static Main method, letting you just start typing your code. It makes your code way-less-nested (okay, two levels), but doesn’t miss any of your usual features.

For example, args is still available, and if you use an await it will work out the Main method (which you haven’t written) will need to be async.

Here’s an example…

using static System.Console;

WriteLine("Hey, I didn't write a class or method here!");

The concept behind this is to simplify that first-write experience to remove the cruft and focus everything on your code.

Check back for some more C# 9 articles coming soon!

The journal C# 9 Simplified Console Apps was first published at Steve Fenton.

]]>
8500
A Glance at PowerToys and WinGet https://www.stevefenton.co.uk/2020/05/a-glance-at-powertoys-and-winget/ Tue, 19 May 2020 20:22:37 +0000 https://www.stevefenton.co.uk/?p=8492 PowerToys and WinGet are exciting previews for Windows Users. If you are a civilian, you’ll be getting these in general release soon, but for technical folks might want to try things out early. Or now! PowerToys PowerToys has been in preview for a while. You’ll install it when someone shows off FancyZones, which gives you […]

The journal A Glance at PowerToys and WinGet was first published at Steve Fenton.

]]>
PowerToys and WinGet are exciting previews for Windows Users. If you are a civilian, you’ll be getting these in general release soon, but for technical folks might want to try things out early. Or now!

PowerToys

PowerToys has been in preview for a while. You’ll install it when someone shows off FancyZones, which gives you templated tiles to organise your desktop… but you’ll keep it because of the Alt + Space Run command.

PowerToys Run Command

This gives you super easy access to apps or open Windows, with a “Run as Administrator” shortcut and an “Open Folder” shortcut. If the application is already running, you’ll see the option with the “Running” annotation alongside it.

You can also launch a shell command by starting your input with >.

PowerToys Run Shell Command with winget install vscode

It remembers common commands that you run, to save you time.

And finally, you can just use it as a calculator by typing in your calculations.

PowerToys Run with 1452 * 2309

WinGet Quick Start

WinGet is basically that thing we all really, really, really wanted for Christmas and we now have it seven months early. It’s a package manager for Windows that let’s you get the apps you want.

There is a super-cool early preview of WinGet available for those who can handle early sight of things… your quick start is to run winget show vscode to view the Visual Studio Code package.

Command Window with winget show vscode

Installing Visual Studio Code is as simple as the following command… you even get a visual progress bar. Neat.

winget install vscode

Command Window with winget install vscode

Create yourself a file with the “stuff your team all uses” and check it into your source control system so you can all keep it up to date. That way, your new folks can be up and running in no time!

PowerToys is awesome and WinGet is ace… and you can use them together too.

The journal A Glance at PowerToys and WinGet was first published at Steve Fenton.

]]>
8492
How to Drop a SQL Server Constraint When You Don’t Know its Name https://www.stevefenton.co.uk/2020/05/how-to-drop-a-sql-server-constraint-when-you-dont-know-its-name/ Fri, 15 May 2020 10:21:59 +0000 https://www.stevefenton.co.uk/?p=8440 If you are looking after a database that has been haphazardly maintained in the past, you might come across inconsistent naming of things such as constraints. When you come to delete the existing one, it might be tricky if it doesn’t have the same name across environments. That’s when you need to do a lookup […]

The journal How to Drop a SQL Server Constraint When You Don’t Know its Name was first published at Steve Fenton.

]]>
If you are looking after a database that has been haphazardly maintained in the past, you might come across inconsistent naming of things such as constraints. When you come to delete the existing one, it might be tricky if it doesn’t have the same name across environments.

That’s when you need to do a lookup to get the name, so you can drop the constraint. You can use this to target constraints by column and table names. In the future, never let anyone except a human name your constraints.

DECLARE
    @constraint NVARCHAR(200),
    @command NVARCHAR(300)

SELECT
    @constraint = default_constraints.name
FROM 
    sys.all_columns
INNER JOIN
    sys.tables ON all_columns.object_id = tables.object_id
INNER JOIN 
    sys.schemas ON tables.schema_id = schemas.schema_id
INNER JOIN
    sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
WHERE 
    schemas.name = 'dbo'
AND
    tables.name = 'MyTableName'
AND
    all_columns.name = 'MyFieldName'

IF @constraint IS NOT NULL
BEGIN
    SELECT @command = 'ALTER TABLE MyTableName DROP CONSTRAINT ' + @constraint;
    EXECUTE(@command)
END
GO

The journal How to Drop a SQL Server Constraint When You Don’t Know its Name was first published at Steve Fenton.

]]>
8440
Naming TypeScript Custom Type Guards https://www.stevefenton.co.uk/2020/05/naming-typescript-custom-type-guards/ Tue, 12 May 2020 14:22:16 +0000 https://www.stevefenton.co.uk/?p=8422 This is a super quick one. Be super-careful about how you name your custom type guards to stop consumers falling into a trap. Basically, the name you give a custom type guard and the return type you specify form a kind of promise that you have to be able to keep. Take this example: function […]

The journal Naming TypeScript Custom Type Guards was first published at Steve Fenton.

]]>
This is a super quick one. Be super-careful about how you name your custom type guards to stop consumers falling into a trap. Basically, the name you give a custom type guard and the return type you specify form a kind of promise that you have to be able to keep. Take this example:

function isCheckbox(elem: HTMLElement | null): elem is HTMLInputElement {
    return elem != null && elem.hasAttribute('checked');
}

const elem = document.getElementById('example');

if (isCheckbox(elem)) {
    console.log(elem.value);
}

If we apply our lessons in logical reasoning from the critical thinking part of our philosophy education, we find a flaw in this statement.

All checkboxes have a checked attribute
This element has a checked attribute
Therefore this element is a checkbox

Not only does a checkbox not necessarily have a checked attribute (i.e. when it is not checked, the attribute may be entirely absent), it is also true that other elements might have a checked attribute, even though they are not checkboxes.

A good example for this would be:

All swans have white feathers
This bird has white feathers
Therefore this bird is a swan

You can see that the first statement is wrong, because Cygnus Atratus has black feathers.

The last statement is also wrong, because a bird with white features may in fact be on of many birds, such as Anserini.

Keep The Explicit Promise

The first problem in our example is that having a checked attribute doth not an HTMLInputElement make. Yet our code promises to determine if the element is an input. If we want to keep our promise, we need to check the element type.

function isCheckbox(elem: HTMLElement | null): elem is HTMLInputElement {
    return elem != null
        && elem.tagName === 'INPUT';
}

const elem = document.getElementById('example');

if (isCheckbox(elem)) {
    console.log(elem.value);
}

We now satisfy the explicit promise elem is HTMLInputElement.

Keeping the Implicit Promise

The second problem is that our type guard is called “isCheckbox”. Once again, the test does not guarantee that we have a checkbox.

There are two solutions to this. First and foremost is that in many cases, you should rename the type guard to make the implicit promise correct.

function isInputElement(elem: HTMLElement | null): elem is HTMLInputElement {
    return elem != null
        && elem.tagName === 'INPUT';
}

const elem = document.getElementById('example');

if (isInputElement(elem)) {
    console.log(elem.value);
}

Your second option, once you are sure the first option doesn’t solve your problem, is to keep the implicit promise in your type guard.

function isCheckbox(elem: HTMLElement | null): elem is HTMLInputElement {
    return elem != null
        && elem.tagName === 'INPUT'
        && elem.getAttribute('type') === 'checkbox';
}

const elem = document.getElementById('example');

if (isCheckbox(elem)) {
    console.log(elem.value);
}

Honest Type Guards

We now have two tools available to make sure the promises made by type guards can be kept.

Making sure the explicit promise in the function declaration is being satisfied, and making sure the implicit promise in the name is being satisfied.

The journal Naming TypeScript Custom Type Guards was first published at Steve Fenton.

]]>
8422