Creating a Car Game in React – Part 3 – Collision

In this, the third post of this series, we’re going to add collision to the game. For a full list of the code, please see here.

If you’re wondering about earlier posts, please start here.

Since we’re introducing collision, we’ll also need to introduce the age old game concept of “Lives”. The premise here is that when you crash into something, you lose a life.

The first step is to add a new state variable to hold the player’s remaining lives:

this.state = {
	playerX: 100,
	playerY: 100,
	windowWidth: 1500,
	windowHeight: 1500,
	playerMomentum: 0,
	playerRotation: 0,
	playerVelocityX: 0,
	playerVelocityY: 0,
	playerLives: 3,
	gameLoopActive: false,
	message: ""
};

If you have a look in the repository, there’s a bit of refactoring, where I’ve taken some of the setState code and separated it into logical functions. I won’t list that here.

Collision Detection

At the end of the game loop, we now have a call to check if we’ve collided with anything:

if (this.detectAnyCollision()) {
	this.PlayerDies(); 
}

The collision detection code is quite straight forward, and is based on the simplistic idea that all objects can be considered rectangles. Whilst this is not precise, it’s sufficient for our purpose:

detectAnyCollision() { 
        const halfWidth = this.spriteWidth / 2;
        const halfHeight = this.spriteHeight / 2;

        let rect1 = {x: this.state.playerX - halfWidth, y: this.state.playerY - halfHeight, 
            width: this.spriteWidth, height: this.spriteHeight}

        if (this.detectOutScreen(rect1)) {
            return true;
        }

        return this.obstacles.some(a => {
            var rect2 = {x: a.props.centreX - halfWidth, y: a.props.centreY - halfHeight, 
                width: this.spriteWidth, height: this.spriteHeight}
            
            if (this.detectCollision(rect1, rect2)) {
                return true;
            } else {
                return false;
            }
        });
}

detectCollision(rect1, rect2) {
	if (rect1.x < rect2.x + rect2.width &&
	rect1.x + rect1.width > rect2.x &&
	rect1.y < rect2.y + rect2.height &&
	rect1.y + rect1.height > rect2.y) {
		return true;
	}
	return false;
}

detectOutScreen(rect1) {
	if (rect1.x < 0 || rect1.x + rect1.width > this.state.windowWidth
	|| rect1.y < 0 || rect1.y + rect1.height > this.state.windowHeight) {
		return true;
	}
	return false;
}

The collision detection code itself was pilfered from here. As you can see, all we’re doing is translating our objects into rectangles, and then seeing if they intersect each other, or if the player has left the game area.

Quick note about forEach and some

I had originally used .forEach for the detectAnyCollision() code. Whilst it would, initially make sense to a C# programmer, in fact the Javascript version of this does exactly what it says on the tin; that is, it executes for each element, and there is no way to exit early!

Player Dies and Score

Now that we have introduced collision, we should consider what to do when it happens. The usual thing in a game is that the player either “dies”, or they lose “health”. Since this is inspired by a spectrum game, we’ll go with “dies”. You saw earlier that we introduced the concept of “lives” and, because it was a spectrum, it has to be 3!

The code to deal with the player death is:

PlayerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		gameLoopActive: true
	});
}

Just a quick reminder that this isn’t a comprehensive listing of code – please see the GitHub repository for that; however, apart from the reduction in lives, the most important thing here is the gameLoopActive code.

The idea here is that we only execute the game loop while this state variable is set; which means we can stop the game loop while we’re dealing with the player’s collision.

The change in the game loop code for this is very simple:

