lördag 30 oktober 2021

Blazor gotcha: Use the @key attribute when visibility of list items can be toggled

Finding the "bug"

We're building a Blazor web from scratch for the first time in a project at work. I like it and we've been able to go pretty fast although it's a new framework for all the devs in the team. But we ran into a strange behavior that looked like a bug.

In the web app a user can add locomotives and wagons to a list to create a train. Each of the vehicles in the list is represented of a header and a body, where the body can be collapsed or expanded.

User input for each vehicle is validated after entry. When a field is invalid a red frame is shown around the field and a validation error message is shown beneath it.

The strange behavior appeared when the body for one vehicle was expanded at the same time as the body for another vehicle was collapsed. When the use entered an invalid value in a field for one of the vehicles, the field for the other vehicle was marked as erroneous!

Reporting the "bug"

I recreated the strange behavior in a minimal project and reported it as a bug in Blazor: Input validation status gets mixed up when toggling content

After a few days I got the reponse:

Thanks for contacting us. It looks like you're missing the @key attribute for the elements which are rendered in a loop. You can learn more about this from https://docs.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-6.0#use-key-to-control-the-preservation-of-elements-and-components

The linked page says: 

The mapping process of elements or components to a collection can be controlled with the @key directive attribute. Use of @key guarantees the preservation of elements or components based on the key's value. 

It can be used like this:

    @foreach (var person in people)
            <Details @key="person" Data="@person.Data" />

Not seen in any material

I dont't remember seeing this in any Blazor material I've studied so far (pluralsight.com and the book "Blazor in Action"), so if you're going to use Blazor and create something with similar behavior, keep this post in mind! :)

fredag 18 juni 2021

Write a ray tracer guided by Jamis Buck's test suite


Having seen people write their own ray tracers, I've been curious about writing my own. And for a while I also believed I just could sit down and write one, without any help, until I tried. At least I failed fast :)

Fast forward a few years to the moment when I listened to the podcast Developer On Fire, where the interviewer asks the interviewee for book recommendations and the book The Ray Tracer Challenge - A Test-Driven Guide to Your First 3D renderer by Jamis Buck is mentioned. I bought it and started coding.

About the book
The book explains the theory you need and contains unit tests in Gherkin, which means that you can translate them to whichever programming language you want to use. 
Here's an example of a test that subtracts a point from another, which should result in a vector:

I used C# and NUnit, which made my test implementation look like this:

The algorithms that make the tests pass are written in pseudocode, so you have to translate them as well.

What I learned
Test first
I really liked the test first way of coding. It catched errors early which made it easier to spot and correct the bugs. It was good to build up a safety net of tests, because the code got pretty math intense and would be pretty hard to debug without them.

Funny / not funny
The fun part was the coding and to see the resulting images. But creating sceneries and trying out different settings was not that fun, which makes it pretty useless to have my own ray tracer to play around with...

Recreational coding
Jamis Buck has also written a book about how to generate mazes, something he did when recovering from a burn out. He's sharing that story in the pod Corecursive.

Examples of created images

Here's two examples of images I created. 

This is supposed to look like falling snowflakes. I made it after learning how to create cylinders and cones and how to group simple shapes together.

The making of a kitchen table

Here's after learning to do cubes and planes and manipulate them, like scaling in different directions, move them and give them color and patterns. Also tried to do a kitchen lamp, but found out that the shadow logic was too simple so that a transparent object shadows as much as an opaque object.

Yes, I had at hard time positioning the table legs :)

The code

It took me quite a while to finish the book. The commit history shows that I began in June 2019 and finished in June 2021. I worked with it in bursts and often had long periods of inactivity.

I skipped the code for matrix manipulation, I used the MathNet.Numerics nuget package instead to faster advance to the chapters that resulted in images.

My github repo for this project.

When searching for The ray tracer challenge at github, I get 254 repo hits in 10 languages, where the most are in Rust (51), C++ (48), C# (32) and Go (17).

After finishing the book I also noticed that people have posted their learning journey on youtube, like this playlist.

söndag 25 april 2021

A SourceTree lover sees Visual Studio catching up


