My talk about how to make code review

February 26th, 2023

The other year I held a talk about how to make code reviews that are of value.
As zip.

Förvänta dig inte att din Pull request går igenom

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring!

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring!
SUGGESTION: Split line.

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring
SUGGESTION: Isn’t it an Article?, not a Device.
CHECK: Have you investigated all uses of the enum?

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring!
SUGGESTION: Split line.
CHECK: Do you use the enum the correct way? Are all cases considered?
EXPLAIN: How do this work?

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring!
SUGGESTION: Split line.
CHECK: Do you use the enum the correct way? Are all cases considered?
EXPLAIN: How do this work?
FIX: Check for null.

ola fjelddahl
göteborgskontoret

Förvänta dig inte att din Pull request går igenom

PRAISE: Nice refactoring!
SUGGESTION: Split line.
CHECK: Do you use the enum the correct way? Are all cases considered?
EXPLAIN: How do this work?
FIX: Check for null.
QUESTION: Is this a HasA or a IsA

ola fjelddahl
göteborgskontoret

A talk about pros and cons with O/RM

February 25th, 2023

These are my pages from my talk about pros and cons with “fat” O/RM today.
As zip.

# O/RM

myname@omegapoint.se Göteborgs-kontoret

https://selfelected.com/
https://ideas.selfelected.com/
https://github.com/LosManos

# O/RM

myname@omegapoint.se Göteborgs-kontoret


Resultat: Ifrågasätt

# O/RM

myname@omegapoint.se Göteborgs-kontoret

Föredraget förutsätter en vag förståelse av ORM.
Fet orm (EF/Hibernate/cache). Micro-orm. (mappning av data och datatyper)
Att det är en översättning från RDb:ns mängdbaserade struktur till det imperativa språkets list-baserade; och tvärtom.

# O/RM

myname@omegapoint.se Göteborgs-kontoret

3 skäl
* Typsäkerhet
* Höger-vänster
* Refaktorering

# O/RM

myname@omegapoint.se Göteborgs-kontoret

Ökad komplexitet

Utsuddade gränser

Choke point

# O/RM

myname@omegapoint.se Göteborgs-kontoret

3 skäl
Typsäkerhet
ändras inte så ofta det så när det väl är mappat
Höger-vänster
ändras ofta i början men tenderar att stabiliseras
Refaktorering
man kan bara automatrefaktorera namn och typer. strukturer är manuellt arbete

# O/RM

myname@omegapoint.se Göteborgs-kontoret

https://www.selfelected.com/the-tree-reasons-to-use-an-o-rm/
https://dapper-tutorial.net/dapper

Data contracts should be findable / enumerable

January 16th, 2023

The idea is this: There are certain requirements on a data contract; like it being serializable and whatnot.

To verify this automagically the test program must be able to find them.
It can be done through:
1) they are all in the same namespace.
2) their names are all suffixed with “DataContract”
3) they all implement “IDataContract”

Then through reflection/RTTI a test can get all data contracts and verify they are all ok.

Unfortunately Aspnet does not have a way to verify that an endpoint returns a data contract through unit testing; it has to be solved through integration testing or surveillance of production.

Update: I created a dotnet utility for finding all classes decorated with a certain attribute to verify they all had a default constructor. It is called “Constructor.IsDefaultImplemented” and look here to see how to use it in your unit test.

Error message “No process is associated with this object.”

May 17th, 2022

If, when starting your web application/service in Visual studio, you get:

—————————
Microsoft Visual Studio
—————————
No process is associated with this object.
—————————
OK
—————————

Check the output, or try starting in debug mode, and a more ´valuable error messag might pop up.

Better type-ahead in Powershell

May 5th, 2022

1
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete

makes for a better type-ahead like:

To make it autostart, add it to your profile. Here is how to get to it quickly with VSCode:

1
code $profile

Just add the Set-PSReadlineKeyHandler thingy above.

Use IHttpClientFactory (or HttpClientFactory) from a console

April 25th, 2022

IHttpClientFactory is bould to Microsoft’s DI.

So create services and retrieve it.


1
2
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

Honour those who should be honoured.

Health middleware in AspnetCore, or rather Dotnet6 throws TaskCanceledException

January 21st, 2022

I added some health check to my aspnet site to trigger from Kubernetes startupProbe and sometimes got

