Category Archives: Short Walks

Casting a C# Object From its Parent

Have you ever tried to do something akin to the following:

public void ConvertClassToSubClass_Converts()
    // Arrange
    var parentClass = new SimpleTestClass();
    parentClass.Property1 = "test";
    // Act
    var childClass = parentClass as SimpleTestSubClass;
    // Assert
    Assert.Equal("test", childClass.Property1);

This is a simple Xunit (failing) test. The reason is fails is because you (or I) am trying to cast a general type to a specific, and C# is complaining that this may not be possible; consequently, you will get null (or for a hard cast, you’ll get an InvalidCastException.

Okay, that makes sense. After all, parentClass could actually be a SimpleTestSubClass2 and, as a result, C# is being safe because there’s (presumably – I don’t work for MS) too many possibilities for edge cases.

This is, however, a solvable problem; there are a few ways to do it, but you can simply use reflection:

public TNewClass CastAsClass<TNewClass>() where TNewClass : class
    var newObject = Activator.CreateInstance<TNewClass>();
    var newProps = typeof(TNewClass).GetProperties();
    foreach (var prop in newProps)
        if (!prop.CanWrite) continue;
        var existingPropertyInfo = typeof(TExistingClass).GetProperty(prop.Name);
        if (existingPropertyInfo == null || !existingPropertyInfo.CanRead) continue;
        var value = existingPropertyInfo.GetValue(_existingClass);
        prop.SetValue(newObject, value, null);
    return newObject;

This code will effectively transfer any class over to any other class.

If you’d rather use an existing library, you can always use this one. It’s also Open Source on Git Hib.

Xamarin Dependencies – Android App Just Doesn’t Start After Deployment

Being relatively new to Xamarin, I naively expected any errors to just show up, you know, like when you run a console app after headbutting the keyboard, it gives you some vague indication that there’s a problem with your code.

My story starts with the default template of Xamarin, running just an Android application. I just want to mention again that this is the default template (admittedly I am running VS2019 and .Net Core 3.0 – at the time of writing, .Net Core 3.0 is still in preview).

Anyway, I start writing my app, and everything is running fine. I add a button, and it appears, I do something on button press: it does it – I’m on a roll! Then I add a chunk of code that calls an API… and suddenly the app just doesn’t run. It compiles and deploys fine, but it doesn’t run. At all.

It occurred to me that this does, potentially, make sense. The code that’s generated may now be complete garbage. In the same way as if you headbutted the keyboard in your console app, the C# compiler will simply run and JIT your C# into invalid IL… Except, that’s not what happens. No sane (statically typed) compiled system would compile a bunch of crap and deploy it… but hey ho.

So, why would my app not run?

Well, it was down to the following line:

var data = JsonConvert.DeserializeObject<List<MyData>>(contentString);

The reason being that, by default, JSON.Net is not installed in the default template; however, because it (or a version of it) is a dependency of one of the other libraries, it is accessible! Presumably there’s a conflict somewhere, or when this compiles it produces a big pile of steaming Java!

(I realise it doesn’t compile down to Java – but I think you’ll agree, steaming IL doesn’t have the same ring to it.)

Anyway, the moral of the story is: check your Newtonsoft dependencies, and liberally distribute try / catch blocks everywhere – it seems to be the only way to get a half sensible error from Xamarin.

Mocking IConfiguration Extension Method

In this post I wrote about the use of app settings in Asp.Net Core. One thing that I didn’t cover at the time was the fact that, as an extension library, the configuration extensions weren’t very easy to include in unit tests. Of course the intention is that you read the configuration at the start, pass through a model class and no mocking is required.

However, sometimes you’ll find yourself wanting to mock out a particular setting. Before I get into this, this post is heavily based on this article which describes the same process.

The following is a code sample using Moq:

            var configuration = new Mock<IConfiguration>();

            var configurationSection = new Mock<IConfigurationSection>();
            configurationSection.Setup(a => a.Value).Returns("testvalue");

            configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);            

This will cause any call to get the app settings key “TestValueKey” to return “testvalue”. As is stated in the linked article, whilst GetValue is an extension method, GetSection is not, but is (internally) called by GetValue.


Short Walks – MakeCert is dead – long live New-SelfSignedCertificate

If you wanted to produce a self-signed certificate, the way to do this used to be makecert. It was part of the Windows SDK. Since Microsoft removed the Visual Studio Command Prompt (not sure why), you would run it like so:

Files (x86)\Microsoft Visual

And then you could call MakeCert; for example:

makecert -r -pe
"CN=testcert" -b 12/12/2018 -e 12/12/2021 -sky signature -a sha256
-len 2048 -ss my -sr LocalMachine

However, one thing that you’ll notice now if you visit the MakeCert page is that it’s deprecated. The new way is a Powershell command; which can be used like so:

New-SelfSignedCertificate -Subject "CN=testcert" -KeySpec "Signature" -CertStoreLocation "Cert:\CurrentUser\My"

Short Walks – Navigating in ReactJs

When you start using the React sample templates, one thing that you’ll notice is the navigation menu; it tends to look like this:

<div className='navbar-collapse collapse'>
    <ul className='nav navbar-nav'>
            <NavLink to={ '/' } exact activeClassName='active'>
                <span className='glyphicon glyphicon-home'></span> Home

After messing around for a while, you’ll probably think: now I need to navigate somewhere from within the code of the tsx/jsx file. Turns out you need to use `.push()`:

import { NavLink } from 'react-router-dom';

. . .

