Monthly Archives: October 2021

More Pattern Matching in C#

A while back I wrote a post C# 8.0 enhancements with pattern matching which was very light on the subject. Let’s look a little more in depth at options for pattern matching.

is/as in pattern matching syntax

Often (if you’ve been writing C# for a while) you’ll used to writing code like this

var person = o as Person;
if (person != null)
{
   Console.WriteLine(person.FirstName);
}

i.e. we have an object o which we don’t know the type of, so we use as to convert this to a Person type or null if it’s not of that type.

This can be replaced with a slightly more concise syntax (and what’s known as the declaration pattern).

if (o is Person person)
{
  Console.WriteLine(person.FirstName);
}

Null checks

This is a pattern known as a constant pattern

if (o is null)
{
  Console.WriteLine("Is null");
}

Along with a logical pattern using not we can also write

if (o is not null)
{
  Console.WriteLine("Is not null");
}

We can also use this pattern with types, for example

if (o is not (string or null))
{
  Console.WriteLine("Is NOT string or null");
}

<strong>Pattern matching when values match a criteria</strong>

If we extend the above Pattern Matching to not just check the type is a Person but also that the Age property is greater than 4, so we can now replace

[code language="csharp"]
if (o is Person p && p.Age > 4)
{
  Console.WriteLine($"Older than 4 {p.FirstName}");
}

with the following

if (o is Person { Age: > 4 } p)
{
   Console.WriteLine($"Older than 4 {p.FirstName}");
}

In the above we’re using a property pattern.

Switch patterns matching

Exhaustive switches can be used to match types using switch statements, for example

var result = o switch
{
  string s => $"String {s}",
  Person p => $"Person {p.FirstName}",
  _ => throw new ArgumentException("Unhandled type")
};

Note the use of the _ (discard) ensuring this is an exhaustive switch.

Better still we can also use other features of pattern matching in the switch like this

var result = o switch
{
  string s => $"String {s}",
  Person { Age: > 4} p => $"Person {p.FirstName} > 4",
  Person p => $"Person {p.FirstName}",
  null => "In Null",
  _ => throw new ArgumentException("Unhandled type")
};

In the above we’re switching based upon type and also matching values.

We can also use relational patterns, in this example we’ll assume o is an int

var result = o switch
{
  1 or 2 => "One or Two",
  > 2 and < 4 => "Mid",
  >= 4 and < 6 => "High",
  6 => "Six",
  _ => "Other"
};

Before we leave the switch statement we can also match against types using the “standard” switch syntax, i.e.

switch (o)
{
  case string s:
    Console.WriteLine(s);
    break;
  case Person p:
    Console.WriteLine(p.FirstName);
    break;
}

Tuples

Pattern matching also allows us to match against tuples and use the discard to ignore parts we’re not interested in, for example

var result = o switch
{
  (1, _) => "First One",
  (_, 0) => "Second Zero",
  _ => "Other"
};

Creating new variables from patterns

We can also use the var pattern to assign values from the patterns

var result = o switch
{
  var (a, b) when a < b => new Tuple<string, int, int>("First less than second", a, b),
  var (a, b) when a > b => new Tuple<string, int, int>("Second greater than first", a, b),
  var (a, b) => new Tuple<string, int, int>("Equals", a, b)
};

In this example we’re deconstructing a tuple and assigning to some new value (in this case an extended Tuple, just because I couldn’t think of a better example – check the documentation link above for a better example).

Mocking – JustMock Lite, NSubstitute, FakeItEasy and Moq

I having been working on several projects with different teams, each have their preferred mocking framework (as well as many other differences in choices of tech.), this post is not meant as a comparison of popularity, preference or even functionality, its really more of a reminder to myself how to use each framework for the core mocking requirements so when switching between teams/projects I’ve a little reminder of the different syntax etc.

Note: This post is not complete or particularly comprehensive and I’ll update further as I need to use other features of the various libraries, but just wanted to get this published before I forget about it. Also there may be better or alternates ways to do things in different frameworks, for the purpose of this post I’m only really interested in showing the bare minimum changes to switch between frameworks.

Please note, MOQ version 4.20 has introduced a SponsoreLink which appears to send data to some third party. See discussions on GitHub.

What are we mocking?

Before we get into the details of the Mock frameworks, let’s see what we’re mocking

public interface IDataProvider
{
  IList<string> GetIds(string filter);
  event EventHandler Updates;
}

So let’s assume this will be an interface to some data provider, whether it’s remote or what the implementation is makes no difference, but the premise is we get some data using GetIds – maybe a list of trades in a trading application. The event tells us there have been updates to the data (this is a rather simplistic example as we don’t tell the consumer what the updates are, but you get the idea hopefully).

We’ll be passing the IDataProvider into a class which will act like a repository and will be used to get the data specific to that repository and the likes, the implementation of this is not really important to the specifics of this post and hence not included here.

Arrange, Act and Assert (AAA)

AAA is a pattern used within unit tests to

  • Arrange – initialize code including setting up any requirements for the system under test, i.e. create instances of objects to be tested, initialize values of the system under test etc.
  • Act – this is really just the action of using the code that we’re testing
  • Assert – this is the stage where we assert or verify results, i.e. did the system under test return the expected data/value

In terms of mocking frameworks, these should also follow and allow a similar flow when used. What we’re after is a way to create instances of

Arrange

To arrange our mock (or unit tests in general) we aim to create the component parts of a test and setup methods regarding what happens when they’re called etc.. In the case of using a mocking framework, we’ll use the framework to create instances of interfaces (or actual objects in some cases) and as the methods on an object don’t really have implementations behind them, we will want to declare what happens when code tries to call our mocked methods.

JustMock

var provider = Mock.Create<IDataProvider>();

Mock.Arrange(() => provider.GetData("/trades")).Returns(tradeData);

Moq

var provider = new Mock<IDataProvider>();
// or
var provider = Mock.Of<IDataProvider>();

provider.Setup(instance => 
   instance.GetTrades("/trades")).Returns(tradeData);

NSubstitute

var provider = Substitute.For<IDataProvider>();

provider.GetTrades("/trades").Returns(tradeData);

FakeItEasy

var provider = A.Fake<IDataProvider>();

A.CallTo(() => provider.GetTrades("/trades")).Returns(tradeData);

Act

The Act phase is actually the use of our mock objects as if we’re calling the actual implementation, hence in our code we may actually call

provider.GetTrades(route);

See also the section on events to see the mocking frameworks calling events.

Assert

In the unit tests we would now assert the results of our system under test, this may take a form such as of an NUnit assert, such as

Assert.AreEqual(3, systemUnderTest.Trades.Count);

This isn’t really part of the mock, as by this time hopefully our mock objects and methods have been called but we might wish to verify that the calls to the mocked methods actually happened.

Verify

In cases where you wish to assert that a mock has been called correctly, i.e. with the correct arguments or it’s been called N number of times, then we need to Assert. Assertions may be quick complex, for example we might want to ensure that a mock was only called with specific arguments, was called once or many times, maybe we don’t care about the arguments etc.

Let’s look at a fairly simple example where we want to ensure our mocked method is called once and once only

Note: JustMock includes the expectations of call occurrences etc. when arrange the mock hence we just verify or in JustMock, Assert, that all the previous Arrange definitions have been met.

JustMock

Mock.Assert(provider);

Moq

provider.Verify(instance => instance.GetTrades("/trades"), Times.Once());

NSubstitute

provider.Received(1).GetTrades("/trades").

FakeItEasy

A.CallTo(() => provider.GetTrades("/trades")).
   Returns(tradeData).MustHaveHappenedOnceExactly();

What about exceptions?

In some cases we want to mimic the mocked code throwing an exception, we do this as part of the Arrange phase on all frameworks

JustMock

Mock.Arrange(() => provider.GetIds("/trades"))
   .Throws<ArgumentNullException>();

Moq

provider.Setup(instance => instance.GetIds("/trades"))
   .Throws<ArgumentNullException>();

NSubstitute

provider.GetIds("/trades").Returns(x => throw new ArgumentNullException());

FakeItEasy

A.CallTo(() => provider.GetIds("/trades")).Throws<ArgumentNullException>();

What about events?

Ofcourse C# has an event model which we would also want to mock, let’s see how each framework allows us to simulate events. The Mock framework would already have supplied the event code and hence what we’re really wanting to do it cause an event to occur. This would therefore be part of the Act phase

JustMock

Mock.Raise(() => provider.Updates += null, null, null);

Moq

provider.Raise(instance => 
   instance.Updates += null, EventArgs.Empty);

NSubstitute

provider.Updates += Raise.Event();

FakeItEasy

provider.Updates += Raise.WithEmpty();

Code

Code is available on GitHub

Index and Range in C#

In C# 8.0 two classes were added to C# to handle Index and Ranges (as well as some syntactic sugar in the form of .. to represent a Range). Both are structs, an Index being literally an int but with some static method and “helper” methods for using indicies. As you might expect, a Range, is made up of a start Index and an end Index. Let’s have a look at both types in a little more depth…

Index

An Index is a very simply type which is best understood in usage on a collection. Let’s therefore assume we have some collection type which, ofcourse, allows for you to get at item at a specific index.

This is hardly an exciting addition in itself but what it does is gives us some “standard” code for handling things like, get the nth item from the end of the collection, using the overloaded ^ operator. Let’s see this in action by creating a simply collection

public class MyCollection
{
  private readonly string[] _collection;

  public MyCollection()
  {
    _collection = new[]
    {
      "One",
      "Two",
      "Three",
      "Four",
      "Five"
    };
  }

  public string this[Index idx] => _collection[idx.GetOffset(_collection.Length)];
}

All we’ve really done here that’s slightly different to how we’d have written this without an Index is we use the Index GetOffset to give us the actual index number to get the value from the collection. What this really does is allow us to write code such as

var c = new MyCollection();
Console.WriteLine(c[^2]);

The ^2 on an Index simply means give me the 2nd item from the end which would result in “Four” being written to the console ^1 would be the equivalent of _collection[_collection.Length – 1] hence you can see that ^2 is the equivalent of _collection[_collection.Length – 2]. The Index helper method simply allows us to let it handle any conversion for us. Ofcourse we can write the following

var c = new MyCollection();
Console.WriteLine(c[2]);

Which, as you’ve expect returns “Three” this item at index 2.

Range

The Range uses Index types to create a Range, for example

var range = new Range(1, 10);

This create a range type with a start of 1 and end of the range 10. Where the Range becomes more useful is in the syntactic sugar, the range shown in the snippet above may be written as

var range = 1..10;

This create a new Range type just as the first snippet, but now if we start to use this sort of stuff in collection types or our own types we start to get some neat syntax to get slices of collections – it should be noted that the current implementation of collections in .NET sees arrays supporting Range and hence can return slices of arrays, whereas other collections do not explicitly support Index and Range but instead can be used with them due to the operator overloading etc.

ofcourse we can create our own types to do similar. Before we look at implementing such things let’s quickly review the basic syntax possibilities/expectations

// short cut for getting a slice [0..10]
var firstToN = array[..10]; 
// short cut for getting the item 2 from the end
var nthItemFromEnd = array[^2]; 
// short cut for getting all items into a copy of the array
var all = array[..]; 

Support for Index

We can write our own types to explicitly understand Index and Range types, however using standard methods existing types can support Index and Range. Let’s demonstrate this by changing our MyCollection type to replace the indexer to look like this (i.e. remove the Index support).

public string this[int idx] => _collection[idx];

If you try to compile with myCollection[^2] you’ll now get a compiler error, cannot convert from ‘System.Index’ to ‘int’. So how do existing types work with Index? This is due to “implicit Index support” which basically means the compiler expects certain named methods with certain expected parameters.

The first required is the type is Countable which basically means it has a property named Length or Count with an accessible getter which returns an int. So this covers arrays and collections such as the List type. Let’s therefore add this to our type

public int Count => _collection.Length;

Now the compiler error will go away. If you think about it, it quite obvious what’s happening, in our original code for the indexer

public string this[Index idx] => 
   _collection[idx.GetOffset(_collection.Length)];

We ofcourse need the length of the collection as well as the Index. Well the compiler using the “implicit Index support” needs the same. So once we add the Count or Length properties, it can now get that information at create the code we otherwise would have to write ourselves and thus an indexer [int idx] now gets the value from the Index implicitly supplied.

So to wrap up “implicit Index support”, your type needs the following

  • The type is Countable i.e. has Length or Count property accessible and returning an int
  • The type has an accessible indexer which takes an int
  • The type does not have an accessible indexer which takes an Index as the first parameter

Support for Range

Let’s change our calling code to try to get a slice of our collection, so now we have

var c = new MyCollection();
Console.WriteLine(c[1..^2]);

This will immediately show the compile time error “cannot convert from ‘System.Range’ to ‘int'”. Let’s therefore add implicit support for Range to our collection.

Well again the type needs to be Countable and also not have a accessible indexer which takes a Range (otherwise this would assumer the type is explicitly handling Range). Which currently have.

As you’d imaging to handle ranges we need a method that creates a slice or sub-collection from our collection and that’s exactly what’s required. Let’s add a Slice method which returns a collection (in our case we’re just pretty much copy the code from Ranges which is also the best place to look for information on Index and Range.

Add the following to MyCollection

public string[] Slice(int start, int length)
{
  var slice = new string[length];
  Array.Copy(_collection, start, slice, 0, length);
  return slice;
}

The compiler should now show our previously broken c[1..^2] code as valid and if you make a small change to output the items from the returned slice, like this

foreach (var item in c[1..^2])
{
  Console.WriteLine(item);
}

You’ll see items from the item at index 1 through to the one 2 from the end, i.e. “Two” and “Three”.

So to wrap up “implicit Range support”, your type needs the following

  • The type is Countable i.e. has Length or Count property accessible and returning an int
  • The type contains an accessible method named Slice which takes two int params, the first being the start index the second being the length
  • The type does not have an accessible indexer which takes an Range as the first parameter

With both the implicit Index and Range code you could ofcourse write explicit code (i.e. use Index and Range in your code). Both offer helper methods to make the experience of using them consistent. Ofcourse neither are restricted to collection types and let’s look at extending Range…

Extending Range

As already mentioned, Index and Range are fairly limited in functionality, but that’s fine, they do exactly what they’re intended to do, but if you’ve ever wanted a Range of numbers in C# you’ve probably looked at Enumerable.Range, so writing something like this

foreach (var i in Enumerable.Range(1, 10))
{
  Console.WriteLine(i);
}

For fun and now we have the syntactic sugar of .. to represent a Range type it’s be cool to write something like this instead

foreach (var i in 1..10)
{
  Console.WriteLine(i);
}

Okay so we know that this is really a Range instance like this

foreach(var r in new Range(1, 10))
{
  Console.WriteLine(i);
}

but ofcourse this will not work, as Range does not support IEnumerator. No worries we’ll create an extension method, something like this

public static class RangeExtensions
{
  public static IEnumerator<int> GetEnumerator(this Range range) =>
    Enumerable.Range(range.Start.Value, range.End.Value).GetEnumerator();
}

This now allows us to use a Range within a foreach and better still we can now use the .. operator syntax

foreach (var item in 1..10)
{
  Console.WriteLine(i);
}

Note: Whilst this offers syntax along the lines of Rust – I’m not necessarily saying using Range in this way within a foreach is a great idea because Range, via Index, supports ^ (from end) syntax and we’re definitely not attempting to support such syntax in our extension method but the terse nature of it’s usage is nevertheless interesting (or for those who prefer more explicit methods then it’s probably horrible).

We could extend our fun and our extension method to add support for IEnumerable for Linq queries, whilst not as nice as the IEnumerator in it’s implicit nature, we might add to RangeExtensions, the following

public static IEnumerable<int> ToEnumerable(this Range range)
{
  foreach (var item in range)
  {
    yield return item;
  }
}

Now we can use this like with Linq, maybe like this

foreach (var i in (1..10).ToEnumerable().Where(v => v % 2 == 0))
{
  Console.WriteLine(i);
}

Which will output the even numbers between 1 and 10.

References

Ranges

Checking who last logged in and when on Ubuntu Server

You might want to see a list of who logged into your Ubuntu server last or over a time period. Or maybe you want to take a look at more than just that and see more of an audit trail…

last

We can use the command last to display a “listing of last logged in users”. For example let’s just get the tail of the list using

last | tail

or ofcourse we might simple look through all entries using

last | less

What about if we know the user we’re interested in, then we can simply use

last -x Bob

Replacing Bob with the username you wish to look for.

There’s options to specify listing data after a specific time or before a time and more see

last --help

What if we want even more information.

/var/log/auth.log

Last works well if you’re interested in users logging into the server, but what about if we just want to check who’s access a shared drive or the likes, then we can check the /var/log/auth.log like this

sudo cat /var/log/auth.log
// or 
sudo less /var/log/auth.log
// or
sudo tail /var/log/auth.log

As per standard piping of commands, I’ve included an example of using less and tail, but basically we want to list the contents of the auth.log file. Ofcourse as it’s a file we can grep it (or whatever) as required.

This auth.log file lists sessions being opened and closed, cron jobs and lots more besides.

Ubuntu server auto upgrade

I have an Ubuntu server happily living it’s life as a NAS (and more) server which every now and then (if I forget to keep track of updates) it runs out of space on /boot causing issues removing old releases or partial updates to be a bit of a problem. So how do we either turn on or off automatic upgrades?

The configuration for this is stored in the file 20auto-upgrades. So we can edit the file using

sudo nano /etc/apt/apt.conf.d/20auto-upgrades

Within the file you’ll see something like this

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

Note: The “1” in the above are not True/False but the minimum number of days. So we could change from “1” to run weekly by changing this value to “7”. A value of “0” will disable the feature.

You can create the file yourself or run the following command to create the file (it can be used to turn on/off by running it on an existing file but that’s all)

sudo dpkg-reconfigure -plow unattended-upgrades

If you want to change the frequency of checks for updates you’ll need to edit the 20auto-upgrades manually (as already discussed).

References

AutomaticSecurityUpdates.
UnattendedUpgrades

Fingerprint and biometrics authentication in Xamarin Forms

This is something I’ve wanted to try for a while and there’s a NuGet package that will allow us to enable and use biometric authentication with very little effort – much of this post will end up covering the github README at Biometric / Fingerprint plugin for Xamarin. So I strongly recommend checking that out.

Create a sample application

Let’s create a new Xamarin Forms application to test this out. So follow these steps to get up and running…

  • In Visual Studio create a new project – Mobile App (Xamarin.Forms)
  • At the solution level, right mouse click in Visual Studio 2019 and select Manage NuGet Packages for Solution
  • Browse for Plugin.Fingerprint by Sven-Michael Stübe
  • Click on the package then check each of your projects, shared and platform specific. We need to add the plugin to all projects, then click Install
  • In the Android MainActivity.cs file, OnCreate method after Xamarin.Essentials.Platform.Init(this, savedInstanceState); add
    CrossFingerprint.SetCurrentActivityResolver(
       () => Xamarin.Essentials.Platform.CurrentActivity);
    
  • In the Android Manifest add Required Permissions USE_FINGERPRINT
  • In the iOS project, open the Info.plist in code (F7) and add the following
    <key>NSFaceIDUsageDescription</key>
    <string>Use your face to authenticate</string>
    

    Ofcourse the string can be whatever you want.

Now we’ve got the project and configuration set up you’ll want some popup, page or just a button on your MainPage.xaml to initiate the Fingerprint/Biometrics login. For now let’s just add a Button to the MainPage.xaml and, for brevity, just add a Clicked handler, so for example

<Button Clicked="Button_OnClicked" Text="Authenticate with Biometrics" />

and here’s the code within the code behind for Button_OnClicked

private async void Button_OnClicked(object sender, EventArgs e)
{
   if (await CrossFingerprint.Current.IsAvailableAsync(true))
   {
      var result = await CrossFingerprint.Current.AuthenticateAsync(
         new AuthenticationRequestConfiguration("Login", "Access your account"));
      if (result.Authenticated)
      {
         await DisplayAlert("Success", "Authenticated", "OK");
      }
      else
      {
         await DisplayAlert("Failure", "Not Authenticated", "OK");
      }
   }
   else
   {
      await DisplayAlert("Failure", "Biometrics not available", "OK");
   }
}

We begin by checking if biometrics are available, passing in true will allow fallback to pin authentication. Assuming biometrics are available we then display the authentication mechanism using AuthenticateAsync passing in configuration that, in this case, will display some text on the fingerprint popup. If we’re authenticate then we display an alert to show success, in this example, but ofcourse you’ll handle success and failure as needed by your application.

Testing in the Android emulator

To test this application in the Android emulator

  • Goto the Settings within the Android OS and select Security
  • Under Device Security select Screen lock and add a pin
  • Under Device Security select Fingerprint and add a fingerprint, now to actually add a fingerprint we’ll click the … on the emulator and select Fingerprint, then click the Touch the Sensor button twice – you’re see the Fingerprint dialog go 50% of the way then 100% on the second click, finally click Done

Once we’re set up the security on the emulator and supplied one or more fingerprints run up your Xamarin Forms application and click the button you added. You’ll be presented with the AuthenticationRequestConfiguration you added, again using the … button on the emulator (if you closed the Extended controls dialog), select Fingerprint and click Touch the Sensore – this basically emulates a fingerprint touching the sensor.

To test for success, ensure the Fingerprint selected is one you added, i.e. by default Finger 1, to test for failure simply select one of the other, non-configured fingers and click Touch the Sensor

Testing in the iOS simulator

The setup for testing using the iOS simulator is a little simpler than Android…

  • Open the simulator and (in the latest XCode I’m using 13 but basically 12.x and above) select Features | Touch ID or Face ID (whichever is available on your simulator) and check the Enrolled option to show a tick (untick to remove the feature).

Now when you click your authentication button in your Xamarin forms application you may be presented with the dialog to allow the permission to be used, once you’ve accepted this you won’t see it again. Next you’ll see a small grey square which will denote your Face ID authentication (or for Touch ID you’ll get the fingerprint dialog), from the simulator’s Features and Face ID submenu, select Matching Face to simulate a successful authentication or Non-matching Face for a failure. For Touch ID simulators select Matching Touch for successful authentication or Non-matching Touch for a failure.

Code

Code for this post is available on GitHub.

References

Biometric / Fingerprint plugin for Xamarin
Enrolling a Fingerprint