gameLoop() {
	if (!this.state.gameLoopActive) return;

 . . . 

Crashed Car

All well and good, but as it stands, this simply results in the car stopping when it hits a tree, and then being re-positioned. We can address this by adding a small “animation” to indicate a crash. If you have a look here, you’ll see why I’ve won several awards for my graphics*!

In order to plug this in, we’re going to change the car graphic binding:

render() { 
return <div onKeyDown={this.onKeyDown} tabIndex="0">
	<GameStatus Lives={this.state.playerLives} Message={this.state.message}/>
	<Background backgroundImage={backgroundImg}
	windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
	
	<Car carImage={this.state.playerCrashed ? brokenCarImg : carImg} 
	centreX={this.state.playerX} centreY={this.state.playerY} 
	width={this.spriteWidth} height={this.spriteHeight} 
	rotation={this.state.playerRotation} /> 
	
	{this.obstacles} 
</div>
}

So, where the crashed flag is set, we’re binding to brokenCarImg; otherwise to carImg; they are defined at the top:

import carImg from '../Assets/Car.png';
import brokenCarImg from '../Assets/Crash.png';

We also split the playerDies() function into two:

playerDying(tillDeath) {
	this.setState({
		playerCrashed: true,
		gameLoopActive: false
	});
	this.stopCar();
	setTimeout(this.playerDies.bind(this), tillDeath);
}

playerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		playerCrashed: false,
		gameLoopActive: true
	});
}

All we’re doing here is calling the first function, which effectively just changes the image and then calls the second function on a timeout. Again, don’t forget the `.bind()` when you call timeout, otherwise, you won’t be able to access `this`!

Footnotes

* I haven’t actually won any awards for graphics – I had you fooled, though!

References

https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection

https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650

https://medium.com/@benjamincherion/how-to-break-an-array-in-javascript-6d3a55bd06f6

Creating a Car Game in React – Part 2 – Steering and Obstacles

In the second part of this series, we’re going to add some steering to our car, and introduce a concept of obstacles. If you’re wondering what this is the second part of, please start here.

The GitHub repo for this post can be found here.

In the first post of the series, we added a car, and allowed the user to move it around the screen in a very crude fashion; here, we’re going to change the controls to feel a little more like a car. As with the previous post, not every single change will be here, but it will be in the GitHub repo above.

Steering and Acceleration

Let’s have a look at the controls in the Game component:

onKeyDown now looks a little different:

onKeyDown(e) {
	switch (e.which) {
		case 37: // Left
			this.playerSteer(-10);
			break;
		case 38: // Up
			this.playerAccelerate(0.3);
			break;
		case 39: // Right
			this.playerSteer(10);
			break;
		case 40: // Down
			this.playerDecelerate(-0.5);
			break;
		default:
			break;
	}
} 

So, we’re no longer simply repositioning the car, but applying forces to it. Initially, I had Down as simply a negative acceleration, meaning that if you break too hard, you go backwards! Here’s the three functions referenced above:

playerAccelerate(speed) {
	this.setState({
		playerMomentum: this.state.playerMomentum + speed
	});
}

playerDecelerate(speed) {
	if (this.state.playerMomentum > 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum + speed
		});
	} else if (this.state.playerMomentum < 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum - speed
		});
	}

}

playerSteer(direction) {
	this.setState({
		playerRotation: this.state.playerRotation + direction
	});
}

There are a number of new state variables, which I won’t list here. However, because we are no longer repositioning the car based on the user action, we need to apply the forces that we are changing; that is, we need a game loop.

Game Loop

The game loop code is relatively complex. Looking at this should make you seriously consider using a a game engine of some description:

gameLoop() { 
	const radians = (this.state.playerRotation - 90) * Math.PI / 180; 
	const aX = (this.state.playerMomentum * Math.cos(radians));
	const aY = (this.state.playerMomentum * Math.sin(radians));
	const velocityX = this.state.playerVelocityX;
	const velocityY = this.state.playerVelocityY;
	const velocitySq = Math.pow(velocityX, 2) + Math.pow(velocityY, 2);
	const posSq = Math.pow(aX, 2) + Math.pow(aY, 2);
	const velocityPosSq = Math.pow(velocityX * aX + velocityY * aY, 2);
	let skidFactor = (posSq == 0 || velocitySq == 0) ? 0 : 1 - (velocityPosSq / posSq / velocitySq);
	
	if (skidFactor <= 0) skidFactor = 0; 
	
	this.setState({
		playerVelocityX: (skidFactor * velocityX) + ((1 - skidFactor) * aX),
		playerVelocityY: (skidFactor * velocityY) + ((1 - skidFactor) * aY)
	}); 
	this.playerMove(
		this.state.playerX + this.state.playerVelocityX,
		this.state.playerY + this.state.playerVelocityY 
	);
	this.playerDecelerate(-(0.1 + skidFactor));
}

