Posts

Mocking EntityFramework Core DbSet

EntityFramework Core introduces IQueryable<T> extensions for asynchronous DB operations, such as FirstAsync SingleOrDefaultAsync ToArrayAsync The problem is, when you need to mock an IQueryable in a unit test, and the test subject uses one of these new extensions you will get an error The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations The solution can be found on various StackOverflow posts, but these are usually for EF 6, or an older version of EF Core. So here is a solution that works for EntityFramework Core 3.x When mocking services for your test subject, you can return any IEnumerable<T> as long as you use the extension AsAsyncQueryable();     using Microsoft.EntityFrameworkCore.Query.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; u

Tom Lehrer has completed his song The Elements by adding the elements discovered since he first wrote it

Image
I've been developing a chemistry game for learning The Periodic Table. This game features the song The Elements by Tom Lehrer . I've corresponded with Tom a few times via email to seek his permission to use his song / recording in the game. Surprisingly though, the discussion led to something quite unexpected. Whilst discussing the elements discovered since he wrote his song I proposed a specific arrangement for including them into the song. Tom said that for many decades he has been uninterested in adding the elements, and that all proposals to date "do not scan or rhyme". Apparently, mine didn't either, but my version "looks so close to satifactory" that he couldn't resist using it as the basis to completing the song himself.   Here is a screenshot of an email from Mr Lehrer himself.     He doesn't say where to insert the new elements, but my guess would be where he says "I left out one actually" at 55 seconds in his Copenhagen re

Entity Framework Core, SQL Server, and Deadlock victims

The application I am currently working on loads text files, transforms them, and then saves them as relational data. I use Entity Framework Core with SQL Server for my persistence. Unfortunately, when inserting so much data I keep experiencing exceptions because SQL Server is throwing deadlock exceptions and preventing my data from being saved. The insert involves data for 4 related tables, every access to the DB is an insert, which is why I was so surprised to see SQL Server couldn't cope with it - especially as Firebird SQL didn't struggle (nor did PostgreSQL).  It seems that adding OPTION (LOOP JOIN) to the end of SQL Statements prevents this problem, so I wrote an extension to ensure it is appended to Entity Framework Core generated SQL. It is used like so: protected override void OnConfiguring(DbContextOptionsBuilder options) { base.OnConfiguring(options); options.UseLoopJoinQueries(); } and the extension code you need is: public static class UseLoopJoinQueriesExte

Generating globally unique mostly-sequential keys for DB rows across multiple processes

Note: This agorithm was co-authored by Phillipa Berresford. I wanted my domain classes to be able to reference each other by Id without having to add association properties - as I felt having all of this navigation in the model made it messy. I'd much rather have association properties within my aggregates (PurchaseOrder to PurchaseOrderLines) but not elsewhere. This was okay when I needed to add a reference to an object that already existed in the DB, but when I was adding a reference to a new object I needed to know the object's Id before Entity Framework Core saved it to the DB. As my tables were using DB assigned incrementing INT columns this was not possible, so it become obvious I was going to have to switch to GUID Ids. The problem with using GUIDs as clustered primary keys is that GUIDs are designed to be random. Whereas an auto-incrementing INT key will always result in new rows being appended to the end of a table, GUID keys would result in new rows being inserted

Blazor: Scoping services to a component