{
	"EventId": 1,
	"LogLevel": "Error",
	"Category": "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware",
	"Message": "An unhandled exception has occurred while executing the request.",
	"Exception": "System.Threading.Tasks.TaskCanceledException: A task was canceled.    
        at Microsoft.Extensions.Diagnostics.HealthChecks.DefaultHealthCheckService.CheckHealthAsync(Func`2 predicate, CancellationToken cancellationToken)    
        at Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckMiddleware.InvokeAsync(HttpContext httpContext)    
        at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)    
        at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)    
        at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)",
	"State": {
		"Message": "An unhandled exception has occurred while executing the request.",
		"{OriginalFormat}": "An unhandled exception has occurred while executing the request."
	}
}

There is nothing in my health checking code that can throw (famous last words…). In the stack above there is none of my code.

There might be a call to cancel that results in a TaskCanceledException or something with authentication/authorisation as can be seen in the stack.

To make a long story short I moved the calls to UseHealthCheck from below UseEndpoints to above UseAuthentication as my endpoints are anonymous (they are very lightweight).

app.UseRouting();

app.UseHealthChecks("/api/article/health/alive", new HealthCheckOptions
{
    Predicate = check => true
});
app.UseHealthChecks("/api/article/health/ready", new HealthCheckOptions
{
    Predicate = check => true
});
app.UseHealthChecks("/api/article/health/startup", new HealthCheckOptions
{
    Predicate = check => true
});

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

Sanity check, nykterhetstest

October 6th, 2021

In a (unit) test I sometimes add extra tests to check the test tests what is anticipated.

user = new User(Id="A", Name = "N1")
sut.Create(user)
saved = sut.Get("A")

saved.Name.Should.Be("N1", "Sanity check we know what we have stored.")

// Act.
sut.Clear("A")

// Assert.
result = sut.Get("A")
result.Name.Should.Be(null)

Notice the “sanity check” to verify a bug didn’t set Name to null when creating the user.

My naming convention is “Sanity check” or “Nykterhetskontroll” in Swedish.
[I know the translation, word per word, is incorrect.]

Azure devops tests fail with very little clue

September 9th, 2021

I updated some references in my Azure Devops build and got the following error in the unit testing task:

...
##[error]Error: The process '/opt/hostedtoolcache/dotnet/dotnet' failed with exit code 1 
Result Attachments will be stored in LogStore 
Run Attachments will be stored in LogStore 
No Result Found to Publish '/home/vsts/work/_temp/_fv-az101-233_2021-09-09_10_21_12.trx'. 
No Result Found to Publish '/home/vsts/work/_temp/_fv-az101-233_2021-09-09_10_21_17.trx'. 
No Result Found to Publish '/home/vsts/work/_temp/_fv-az101-233_2021-09-09_10_21_24.trx'. 

##[warning].NET 5 has some compatibility issues with older Nuget versions(<=5.7), so if you are using an older Nuget version(and not dotnet cli) to restore, then the dotnet cli commands (e.g. dotnet build) which rely on such restored packages might fail. To mitigate such error, you can either: (1) - Use dotnet cli to restore, (2) - Use Nuget version 5.8 to restore, (3) - Use global.json using an older sdk version(<=3) to build 
Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions. You can learn more about the breaking changes here: https://docs.microsoft.com/en-us/dotnet/core/tools/ and https://docs.microsoft.com/en-us/dotnet/core/compatibility/ . To learn about more such changes and troubleshoot, refer here: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops#troubleshooting 

##[error]Dotnet command failed with non-zero exit code on the following projects : 
Async Command Start: 
Publish test results Publishing test results to test run '1136330'.
...

Especially the last, “Dotnet command failed … on the following projects” does not give the clue I am looking for. What failed?

To cut a long story short: One of my test project lacked reference to Microsoft.NET.Test.Sdk.

A longer story is that I updated from xunit.runner.visualstudio from 2.4.1 to 2.4.3 and it doesn’t have a reference to the Microsoft.Net.Test.Sdk project as it is no longer Visual studio that holds the reference but the project itself. The clues I got were from https://github.com/xunit/visualstudio.xunit/issues/219 and https://github.com/xunit/visualstudio.xunit/issues/259 in no special order.

Error message “Can’t bind to ‘ngIf’ since it isn’t a known property of ‘div'” solved

June 11th, 2021

When testing a component in Angular you might receive the follwoting warning:

Can’t bind to ‘ngIf’ since it isn’t a known property of ‘div’

It might depend on you not declaring the component-under-test.

See this repo.

describe('AppComponent', () => {
   beforeEach(async () => {
     await TestBed.configureTestingModule({
       imports: [
         RouterTestingModule
       ],
       declarations: [
         AppComponent
       ],
     }).compileComponents();
   });
   it('should create the app', () => {
       const fixture = TestBed.createComponent(AppComponent);
       const app = fixture.componentInstance;
       expect(app).toBeTruthy();
     });
 });

The code is slightly different than the boiler plate Angular/Jasmine test code but still visualises the issue.

The row

const fixture = TestBed.createComponent(AppComponent);

Creates a component that must be declared in

declarations: [
  AppComponent
],

It took me an hour to find it due to code being convoluted.
If it saves you 5 minutes, it was worth writing this post.