If you’re wondering where this brain-melting maths comes from, have a look here.

I’ve split it up in an effort to make it slightly more understandable, but the premise is that if you’re travelling fast and change direction suddenly, it doesn’t immediately turn. Again, if you’re thinking you don’t want to be messing around with this kind of thing then a lot of game engines take care of this for you.

Obstacles

Finally, we have our obstacles. There is no collision just yet, but this basically puts pictures of trees around the screen (incidentally, I did all the artwork myself, which I assume the reader to be suitably impressed by!) We’ll come back to this later to make the collision work:

buildObstacles() {
	let obstacles = [];
	const obstacleCount = Math.floor(Math.random() * 10) + 1;
	console.log('Obstacle count ' + obstacleCount);
	for (let i = 1; i <= obstacleCount; i++) {
		const centreX = Math.floor(Math.random() * this.state.windowWidth) + 1;
		const centreY = Math.floor(Math.random() * this.state.windowHeight) + 1;
		
		obstacles.push(<Obstacle key={i} image={treeImg} centreX={centreX} centreY={centreY} width={this.spriteWidth} height={this.spriteHeight} />);
	}
	return obstacles;
}

All this function does is build up an array of HTML; we then feed that into a class variable in the constructor:

constructor(props) {
	super(props);
	document.body.style.overflow = "hidden";
	this.state = {
		playerX: 100,
		playerY: 100,
		windowWidth: 1500,
		windowHeight: 1500,
		playerMomentum: 0,
		playerRotation: 0,
		playerVelocityX: 0,
		playerVelocityY: 0
	};
	this.spriteWidth = 25;
	this.spriteHeight = 25;
	this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
	this.onKeyDown = this.onKeyDown.bind(this); 
	this.obstacles = this.buildObstacles(); 
}

(It’s worth noting, as an aside, that we are preventing scrolling here by setting document.body.style.overflow)

Finally, we’ll display it in the render method:

render() { 
	return <div onKeyDown={this.onKeyDown} tabIndex="0">
		<Background backgroundImage={backgroundImg}
		windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
		
		<Car carImage={carImg} centreX={this.state.playerX} 
		centreY={this.state.playerY} width={this.spriteWidth}
		height={this.spriteHeight} rotation={this.state.playerRotation} /> 
		
		{this.obstacles} 
	</div>
}

This technique allows you to build an array of HTML objects dynamically. The thing to notice here is the ‘key’ that we’re passing through; if you don’t pass this, you’ll start getting the following error:

Each child in a list should have a unique “key” prop.

In the next post, we’ll introduce collision.

References

https://stackoverflow.com/questions/5192983/calculating-x-y-movement-based-on-rotation-angle

https://gamedev.stackexchange.com/questions/172571/how-to-implement-a-slight-skid-in-a-car-game

https://stackoverflow.com/questions/39962757/prevent-scrolling-using-css-on-react-rendered-components

Creating a Car Game in React – Part 1 – Drawing and Moving

Since I started looking at React, I’ve wondered whether it would be possible to create a multi-user game. The game would look a little like a Spectrum game that I used to play called: Trans-Am. I’m guessing most people reading this are not going to be old enough to remember this. Essentially, it marks the peak of car game development, and everything has been down hill ever since.

If you have no idea what I’m talking about then there’s a demo of the game here.

I’m not going to try and emulate this exactly, I thought I’d use it as a basis to make a multi-player car game.

The GitHub repository for this post can be found here.

Create a React Application

We’ll start by creating a new React Application (see here for details):

Now we have the application, we’ll need some game assets. If you want to use the same assets as me then feel free to pull my repository. However, at this stage, all you’ll need is a square box and a green screen.