.then(output => {

Not exactly intuitive. And even less intuitive is if you want to go back. You’re thinking it must be `.pop()`? So was I; it’s actually:

import { NavLink } from 'react-router-dom';

. . .

.then(output => {

Short Walks – NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods

Not a huge post, but this has tripped me up several times, and sent me down some quite deep rabbit holes.

On to the story…

I once had a check to received calls like this:

var myData = Substitute.For<IData>();

. . .

    .Add(Arg.Is<MyEntity>(a =>
        a.Active == true
        && a.Field1 == 1
        && a.Field2 == 42))

And I was getting the error:

NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods

I was confident that I had declared it correctly, a few lines above… I could, in fact see that I had declared it correctly. As my brain slowly dribbled from my nose, I did a quick search on the web; and found a solitary article that suggested I might have confused the Received and method calls; the correct syntax being:

    .Add(Arg.Is<MyEntity>(a =>
        a.Active == true
        && a.Field1 == 1
        && a.Field2 == 42));

Hopefully, now that I’ve doubled the available resources available to people finding this error, it will plague me less in compensation.

Short Walks – System.InvalidOperationException: ‘The seed entity for entity type ‘MyEntity’ cannot be added because another seed entity with the same key value for {‘Id’} has already been added. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.’

I got this error recently while playing with EF Core 2. There’s very little on Google about it; although it’s not a hugely difficult problem to solve, if I ever get it again, I can just Google it !

The error:

System.InvalidOperationException: ‘The seed entity for entity type ‘MyEntity’ cannot be added because another seed entity with the same key value for {‘Id’} has already been added. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.’

If effectively cause by a conflict in the primary key; and it gives you the first step towards solving it in the error (in OnModelCreating):

var options =
    new DbContextOptionsBuilder<ApplicationDbContext>()

Now it says:

System.InvalidOperationException: ‘The seed entity for entity type ‘MyEntity’ cannot be added because another seed entity with the key value ‘Id:1′ has already been added.’

In my particular case, I’d been playing around with adding some seed data, and had left this in (OnModelCreating):

modelBuilder.Entity<MyEntity>().HasData(new Data.MyEntity()
    Id = 1,
    Name = "Test",
    CreatedDate = new DateTime(2018, 07, 03),
    UpdatedDate = new DateTime(2018, 07, 03)

Short Walks – XUnit Warning

As with many of these posts – this is more of a “note to self”.

Say you have an assertion that looks something like this in your Xunit test:

Assert.True(myEnumerable.Any(a => a.MyValue == "1234"));

In later versions (not sure exactly which one this was introduced it), you’ll get the following warning:

warning xUnit2012: Do not use Enumerable.Any() to check if a value exists in a collection.

So, Xunit has a nice little feature where you can use the following syntax instead:

Assert.Contains(myEnumerable, a => a.MyValue == "1234");

Short Walks – Submit a single row of data in ReactJS

While looking into the react sample app, I came across a scenario whereby you might need to pass a specific piece of data across to an event handler. A lot of the online examples cover data state; but what happens when you have a situation such as the one in the sample app; consider this:

In this instance, you want to pass the temperature of the line you’ve selected. The solution is quite simple, and documented here:

private renderForecastsTable(forecasts: WeatherForecast[]) {
    return <table className='table'>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
        { =>
            <tr key={ forecast.dateFormatted }>
                <td>{ forecast.dateFormatted }</td>
                <td>{ forecast.temperatureC }</td>
                <td>{ forecast.temperatureF }</td>
                <td><button onClick={(e) => this.handleClick(e, forecast)}>Log Temperature!</button></td>

Here, we’re passing the entire forecast object to the handler; which looks like this:

handleClick = (event: React.FormEvent<HTMLButtonElement>, forecast: WeatherForecast) => {
    console.log("timestamp: " + event.timeStamp);
    console.log("data: " + forecast.temperatureC);

Short Walks – Using AppSettings.json in Asp Net Core

One of the things that is very different when you move to Asp.Net Core is the way that configuration files are treated. This partly comes from the drive to move things that are not configuration out of configuration files. It looks like the days of app.config and web.config are numbered and, in their place, we have AppSettings.Json. Here’s an example of what that new file might look like:

  "Logging": {
    "LogLevel": {
      "Default": "Warning"
  "AzureAppSettings": {
    "ApplicationInsightsKey": "1827374d-1d50-428d-92a1-c65fv2d73272"

The old files were very flat and, using the configuration manager, you could simply read a setting; something like this:

var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key];

So, the first question is: can you still do this? The answer is, pretty much, yes:

public void ConfigureServices(IServiceCollection services)
    IConfigurationBuilder builder = new ConfigurationBuilder()
    Configuration = builder.Build();


However, you now have the option of creating a class to represent your settings; something like:

AzureAppSettings azureAppSettings = new AzureAppSettings();

If you use this approach then you’ll need an extension library from NuGet:

Install-Package Microsoft.Extensions.Configuration.Binder

Is it better, or worse?

At first glance, it would appear that things have gotten worse; or at least, more complex. However, the previous method had one massive problem: it was a static class. The result being that most people have written their own wrapper around the ConfigurationManager class. We now have a class that can be injected out of the box; alternatively, you can split your configuration up into classes, and pass the classes around; the more I think about this, the better I like it: it makes more sense to have a class or method accept parameters that are necessary for its execution and, arguably, breaks the single responsibility principle if you’re faffing around trying to work out if you have all the operating parameters.

The other advantage here is that the configuration file can now be hierarchical. If you have well designed, small pieces of software then this might not seem like much of an advantage, but if you have 150 settings in your web.config, it makes all the difference.