This was supposed to be a post about features that I find important for the daily work I do that the git gui SourceTree has and that Visual Studio's git tool lacks. But instead I learned that Visual Studio is catching up with its Visual Studio 2019 16.10 Preview 2.1 release!

File change preview for historic commits

Navigating the commit history and looking at file changes in Visual Studio is a pain, but today I downloaded Visual Studio 2019 16.10 Preview 2.1 and explored the news in its git tool. Looking at changes in historic commits is no longer a pain!

I also learned that Visual Studio can show diffs as inline or side-by-side.

SourceTree shows all branches in history

In SourceTree you see ALL branches by default, which is the way I like it because I get the full latest commit history context immediately. This isn't possible in Visual Studio, you have to select the branch that has the latest commit to be able to see the history for all branches.

If you ever would like to not see all branches in SourceTree, you can easily turn it off by selecting Current Branch in the dropdown, like this.

To show all branches is a feature under review by Microsoft 

Merges are shown better in SourceTree

I find the branch history tree to be more clear in SourceTree. Compare these two images that pictures a branch branched off of master, and then the branch is merged back to master.

In SourceTree it looks just like that, a branch going out from master and then coming back to master.

In Visual Studio it looks like a branch has been branched off from master, but then it looks like master has been merged to the branch!? When merging, the merge commit has two parents instead of one. There is a primary parent (the branch merged to) and a secondary parent (the branch merged from) and VS seems to mix them up.

I added a ticket regarding this.

But the image below, taken from this ticket hints about a rewrite of the the commit history tree visualization in VS. No merge is shown, but the tree looks different, and hopefully it will be easier to follow.

SourceTree auto-adds commits message for merge with conflicts

When doing a merge and the merge results in conflicts, a commit message like this the one below is added automatically by SourceTree. Visual Studio adds nothing. 
Merged ‘master’ into 'a_feature_branch'. Conflicts: # Foo.h # Bar.cpp

To be able to see which files that have had conflicts can be of help when you know that a feature has been added in a file, but that feature suddenly is gone or is buggy, because it probably disappeared in a manual merge conflict resolution that went wrong.

This also seems to be a feature under review.

In SourceTree you can pull a branch that isn't currently active

Yes, you can, and I thought it was something that made my branch handling smoother, but when writing this I can't come up with a scenario where it is needed.

onsdag 3 mars 2021

E-handla kläder med din digitala tvilling

Att e-handla kläder kan vara svårt, bland annat att gissa vilken storlek som passar bäst. Storleksangivelsen ger en fingervisning, men är långt ifrån en sanning om plagget kommer passa dig, eftersom storlekar kan skilja från tillverkare till tillverkare.

Och om du är osäker på storlek så kanske du beställer flera olika storlekar av samma plagg och skickar tillbaka resten. Det är det många som gör. En himla massa paketskickande blir det totalt, vilket är ett slöseri. 

För att lösa en del av den här problematiken så har Knowit skapat tjänsten Zizr, https://zizr.id/, en tjänst där du kan ange vad du köpt och vilken storlek som passade dig. Utifrån dina köp och en massa andra klädköpares köpdata så kommer Zizr kunna hitta andra som har din storlek och därmed kunna ge storleksrekommendationer på kläder som de andra köpt och angett att de passar. 

Dina digitala kroppsstorlekstvillingar behöver inte vara helkroppstvillingar, utan kan vara delkroppstvillingar, eftersom matchningen delas upp i fötter, underkropp och överkropp.

Det här är en existerande tjänst, dock är den än så länge bara i beta-stadie och har samarbete med endast två butiker, Junkyard och Kleins, men planen är såklart att knyta till sig så många butiker som möjligt.

Jag har skapat konto och skummat de två klädbutikerna. Än så länge har det inte blivit nåt köp, men jag gillar idén skarpt! Konceptet digitala tvillingar känns underutnyttjat, det är ett kraftfullt verktyg som skulle kunna användas för så mycket mer. Men såklart, det är inte helt oproblematiskt med att dela med sig av sin personliga data inom alla områden.

Här kan du titta på en presentation om hela utvecklingsresan av Zizr.