Game Layout

The next stage is to design the game layout; because this is React, we’ll start with App.js. We’ll delegate all of our game logic to a component called Game:

import React from 'react';
import './App.css';
import Game from './Components/Game';
function App() {
	return (
		<div className="App">
			<Game />
		</div>
		);
}
export default App;

If you want to see, comprehensively what Game.Jsx looks like, then have a look at the latest version on GitHub. However, some of the highlights are the render method:

render() { 
	return <div onKeyDown={this.onKeyDown} tabIndex="0">
		<Background backgroundImage={backgroundImg}
		windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
	<Car carImage={carImg} centreX={this.state.playerX} 
		centreY={this.state.playerY} width={this.playerWidth}
		height={this.playerHeight} /> 
	</div>
}

This will probably change as to game progresses, but at the minute, it just renders to two constituent components. We’re also responding to KeyDown here, so let’s have a look at onKeyDown:

onKeyDown(e) {
	switch (e.which) {
		case 37: // Left
			this.playerMove(this.state.playerX - this.SPEED, this.state.playerY); 
			break;
		case 38: // Up
			this.playerMove(this.state.playerX, this.state.playerY - this.SPEED);
			break;
		case 39: // Right
			this.playerMove(this.state.playerX + this.SPEED, this.state.playerY); 
			break;
		case 40: // Down
			this.playerMove(this.state.playerX, this.state.playerY + this.SPEED);
			break;
		default:
			break;
	}
} 

playerMove(x, y) {
	this.setState({
		playerX: x,
		playerY: y
	}); 
}

We’re storing the players position in state; as I detailed here, this enables us to update the state and have React update the screen as it detects a change in the Virtual DOM.

Game Components

In an effort to stay as close as possible to React’s preferred architecture, the components of the game (the background and the cars for now) will be, well, components. Background is easy:

import React from 'react';
function Background(props) {
	const bgStyle = { 
		width: `calc(${props.windowWidth}px)`, 
		height: `calc(${props.windowHeight}px)`, 
		top: 0,
		left: 0,
		position: 'absolute' 
	};
	return (
		<img src={props.backgroundImage} style={bgStyle} />
	);
}
export default Background;

We’re basically just displaying an image here. One thing that’s worth noting is that the windowWidth and windowHeight are properties, not state. They do exist as state in the Game component and, when they change, are updated there, and so updated here. The React guys call this Lifting State.

The car component is exactly the same idea:

import React from 'react';
function Car(props) {
	const left = Math.round(props.centreX - (props.width / 2));
	const top = Math.round(props.centreY - (props.height / 2));
	const carStyle = { 
		width: `calc(${props.width}px)`, 
		height: `calc(${props.height}px)`, 
		top: `calc(${top}px)`,
		left: `calc(${left}px)`, 
		position: 'absolute',
		zIndex: 1 
	};
	return (
		<img src={props.carImage} style={carStyle} />
	);
}
export default Car;

There are a number of advantages to this idea of maintaining the state in a higher component; for example, this way, you can share a single state between components; however, the biggest advantage for us is that, while the components are, effectively, intelligent sprites, you can easily create an “EnemyCar” version of the Car component.

It’s worth bearing in mind that, because the position of the car doesn’t exist in this component as state, we wouldn’t be able to change it here, even if we wanted to. The strategy to get around this is to have an update function passed in as a property (effectively a function pointer that you can call from within the child component).

In the next post, I’m going to update the movement so it’s a little more car-like, and introduce some obstacles.

References

https://reactjs.org/docs/components-and-props.html

https://stackoverflow.com/questions/43503964/onkeydown-event-not-working-on-divs-in-react

https://stackoverflow.com/questions/37440408/how-to-detect-esc-key-press-in-react-and-how-to-handle-it/46123962

https://reactjs.org/docs/lifting-state-up.html

https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs

Casting a C# Object From its Parent

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

[Fact]
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.

A C# Developer’s Guide to: ReactJS – Part 3 – Conditionally Rendering HTML in React