If you want your Blazor component to have its own dependency injection scope, so you can inject new instances of services and have those services disposed of when the component is disposed, then do the following: First, copy and paste the code below into your application.  Then descend your component from ScopedComponentBase . Finally, decorate your dependency properties with [InjectScoped] rather than [Inject] or @inject . For example @inherits ScopedComponentBase @code { [InjectScoped] private WeatherService MyWeatherService { get; set; } } Here is the code you need using Microsoft.AspNetCore.Components; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace BlazorApp130.Shared { public abstract class ScopedComponentBase : OwningComponentBase<IServiceProvider> { protected override void OnInitialized() { base.OnInitialized(); DependencyInjector.InjectDependencies(

Blazor setTimeout

If you need something like JavaScript's setTimeout in Blazor, you can achieve the same thing with a System.Threading.Timer: The time sponsored by Accurist is @Time private string Time { get; set; } protected override void OnInit() {  var timer = new System.Threading.Timer((_) => {   Time = DateTime.UtcNow.ToString();   InvokeAsync(StateHasChanged);  }, null, 0, 1000);  base.OnInit(); }

Blazor-Fluxor ranked #7 in top 10 Blazor tools!

I was really pleased to see my Blazor library "Fluxor" mentioned in this Visual Studio Magazine article!!!

Review: Rock Your Code: Defensive Programming for Microsoft .NET by David McCarter

Image
I saw a post on Twitter from a guy named David McCarter  promoting his new book.  Rock Your Code: Defensive Programming for Microsoft .NET . I thought the title looked interesting so I bought it. This book (if approximately 50 pages of A5 can count as a book) was packed with bad advice. It is going to be more effort to explain why than the book deserves, but I will do it. TL;DR Source code doesn't compile. When it does, it doesn't do what the author says it does. The author promotes practices long established as poor. Chapter 1: OOP This chapter explains the three pillars of OOP are Encapsulation, Inheritance, and Polymorphism. The author has a tiny 1 or 2 sentence explanation of each. He then goes on to show an example of some poor source code "from a real in production project" (I hope he has permission from the copyright holder). The source code is a single class with lots of public attributes. That's the end of the chapter. Honestly, th

Assigning a piped async result to a variable in an Angular view

If you have an Observable<x> in your component you might find yourself doing something like this {{ ( source$ | async)?.property1 }} {{ ( source$ | async)?.property2 }} This will subscribe to the source$ observable more than once. A commonly used technique to avoid this is to assign the result of the async into a view variable, like so: <ng-container ngif="source$ | async as source">   {{ source?.property1 }}   {{ source?.property2 }} </ng-container> But if you have other UI elements within that ng-container that you want to be displayed whether or not source$ has emitted a value then you might not like the fact that a portion of your UI is excluded until the observable emits a value or when the observable emits a falsey value. If that is the cast, you can try this little trick. <ng-container ngif="(source$ | async) || {} as source">   {{ source.property1 }}   {{ source.property2 }} </ng-container> We utilise *ngIf to a

Implementing a really simple Elvis Operator in TypeScript

Here is a simple routine that implements what is known as the Elvis Operator in TypeScript. In C# you can write code like this Nullable<int> age = person?.BestFriend?.Mother?.CurrentHusband?.Age); If any of the values along the way it will return a null rather than throwing a NullReferenceException. Using the class in my previous blog  Get a Lambda expression as a string  it is possible to achieve the same in TypeScript using the following format const age = elvisOperator(person, x => x.bestFriend.mother.currentHusband.age; It doesn't currently support anything more than simple property access, so you can't access elements in an array for example. import { Expression } from './expression'; export function isUndefinedOrNull(value: any): boolean { return _.isNull(value) || _.isUndefined(value); } export function elvisOperator (instance: TSource, member: (v: TSource) => TResult): any { let path = Expression.pathAsArray(member); let result

A type safe way of creating Angular ReactiveForms and FormGroups

If, like myself, you prefer as many of your coding mistakes to be identified at compile time as possible then you might like the following example. The FormBuilder in Angular expects us to identify our FormControls with a string name. If ever the API of your server changes then of course the names of those controls will also need to change. So, rather than using magic strings when building a FormGroup I wrote this small utility class for building them against a strongly typed class by using lambda expressions. This routine uses a routine I blogged about recently  ( Get lambda expression as a string) Take the following interface as an example of something we wish to edit in a ReactiveForm. interface Address { line1: string; line2: string; city: string; } The code to build the form would look like this this.form = this.expressionFormBuilder .createFormGroup<Address>() .addFormControl(x => x.line1) .addFormControl(x => x.line2) .addFormControl(x

Failed to execute 'send' on 'XMLHttpRequest': Failed to load ng:///DynamicTestModule - Solved (Angular testing)

If when you run your tests you see an error similar to this Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/xxxxxxComponent_Host.ngfactory.js It means something in your component is throwing an exception and the test framework is returning a wrapped exception. To see the actual exception run ng test with -sm=false as a parameter ng test -sm=false This will not only stop your browser from freezing on that test, but will also give you the original error including line number.

Angular - How to create a data aware custom component

Introduction This blog will demonstrate how to create an Angular component that you are able to add [ngModel] [formControl] and [formControlName] attributes to your custom component, and have your component correct implement the features required to work with Angular forms. Setting up the ngModule First add FormsModule and ReactiveFormsModule to your main NgModule's import declaration import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Creating the custom component's template Note: If you have installed @angular/cli using npm you can type ng g component /components/custom-input in a command prompt to create the component + template + test cases. Next create a new component with the following html template My custom input <input (

TypeScript - A polyfill to extend the Object class to add a values property to complement the keys property

I expect you've used Object.keys at some point. Here is how to extend the Object class to add a values property. This kind of thing is useful when you have a lookup of keys where all of the values are the same type, such as the following object you'd expect to see in a Redux app. { "gb": { code: "gb", name: "Great Britain" }, "us": { code: "us", name: "United States" } } The code interface ObjectConstructor { values<T>(source: any): T[]; } /** * Extends the Object class to convert a name:value object to an array of value * @param source * @returns {T[]} */ Object.values = function<T>(source: any): T[] { const result = Object.keys(source) .map(x => source[x]); return result; }

TypeScript - Get a Lambda expression as a string

One of the things I really like about C# is the ability to convert a lambda into a string. It's useful for doing all kinds of things, especially when you are calling a 3rd party library's method that expects a string identifying a member of an object. I saw this was lacking in TypeScript, which was a pain because I wanted to make various parts of my Angular application more compile-time resilient to changes in the server's API model. Using the following code it is possible to take a call like this someObject.doSomething<Person>(x => x.firstName) From there we can get the name of the property referenced in the lamba expression. In fact it will return the entire path after the "x." abstract class Expression { private static readonly pathExtractor = new RegExp('return (.*);'); public static path<T>(name: (t: T) => any) { const match = Expression.pathExtractor.exec(name + ''); if (match == null) { throw new

Angular - How to create composite controls that work with formGroup/formGroupName and ReactiveForms

This blog post will show you how to create composite controls in AngularX that allow you to reuse them across your application using the formGroupName directive to data-bind them. We'll start off with a very basic component that uses a reactive form to edit a person and their address. Editing a person's name and address import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormGroup} from '@angular/forms'; @Component({ selector: 'app-root', template: './app.component.html', }) export class AppComponent implements OnInit { public form: FormGroup; constructor(private formBuilder: FormBuilder) {} ngOnInit(): void { this.form = this.formBuilder.group({ name: 'Person\'s name', address_line1: 'Address line 1', address_line2: 'Address line 2', }); } } <form novalidate [formGroup]="form"> <div> Name <input formControlName="nam

Redux sub-reducer pattern for complex / nested data structures

Image
I love the idea of the Redux pattern, the way all reducers are pure and predictable. I love the way they are effectively listeners that act on event notifications received from a central dispatcher, and I really like the way the whole approach simplifies the application and makes code in my Angular app's components only concerned with view related concerns rather than business logic. However, what I am not a big fan of is the normalised data approach. I've seen it recommended so many times for use with the Redux approach. You essentially have any object (read "row from table on server") in memory once and then everywhere else you hold a reference to the locally stored record/object by its unique ID. So, a view state you receive that looks like this [ { "id": "Emp1024", "name": "Peter Morris", "address": { "id": "123", "street": "xxx" } }, { "id": "Emp4096&qu

Loading an assembly from a specific path, including all sub dependencies

public static class AssemblyLoader { private static readonly ConcurrentDictionary<string, bool> AssemblyDirectories = new ConcurrentDictionary<string, bool>(); static AssemblyLoader() { AssemblyDirectories[GetExecutingAssemblyDirectory()] = true; AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; } public static Assembly LoadWithDependencies(string assemblyPath) { AssemblyDirectories[Path.GetDirectoryName(assemblyPath)] = true; return Assembly.LoadFile(assemblyPath); } private static Assembly ResolveAssembly(object sender, ResolveEventArgs args) { string dependentAssemblyName = args.Name.Split(’,’)[0] + ".dll"; List<string> directoriesToScan = AssemblyDirectories.Keys.ToList(); foreach (string directoryToScan in directoriesToScan) { string dependentAssemb