This is the third in a series of posts on interesting things I’ve discovered about React; the first of these can be found here.

One of the things that tripped me up early on while I was learning React (not that I’m a fully-fledged expert now or anything) was how to display HTML elements based on a given criteria. For example, say you only want to display a label while the form is loading, or you want to display a message based on other information on the screen.

If you were using a desktop binding architecture, say MVVM, you would bind the visibility to a visible property. Likewise in HTML, you may have a conditional style based on the bound model property. Let’s see how you might do that in React.

Create a new React Application

Let’s start by creating a new React application (using bash here):

This isn’t a particularly fast process, so maybe it’s time to get a brew.

Once it’s done, and assuming you have VS Code installed (if you don’t then go and install it from here), type:

code testreactapp

And as if by magic, VS Code appears!

You should be able to run this straight out of the box. Start a new terminal in VS Code, and type npm start:

The displayed screen is of a little animated spiragraph. Let’s add a button and, where the user presses the button, hide or show the spinning spiragraph.

State

As I have previously written about here state is one of the key concepts in React. Let’s create a state object that will determine the visibility of our animation.

In order to introduce state, we need to change the default app.js to be a class, as functions cannot have state. Note that, were this a real application, you would probably move this out into a separate component; but let’s change our app.js to be a class:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

export default class App extends Component {
	render() {
		return (
			<div className="App">
				<header className="App-header">
					<img src={logo} className="App-logo" alt="logo" />
					<p>
						Edit <code>src/App.js</code> and save to reload.
					</p>
					<a
					className="App-link"
					href="https://reactjs.org"
					target="_blank"
					rel="noopener noreferrer"
					>
						Learn React
					</a>
				</header>
			</div>
		);
	}
}

All I’ve done here is change the function to a class, and added `import {Component}`.

Now let’s add some state. At the top of the class, add a constructor:

constructor(props) {
	super(props)
	this.state = {
		showSpiragraph: true
	}
}

Let’s now add the button, so we can change the value of the state; first, we’ll need the button itself:

. . .
	<a
		className="App-link"
		href="https://reactjs.org"
		target="_blank"
		rel="noopener noreferrer"
	>
		Learn React
	</a>
	<button onClick={this.toggleShow}>Hide/Show</button>
</header>
. . .

Then the function that we’re calling (toggleShow):

toggleShow = () => {
  this.setState(state => ({showSpiragraph: !state.showSpiragraph}));
}

If you run this now, it will allow you to press the button until your finger aches, but it won’t actually do anything.

Conditionally Displaying an Element

Okay, so we come to the crux of the entire post; we can conditionally render our image by using the following syntax:

. . .
<header className="App-header">
  {this.state.showSpiragraph &&
    <img src={logo} className="App-logo" alt="logo" />
  }
. . .

You should now be able to click the button and have the Spiragraph show and hide at will.

References

https://medium.freecodecamp.org/quick-guide-to-understanding-and-creating-reactjs-apps-8457ee8f7123

https://reactjs.org/docs/handling-events.html

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.

References

https://dejanstojanovic.net/aspnet/2018/november/mocking-iconfiguration-getvalue-extension-methods-in-unit-test/

Adventures in C#8 – The annotation for nullable reference types should only be used in code within a ‘#nullable’ context.

If you’re playing around with C# 8, and have been for a while, you may spot this message when using nullable reference types:

Warning CS8632 The annotation for nullable reference types should only be used in code within a ‘#nullable’ context.

There’s a couple of things you can check to fix this; the first is to check that you are, in fact, using C# 8. It’s likely that you are, because there is a separate error if you are not, but just for my own benefit:

<LangVersion>preview</LangVersion>

The next, and more likely step, is that you’re using the previous declaration for Nullable Reference Types; it used to look like this:

<NullableReferenceTypes>true</NullableReferenceTypes>

But no more! Now it looks like this:

<NullableContextOptions>enable</NullableContextOptions>

And, as if by magic – the error disappears!

But why? Well, it looks like they are making the setting more nuanced than simply on or off.

Update (8/7/2019)

It appears that the NullableContextOptions is now simply: Nullable; e.g.:

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>

Working out when something broke using Git Bisect and Git Log

On 5th Feb, I attended DDD North. There were many excellent talks on the day, but in this post, I’m delving into something that I saw in one of the grok talks (I gave one myself). It concerns a feature of git that I’d never heard about until then, and it’s proved to be enormously useful. This post is, as all of my posts are, really for myself.

Something has broken

You’re giving the app a quick test, and suddenly you realise that something in the application has stopped working (or maybe it’s started, but it shouldn’t have). You remember that two days ago, this particular thing was working fine. This post is going to cover manually using git bisect to determine when your code was broken.

Get the good commit

To use git bisect, you need a good commit and a bad commit. Obviously, git doesn’t know what’s good or bad, so you could use it to determine when something was changed, added, or removed. Providing the behaviour is different, you can identify it.

If you know the date of the ‘good’ commit, you can ask git for the logs after that date. To list commits after a given date:

git log --after="2019-03-19T00:00:00-00:00"

This will give you all the commits (you can add a ‘–before’, too if you’re dealing with a long time ago. When you get the git Commit Id, make a note of it; for example:

Bc1afa359dc98b899cc4194ec8130a6229643172

Let’s do some bisecting

You start the bisect process by:

git bisect start

At all times through this process, git does precisely nothing to help you along, so if you even get an acknowledgement of your command you should consider yourself lucky!

The next step is to tell git that the current release is bad:

git bisect bad

You can give it a commit here that isn’t the current release, if you so choose.

The final step to start the process is to tell it where to start – i.e. what was the last known good release. This is your commit Id from earlier:

git bisect good Bc1afa359dc98b899cc4194ec8130a6229643172

What git does here is a binary chop. So the first code it will check out will be halfway between the two commits. It then tells you nothing (as usual). Now that it’s checked out the code for you, run your application with the code and see whether it is ‘good’ or ‘bad’. Once you’ve determined that, go back to git and tell it:

git bisect good

Or:

git bisect bad

Each time you tell it it’s good or bad, it will check out new code, and you need to test again:

(apologies for all the redacting)

Finally, it will determine which commit was the first bad one, and report back:

$ git bisect bad
Eea8e3d72fcb26cdebb2dbf2c13fdd88d7f3782a is the first bad commit
commit Eea8e3d72fcb26cdebb2dbf2c13fdd88d7f3782a
Author: Ian Kilmister <[email protected]>
Date:   Wed Mar 20 11:49:18 2019 +0100

    New lyrics

Once you’re done, you need to reset – this will book out the code you had out before you started:

git bisect reset

Read a Document in a .Net Core Application Baked into the Project File

This isn’t a difficult thing to achieve, but it is one that frequently has me reaching for Google to get the exact syntax. By creating this post (I create all my posts on OneNote first), it’s now offline for me.

There’s more than one way to do this; I’ve covered two. All the examples here are using a CSV file from an Assets folder:

Embedded Resource

These are embedded into the compiled assembly; which means in order to change them, you would need to recompile your code. This works well for images, but less well for data files.

First, you need to add your resource to your project, and set the properties to be an embedded resource:

Because it’s embedded, copying makes no sense. To read the file:

public string GetResourceTextFile(string filename)
{
    using Stream stream = this.GetType().Assembly.
                       GetManifestResourceStream($"SalesOrder.Generate.{filename}");
    using StreamReader sr = new StreamReader(stream);                           
            
    return sr.ReadToEnd();
}

Content

This allows you to include a file within your project; however, content files are not compiled. Combined with the “Copy To Output Directory” they place files in the binary directory of your project. The advantage here is that you can change this file after compilation:

Because this just copies the file to the executing directory, it’s easier to read the file:

public string GetContentTextFile(string filename)
{
    return File.ReadAllText($"Assets/{filename}");
}

References

https://stackoverflow.com/questions/145752/what-are-the-various-build-action-settings-in-visual-studio-project-properties