Reinstalling macOS

reinstalling-macos

I reinstalled macOS on my MacBook Pro M1 at the start of the summer. I was hoping to use nix-darwin to manage it, but just couldn’t get on with it, so I’m going back to using Homebrew. This series of blog posts is an aide-memoire, in case I have to reinstall everything again.

» read more

Callouts in Hugo

hugo

In replacing Jekyll with Astro, and then with Hugo, I’ve had to re-implement callouts and alerts a number of times. For Hugo, I’m using shortcodes. Here’s what the callouts look like.

» read more

Alerts in Hugo

hugo

In replacing Jekyll with Astro, and then with Hugo, I’ve had to re-implement callouts and alerts a number of times. For Hugo, I’m using shortcodes. Here’s what the alerts look like.

» read more

Timelapse Lego Builds

lego

I have a few timelapse Lego build videos on my YouTube channel. This post explains how that’s set up. It’s mostly to remind myself for next time.

» read more

Synology Router .dss file: What is it?

synology-srm

I’m considering monkeying around with the firewall rules on my Synology router. If I mess that up, I’ll need to factory-reset the router. So I should probably back up the current configuration first. The Back Up Configuration button downloads a SynologyRouter_YYYYMMDD.dss file. What’s in it?

» read more

docker build without a Dockerfile

docker

I recently wanted to create an Ubuntu container image with some extra stuff installed, but I couldn’t be bothered to create a Dockerfile. It turns out that docker has a docker container commit command, so I used that. Here’s how.

» read more

Using docker with macvlan

docker

If you use the bridge or host network drivers in Docker, containers must use different port numbers to be accessible on the host network. Here’s how to use the macvlan driver to assign a unique IP address to each container, allowing containers (and the host) to use the same port numbers.

» read more

Helpers for fold accumulators

erlang

On whether “fold accumulator helpers” are a good idea.

I’m currently writing some code that recursively folds over a multi-level data structure, and I found myself wondering whether introducing helper functions specifically to abstract over the accumulator are a good idea.

» read more

Exporting SNMP metrics to Prometheus

My DS416play keeps falling off the network, requiring a hard reset. I wondered whether it was possible to monitor it somehow. It turns out that it responds to SNMP queries, so here’s my attempt to export all of that into Grafana.

» read more

Improving your quality of life as a developer

I’ve just come off a call with a colleague and while he was sharing his screen and we were walking through some things, I noticed that his setup is missing all of the little “quality of life” tweaks that I’ve made over the years.

» read more

SSH Forwarding in Docker

docker

If you’re building your application inside a Docker container, and you need to pull dependencies from a git server (e.g. Github or Gitlab) using SSH, you need to forward your SSH session to the container.

» read more

gen_server debug options

erlang

Erlang’s gen_server (and gen_statem, etc.) allow for you to pass {debug, DebugOptions} in gen_server:start_link/4 (et al.). The documentation for it is spread over several pages, making it hard to understand at first. How should we use it?

» read more

Installing Tempo

I want to play with OpenTelemetry, so I figured I’d install Grafana’s Tempo in my cluster. I’m going to use ArgoCD to install the Helm chart.

» read more

Erlang: via

erlang

Here’s how you can use via in a name specification when starting a gen_server (or gen_statem, etc.) to register your process with a process registry.

» read more

Upgrading gitea

kubernetes gitea

I’m running Gitea and ArgoCD on my K3s cluster, for some GitOps goodness. I noticed that Gitea 1.19.0 recently came out, with some features I want to try, such as Gitea Actions. Since I’m running 1.17.4, it’s time to upgrade.

» read more

Exporting variables from scripts

Often, when you’re doing something in an interactive shell, you’d like to set an environment variable from a script. But you can’t, because scripts run as their own process, which means that they can’t set environment variables in their parent (the shell). How do we get around that?

» read more

Using socat to strip HTTPS

I’m trying to figure out how kubectl does its thing. Because it uses HTTPS to talk to the API server, I can’t use Wireshark to look at the traffic. Here’s how I used socat to snoop on the traffic.

» read more

Simple log colouring in Erlang

erlang

By default, the improved logger originally introduced in Erlang/OTP-21 doesn’t support per-level colours. This is something that I miss from lager and from Elixir’s Logger. Here’s a simple way to implement something like lager.

» read more

Building Erlang/OTP

erlang

There’s more comprehensive information in various files in the HOWTO directory, but ain’t nobody got time for that. This works for me.

» read more

Forking Erlang/OTP

erlang

Some notes about hacking on and contributing to Erlang, because I don’t do it frequently enough to have all of this in muscle memory.

» read more

Erlang application versioning

erlang rebar3

When you’re investigating a problem with a deployed application, it’s useful to know precisely which version you’re looking at. Here’s how to automatically set the version number in an Erlang project.

» read more

Rebar3 Umbrella Projects

erlang rebar3

Some notes about using rebar3 with an umbrella project.

rebar3 new umbrella name=foo      # umbrella and release are aliases
cd umbrella/
cd apps/
rebar3 new app name=bar
rebar3 new lib name=baz

It doesn’t set up the application dependencies (because it can’t know what you mean to do), so you’ll need to do that yourself. Edit apps/foo/src/foo.app.src:

» read more

Erlang clustering recap

erlang

I want to write a post about using mutual TLS to secure Erlang distribution (clustering), with auto-provisioning of certificates when running in Kubernetes. This is not that post. This is a recap of basic Erlang clustering, to refresh my memory and lay some groundwork.

» read more

Monitoring temperatures with telegraf

telegraf

One of my NUCs keeps hanging, and I suspect temperature. I wanted to use collectd to gather the temperature sensor values, but it was removed from Ubuntu 22.04. Instead, I’m going to see if I can get telegraf to do it instead.

» read more

Pod DNS Problems

I’ve got an extra instance of CoreDNS running in my cluster, serving *.k3s.differentpla.net, with LoadBalancer and Ingress names registered in it, and it’s working fine for queries to the cluster. It’s not working fine for queries inside the cluster. What’s up with that?

» read more

Traefik Ingress

I’m in the middle of installing ArgoCD (blog post will appear later). Rather than use up another LoadBalancer IP address for it (and mess around with TLS), let’s talk about using an Ingress. It’s entirely possible that I can convert the previously-installed docker registry and Gitea to use one as well.

» read more

Colouring the 'iex' prompt

elixir

If you’ve got separate dev, test and prod environments, it can help to use colour to tell you which one you’re logged into. Here’s how to colour the iex prompt appropriately.

» read more

Upgrading k3s

k3s k3s
The Rancher docs say that you should update the server first, then the workers.

Control Plane

This is a non-HA cluster (I’ve only got one server node), and kubectl drain rpi401 (the server) doesn’t want to evict pods with local storage. So I guess I just apply the upgrade and hope that it recovers after a restart:

» read more

k3s on Raspberry Pi: Persistent Volume Namespaces

k3s raspberry-pi k3s

Persistent Volume Claims are namespace-scoped. Persistent Volumes are not:

$ kubectl get pvc
NAME              STATUS   VOLUME           CAPACITY   ACCESS MODES   STORAGECLASS   AGE
testing-vol-pvc   Bound    testing-vol-pv   1Gi        RWO            iscsi          27h

$ kubectl --namespace docker-registry  get pvc
NAME                  STATUS   VOLUME               CAPACITY   ACCESS MODES   STORAGECLASS   AGE
docker-registry-pvc   Bound    docker-registry-pv   1Gi        RWO            iscsi          23h

$ kubectl get pv
NAME                 CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                                 STORAGECLASS   REASON   AGE
testing-vol-pv       1Gi        RWO            Retain           Bound    default/testing-vol-pvc               iscsi                   27h
docker-registry-pv   1Gi        RWO            Retain           Bound    docker-registry/docker-registry-pvc   iscsi                   23h
» read more

git start

git

When I create a new git repository, I prefer for there to be an empty commit at the beginning of history.

» read more

Multiple Laptops, Multiple Monitors

At home, I’ve got a rather nice setup with two Dell U2520D monitors on my desk, which I’m currently using from my (work) Linux desktop. However, more recently, I’m trying to strike a better work/life balance, so I’ve decided to start making more use of my (personal) Microsoft Surface Book 3 laptop, but I’d like to continue using the two monitors (which are also mine; I never bothered filing the expense claim).

» read more

failed to start child: :ranch_server_proxy

elixir ranch
** (Mix) Could not start application example_server: ExampleServer.Application.start(:normal, []) returned an error: shutdown: failed to start child: {:ranch_embedded_sup, :example_server}
    ** (EXIT) shutdown: failed to start child: :ranch_server_proxy
        ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started

Did you start the ranch application? If you’re using rebar3 (Erlang) or mix (Elixir), it ought to start automatically as part of your application.

» read more

ALPN in Erlang

erlang

Per Wikipedia:

Application-Layer Protocol Negotiation (ALPN) is a Transport Layer Security (TLS) extension that allows the application layer to negotiate which protocol should be performed over a secure connection in a manner that avoids additional round trips and which is independent of the application-layer protocols.

» read more

Gnome Extensions

ubuntu ubuntu-install

I installed the following extensions:

Windows-style taskbar

  • Hide top bar. This extension didn’t seem to do anything.
  • Dash to panel. This replaces the top bar with a Windows-style task bar. I haven’t figured out to stop it from hiding under maximised windows, though. This is annoying.
  • Dash to dock. This allows me to have a taskbar on my second monitor. I configured it to “Show the dock on: Secondary monitor 1”, at the bottom. Turn off “Show favourite applications”. Turn on “Isolate monitors”. Turn off “Show Applications icon”.

“Dash to panel” and “Dash to dock” aren’t quite the same size, but I’ll live with it.

» read more

Installing an mSATA disk in an empeg

empeg

Background

The hard disk in my spare empeg player (“toothgnip”) died at some point. I’m using a 64GiB Transcend 2.5" PATA SSDs in my main empeg player (“crowley”), but they’re getting harder and harder to find, so I opted for a Kingston mSATA disk (240G) and a JMicron-based mSATA to PATA adapter.

» read more

Getting Erlang version

Use this helper function:

erlang_version() {
    erl -eval '
        {ok, Version} = file:read_file(
                            filename:join(
                                [code:root_dir(),
                                 "releases",
                                 erlang:system_info(otp_release),
                                 "OTP_VERSION"])),
        io:format("Erlang/OTP ~s", [Version]),
        halt().' -noshell
}
Note that this only works when you run erl; it doesn’t work in a released application.
» read more

Rebuilding kerl Installations

kerl erlang

If kerl list installations is displaying Erlang installations that you deleted ages ago, and you’ve got all of your installations in ~/.kerl/erlangs/, you can rebuild the list by running the following command:

» read more

jq reduce

jq

I found myself having to process a large JSON file using jq --slurp, and it was using up a lot of memory, so I thought it was time to learn about jq’s reduce function.

» read more

git rebase tips

git

This is an internal email I wrote almost exactly 2 years ago. I had to refer to it today, and I figured that it bears sharing publicly.

» read more

Running Chromium as a Dashboard

On my desk I have a dashboard (an “information radiator”) that displays various useful things, such as the build status of various Jenkins jobs, clocks showing important timezones (Electric Imp is a distributed company), and so on.

» read more

Reverting Erlang 17

We’ve found a couple of problems with Erlang R16 that mean that one of our projects requires Erlang 17. Conversely, we’ve found a couple of problems with Erlang 17 that mean that one of our other projects should stick with Erlang R16.

» read more

Using kerl with direnv

kerl direnv erlang

kerl allows you to easily build and install multiple Erlang/OTP releases. It’s kinda like nvm or rvm, but for Erlang. It doesn’t do everything, and that’s what direnv is for. direnv allows you to run commands upon entering or leaving a particular directory.

» read more

epgsql: invalid_password

I’m writing a simple web application in Erlang that uses epgsql to talk to a PostgreSQL database. I keep getting invalid_password, despite the fact that the user doesn’t have a password (and I’m passing “”). I can also log in by using psql -U foo.

» read more

On caching

Background

There’s a quote:

“There are only two hard problems in Computer Science: cache invalidation and naming things.”

– Phil Karlton

» read more

vim, syntastic, .jshintrc

vim

I’ve been using Syntastic for a while now. It’s awesome.

One thing it’s missing, however, is the ability to automatically find an appropriate .jshintrc file for the file you’re editing.

» read more

gen_fsm learnings, part 3

erlang gen_fsm

Some odds and ends.

handle_info information

The last of the “I don’t know what this is for” functions is handle_info. This is documented as being called for messages that aren’t events or system messages.

» read more

Lego Storage

lego

My son has quite a lot of Lego, but he stopped playing with it. It turns out that he gets frustrated when he can’t find a particular piece. So we started exploring storage options.

» read more

Phones I have owned

Apropos of a discussion on Facebook earlier today:

  • Motorola MR20
  • Motorola Startac
  • Motorola (blue thing)
  • Nokia 8310
  • Nokia 6230
  • HTC Desire
  • Samsung Galaxy S3
» read more

Failed to load data access DLL

While attempting to debug a crash dump from a .NET 4.0 RTM process on my (.NET 4.5), I got the dreaded Failed to load data access DLL, 0x80004005 error message.

» read more

Packaging vs-welcome-page

Next problem: packaging the vs-welcome-page extension.

How to get the web application installed with the VS package? There doesn’t appear to be an easy way to add arbitrary files to a VSIX package. You can do it by adding references to dependencies, but that doesn’t help with the content (CSS, HTML files, etc).

» read more

Spike: Providing parameters to IIS Express-hosted applications

An aside: We need to be able to support multiple instances of our small web application (because you might have more than one instance of Visual Studio open). If we host our application in IIS Express (and remember that we’re doing this to avoid messing around with URL ACLs), we either need to duplicate the whole thing for each site, or figure out a way to provide it with parameters.

» read more

Finding IIS Worker Processes

powershell iis

How do we find out if there’s a worker process for an application pool? Note that there can be more than one worker process for each application pool. Note also that a worker process can host multiple web applications.

» read more

The case of the missing print jobs

Having recently moved my home server (Windows 2012) from the hall cupboard to the corner of my study, I decided to connect it to my printer. This means that I can print from my laptop over wireless without needing to turn on the desktop PC that the printer was originally connected to.

» read more

PowerShell and enums

powershell

PowerShell has a really cool feature where it’ll coerce a string into an enum value. I’ll demonstrate by exporting a certificate from the Windows certificate store:

» read more

Acer Aspire S7 and Secure Boot

I just bought myself a shiny new Acer Aspire S7-391, with a view towards nuking Windows 8 and to install Linux Mint on it. Stupidly, I didn’t consider that Windows 8 logo certification now requires a UEFI BIOS and Secure Boot.

» read more

Installing Windows 8 Pro on Acer Aspire S7

  1. Make sure that the ISO file you’ve downloaded is not corrupt – this caused me a bunch of grief.
  2. Format a bootable USB stick as FAT32.
  3. Mount the ISO.
  4. Copy the files from the ISO to the USB stick.
  5. In the Acer’s BIOS, select UEFI; enable F12 boot menu.
  6. Restart the Acer.
  7. Press Fn-= (F12).
  8. Select the USB stick.
  9. Add the Intel drivers.
  10. Continue with the installation.

Note that the 128GB SDD is two 64GB SSD drives configured as RAID0. You’ll need the Intel RAID drivers.

» read more

Logging Learnings

I’ve just spent the bulk of the morning attempting to understand a bug by reading through some fairly large log files. Because of that, I’ve come to some realisations about log files and logging.

» read more

Reliable Sessions and HTTPS don't mix

System.InvalidOperationException: Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP.

» read more

PROCESSOR_ARCHITEW6432

What’s the PROCESSOR_ARCHITEW6432 environment variable for?

If you’re on 64-bit Windows, you’ll see that you have a PROCESSOR_ARCHITECTURE environment variable:

» read more

Hyper-V Remote Management

It turns out that you cannot manage a Windows 2008 R2 Hyper-V installation from a Windows 8 desktop (even with the Remote Server Administration Tools for Windows 8 installed) or from Windows 2012 Server.

» read more

PowerShell tip: Deleting certificates

powershell
$certs = Get-ChildItem cert:\LocalMachine\My | where { $_.Subject –like 'CN=Victim*' }
foreach ($cert in $certs) {
    $store = Get-Item $cert.PSParentPath
    $store.Open('ReadWrite')
    $store.Remove($cert)
    $store.Close()
}

The first line finds certificates with the matching subject. The loop goes through those certificates, using .NET class library methods to delete them.

» read more

PowerShell Closures

powershell
# Create a script block. It doesn't capture $x.
$x = 'A'
$sb = { Write-Host $x }

# Change the value of $x and run the script block. Note that it displays the current value.
$x = 'B'
& $sb                  # ... B

# Create a closure.
$closure = $sb.GetNewClosure()

# Change the value of $x.
$x = 'C'

# Run the closure. It displays the original value. Success.
& $closure             # ... B

# For comparison, run the script block. Nope. Still tracking the current value.
& $sb                  # ... C
» read more

New Theme

New theme: Acquia Slate. It’s maybe a little dark for my taste, but I’m going to leave it for a couple of weeks and see if it grows on me.

» read more

PowerShell: ImportSystemModules

powershell

I’ve been using PowerShell as a better Command Prompt for a while now. Increasingly, however, it’s one of the first tools I reach for when I come across a problem, rather than being an afterthought.

» read more

FTTC FTW

I’ve not posted this until today, because my blog’s been poorly, but the BT engineer came round last week and upgraded me to FTTC.

» read more

Repairing image links in drupal

Somehow – I’m not sure how, and I’m not exactly sure when – my website (powered by drupal) lost all of its images. They were still there in the filesystem, and the rows were still in the node table, but they’d vanished from the actual pages.

» read more

F# Coding Kata: Fizz Buzz

Described here.

let IsDivisible n d =
    ((n % d) = 0)

let FizzBuzz n =
    match n with
    | n when IsDivisible n 3 && IsDivisible n 5 -> "fizzbuzz"
    | n when IsDivisible n 3 -> "fizz"
    | n when IsDivisible n 5 -> "buzz"
    | _ -> n.ToString()

let FizzBuzz_WithSequence_ShouldReturnExpectedSequence() =
    let actual = List.map FizzBuzz [4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15]
    let expected = ["4"; "buzz"; "fizz"; "7"; "8"; "fizz"; "buzz"; "11"; "fizz"; "13"; "14"; "fizzbuzz"]
    Assert.Equal(expected, actual)
» read more

MSBuild Target Batching (For Each) Simplified

msbuild

It’s actually quite simple:

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="Default">
   <ItemGroup>
      <ProjectsToPublish Include="AdminConsole\AdminConsole.csproj" />
      <ProjectsToPublish Include="AdminService\AdminService.csproj" />
   </ItemGroup>

   <Target Name="Default">
      <CallTarget Targets="PublishProjectOutput" />
   </Target>

   <Target Name="PublishProjectOutput" Inputs="@(ProjectsToPublish)" Outputs="%(Identity).Dummy">
      <Message Text="@(ProjectsToPublish)" />
   </Target>
</Project>

We set up an item group containing the items that we’d like to process. Our “Default” target is just to demonstrate that we don’t need to do anything clever with CallTarget.

» read more

Release Process: Using Source Server

One of the cool things you can do with the Microsoft Debugging Tools is set up a source server. This works by embedding source control details in your PDB files. Once you’ve published these to a symbol server, and set that up properly, you should be able to load a minidump file in Visual Studio (or WinDbg) and be taken to the correct line of the correct revision of the source file where the crash happened.

» read more

Release Process: Goals

One of the many things that my former company, 1E, does well is its build and release process. That got me thinking: what makes a good build process?

» read more

Returning HTML from a WCF service

wcf

I’m messing around with writing yet another a blog engine, as a way to learn ASP.NET MVC. One of the things that I’d like to do is have it support uploading from Windows Live Writer. This means that it needs to support XML-RPC and Really Simple Discovery (RSD). More on the XML-RPC stuff later.

» read more

Coding Standards: Non-const reference parameters in C++ are evil

This is just a minor rant:

In C++, const references are useful for parameters, because they avoid copying the arguments to a method. Non-const references, on the other hand, are pure evil, because there’s no way (at the call site) to immediately see that a method might change a variable:

» read more

Setting up Squid on Windows

squid

At work, we do a lot of our testing and debugging with virtual machines (using Microsoft Virtual Server or Hyper-V, mostly). The virtual guests are generally not allowed any access to our live network, which makes accessing the Internet difficult. To get around this, I usually set up Squid on the host machine. This allows the guests to access (e.g.) Windows Update and Microsoft Symbol Server, which makes things a bit easier.

» read more

Symbol Store: How are EXE files stored?

If you’re using the Microsoft Symbol Server to pull down symbols for Windows, or if you’re using SYMSTORE.EXE for your own stuff, you’ll see that EXE (and other binary files) are stored in a path similar to C:\WebSymbols\user32.dll\4226015990000\user32.dll.

» read more

Using SQL Server Compact Edition for Unit Testing

sql-server-ce

Ayende shows how to use SQLite with an in-memory database for unit testing your NHibernate code (here). This is a great idea: your unit tests will run more quickly, and you don’t have to worry about tearing the database down when you’ve finished. On the other hand, it’s not an exact match for Microsoft SQL Server (which is probably what your production website will run against).

» read more

Unplanned downtime

At the end of February, differentpla.net suffered filesystem corruption. I had to revert pretty much everything to a previous backup, which meant losing about a week’s worth of stuff.

» read more

Windows 7 beta on Samsung NC-10 Netbook

Nothing to report. It all works fine. Installation took an hour. The only hiccup was that I had to download the Marvell Yukon drivers (I used the Vista x86 ones) from Marvell’s website, but the WiFi works, so that was easy. I also slapped an SDHC card in there for some ReadyBoost goodness.

» read more

Things I learnt this week: SetWaitableTimer

SetWaitableTimer doesn’t accept NULL for the pDueTime parameter.

It returns FALSE; GetLastError() returns ERROR_NOACCESS (998). If you specify zero (i.e. a LARGE_INTEGER containing zero) for pDueTime, the timer is signalled immediately.

» read more

Things I learnt this week: SVCHOST

SVCHOST services are configured by having ImagePath set to "%windir%\system32\svchost.exe -k _name-of-service_", and a Parameters key containing ServiceDll (REG_EXPAND_SZ), which names a DLL with a ServiceMain entry point. ServiceMain has argc and argv.

» read more

Things I learnt this week: RegQueryValueEx

RegQueryValueEx, when passed lpData = NULL, will set *lpcbData to the length required in bytes, even if it’s already set to something. If lpData != NULL, and *lpcbData is too short, RegQueryValueEx will return ERROR_MORE_DATA.

» read more

Generating SSL certificates for differentpla.net

openssl

Because I keep forgetting how to.

Preamble

$ **mkdir SSL**
$ **cd SSL**
$ **cp /usr/lib/ssl/misc/CA.pl .**

Setting up a certificate authority

$ **./CA.pl -newca**
CA certificate filename (or enter to create)**Press Enter**

Making CA certificate ...
Generating a 1024 bit RSA private key
.......................++++++
.....................................................++++++
writing new private key to './demoCA/private/cakey.pem'
Enter PEM pass phrase:**Enter a passphrase to use for the CA**
Verifying - Enter PEM pass phrase:**Enter the same passphrase**
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:**UK**
State or Province Name (full name) [Some-State]:**England**
Locality Name (eg, city) []:**London**
Organization Name (eg, company) [Internet Widgits Pty Ltd]:**differentpla.net**
Organizational Unit Name (eg, section) []:**Certificate Authority**
Common Name (eg, YOUR name) []:**ca.differentpla.net**
Email Address []:**Enter a valid email address**

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:**Press Enter**
An optional company name []:**Press Enter**
Using configuration from /usr/lib/ssl/openssl.cnf
Enter pass phrase for ./demoCA/private/cakey.pem:**Enter the passphrase from above**
Check that the request matches the signature
Signature ok
Certificate Details:

(snip)

» read more

&lt;define&gt; task for NAnt

nant

Essentially, you write a new task like this:

<define name="echo3">
  <echo message="${this.message}"/>
  <echo message="${this.message}"/>
  <echo message="${this.message}"/>
</define>

…and then you call it like this:

» read more

Tweaking TeamCity

teamcity

I just started using TeamCity Professional Edition for some personal projects (and we’re evaluating the Enterprise edition for use at work).

» read more

When I'm supreme ruler: Vacations

supreme-ruler

When I’m supreme ruler of the universe: If you’ve taken more than 5 days vacation, employers will be required to let you work only a half-day on your first day back. It could be the morning, or the afternoon, but you’ll be required to work only 4 hours.

» read more

12 Drinks of Christmas

To the tune of the twelve days of Christmas…

  • 12 Piper Heisecks
  • 11 Flaming Absinthes
  • 10 Gin and Tonics
  • 9 Tequila Slammers
  • 8 Black Sambucas
  • 7 Whiskey Sodas
  • 6 Vodka Redbulls
  • 5 Goldschlagers
  • 4 Cointreaux
  • 3 Rum Cokes
  • 2 Mai Tais
  • …and an ice cube in a Baileys…
» read more

empeg packet format

empeg

The format of the packets in the empeg’s TCP/IP protocol owe a lot to the fact that the empeg mk1 communicated over a serial link. This means that there’s a certain amount of cruft still in the protocol.

» read more

Source Code License

Unless specified otherwise, all source code published on the differentpla.net website is available under the following license terms: Do what you want with it, but don’t claim you wrote it, and it’s not my fault if it doesn’t work.

» read more

FindFirstFile and SE_BACKUP_NAME

If you want to read a file and bypass security (e.g., if you’re writing a backup program), it’s not enough to simply enable the SE_BACKUP_NAME privilege, you have to also pass FILE_FLAG_BACKUP_SEMANTICS to CreateFile.

» read more

Subtracting dates in Javascript

javascript

Here’s how to find the time 30 minutes ago:

var THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;

var now = new Date();
var nowMs = now.getTime();

var thenMs = nowMs - THIRTY_MINUTES_IN_MS;
var then = new Date(thenMs);

The secret is that Date.getTime returns the number of milliseconds since the epoch, and that the Date constructor accepts these millisecond values.

» read more

Debugging Sidebar Gadgets

sidebar-gadgets

Apparently, you can debug JScript in Visual Studio.

The documentation for this is horrendous, though. Almost every resource talks about debugging ASP.NET programs. If you’re writing a Windows Vista Sidebar Gadget, this isn’t a lot of use.

» read more

Calling C# from JScript

It’s possible, through the magic of COM interop, to call C# code from JScript or VBScript. Here’s an example of how to do it from JScript.

» read more

Implementing For Each in JScript

function forEach(enumerable, delegate)
{
    for (var enumerator = new Enumerator(enumerable); !enumerator.atEnd(); enumerator.moveNext())
    {
        delegate(enumerator.item());
    }
}

Used like this:

» read more

Enabling Concurrent Remote Desktop Sessions in Vista

remote-desktop

At work, I do all of my development on a Windows 2003 box. I generally log in as a normal user, and then use Remote Desktop to concurrently log in as Administrator. This means that I’m relatively safe from malware when doing day-to-day stuff, but that I can still get hold of Administrator privileges when I need them.

» read more

A list of HRESULT codes

…because every time I search for a given HRESULT, all I get is yet another frigging VB website regurgitating the contents of WinError.h

» read more

Turning off Registry Virtualization

On Windows Vista, applications running without admin privileges can write to HKEY_LOCAL_MACHINE, and they’ll be transparently redirected to HKEY_CURRENT_USER\Software\Classes\VirtualStore. Similar redirection applies to C:\Program Files.

» read more

Things I found out today while looking at Side-by-Side DLLs

  • You can add DLL dependencies to your EXE file’s manifest by using the /manifestdependency linker switch. As with several other linker switches, this can be done using #pragma comment(linker, ...).
  • The Visual C++ 2005 compiler automatically inserts a /manifestdependency switch into .OBJ files that it creates. It marks them as dependent on the Microsoft.VC80.CRT DLL, version 8.0.50727.762. It does this in the VC\include\crtdefs.h file.
» read more

qmail STARTTLS is slow

qmail

I’ve recently been struggling to reliably send email via my qmail server. I’ve got STARTTLS and SMTP AUTH enabled, in order to allow relaying for authenticated users. However, it’s been really slow, and Thunderbird quite often times out and gives up on the connection.

» read more

Unable to open Web Project

Unable to open Web Project 'foo'.
The file path 'C:\wherever\foo' does not correspond to the URL 'http://localhost/foo'.
The two need to map to the same server location.

Some possible causes, and fixes.

» read more

Empeg File Structures

empeg

If you’ve ever gone looking for the music and playlists on your empeg, you’ll find them in the /empeg/fids0 and /empeg/fids1 directories.

» read more

FileInfo doesn't cache its contents

Imagine this code:

FileInfo oldInfo = new FileInfo(path);
RemoveID3TagsFromFile(path);
FileInfo newInfo = new FileInfo(path);
Trace.Assert(newInfo.Length < oldInfo.Length);

So, we’ve got some code that removes the ID3 tags from a file, thus shortening it. To check that it’s working correctly, we use FileInfo to make sure that the new file is smaller than the old one.

» read more

Jam: Linking with System Libraries

jam

Obviously, your code doesn’t just link with your libraries. It also has to link with some of the system libraries. Jam manages this by using the LINKLIBS variable. The simplest way to make this work is something like the following:

» read more

Getting hold of the current directory in a batch file.

A common UNIX shell idiom is to write things like cwd=$(pwd) to save the current directory so that in case be used later when other things might have changed it. For a long time I didn’t think this was possible in Windows batch files. It turns out that it is, but it isn’t pretty and it does generalise to getting the output of any command.

» read more

Handling LVN_GETDISPINFO

mfc

If you specify LPSTR_TEXTCALLBACK when inserting an item into a ListView control, it no longer supports sorting; you can’t click on the column heading to sort the list control.

» read more

Unresolved external symbol _WinMain@16

visual-studio

I got this error message today:

msvcrt.lib(crtexew.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function _WinMainCRTStartup

The most common cause for this error message is adding Unicode configurations to your project and forgetting to change the entry point to wWinMainCRTStartup.

» read more

Sent Items: Thunderbird and Outlook Express on the same account

Outlook Express likes to store a copy of your outgoing email in a folder called “Sent Items”. Thunderbird likes to store a copy of your outgoing email in a folder called “Sent”. If you use both to access the same email account using IMAP, you’ll end up with both folders being created, and your outgoing email will end up in either, depending on which client you used at the time.

» read more

Using qmail extension addresses with vpopmail

qmail qmail

Extension addresses

Quite often, I’ll hand out a qmail extension address (i.e. roger-foo@domain.com) so that I can more easily filter email received to this account. This is useful. According to the vpopmail documentation, the --enable-qmail-ext switch to configure is supposed to turn this on. Unfortunately, it doesn’t appear to do anything. This is with vpopmail-5.4.0. I’m not entirely sure what it’s supposed to, but it doesn’t make extension addresses work.

» read more

Installing BincIMAP

qmail qmail

Configuring BincIMAP

Another of my requirements is that my email should be accessible using IMAP. I’ve had a quick look at Courier IMAP, and (IMO) it’s a bit oversized for my needs. So, I’m going to install BincIMAP instead. I grabbed the 1.2.7beta5 tarball and unpacked it in /usr/local/src.

» read more

Removing exim and installing qmail

qmail qmail

Removing exim

The first thing to do is to remove exim. Because of Debian’s package management system, you can’t remove exim without installing another package that provides mail-transfer-agent. Because qmail isn’t available as a binary Debian package, this is a little trickier than it needs to be. The answer to this conundrum is in the equivs package, so we install that:

» read more

Deleting the Internet Explorer Cache programmatically

Here’s some C source code that does it.

char buffer[4096];
DWORD cb = 4096;

INTERNET_CACHE_ENTRY_INFO *p = (INTERNET_CACHE_ENTRY_INFO *)buffer;
HANDLE h = FindFirstUrlCacheEntry(NULL, p, &cb);
while (h)
{
    // Do something with it...
    printf("Deleting: %s...", p->lpszSourceUrlName);
    if (!DeleteUrlCacheEntry(p->lpszSourceUrlName))
    {
        printf("failed, 0x%x\n", GetLastError());
    }
    else
        printf("ok\n");

    cb = 4096;
    if (!FindNextUrlCacheEntry(h, (INTERNET_CACHE_ENTRY_INFO *)buffer, &cb))
        break;
}
» read more

Resource File Dependencies

jam

Our MFC application has a resource script. This resource script suffers from a minor problem: It’s not dependency-scanned. If we edit any file included by it – for example the .rc2 file, it’s not rebuilt properly.

» read more

Conflicting 'lib' target

jam

empeg’s source tree has a directory called lib, in which the core libraries used by all of our products live. Unfortunately, this conflicts with one of the included pseudo-targets that jam uses.

» read more

Linker Command Line Length

jam

Jam imposes a hard limit of 996 characters on command lines when built on NT. This limit is higher for other operating systems, and can actually be raised to around 10Kb on Windows 2000. However, it’s still not high enough for some link actions.

» read more

Displaying Progress in a Wizard

mfc

I’m adding a wizard to the program that I’m currently working on. The wizard walks the user through importing some information from a file. I’d like to be able to display the import progress as a seamless part of the wizard.

» read more

Welcome

Welcome to differentpla.net, where Roger occasionally posts snippets of code and other stuff that he feels like sharing with the world.

» read more

Installing Windows XP Pro on a Sony Vaio SRX87

sony-vaio windows-xp

Introduction

I’ve recently acquired a shiny new Hitachi 7K60 hard disk to go into my laptop. The disk is 60Gb, which will hopefully give me enough space to dual-boot Windows XP and Linux. I ran out of space on the 20Gb disk that the Sony comes with, and I had to remove Linux. The other nice thing about this disk is that it’s a 7200 rpm disk, which should make those away-from-home hacking sessions go much more smoothly.

» read more

Using FindWindow in an MFC application

mfc

There are at least two reasons for using FindWindow.

  • To activate the previous instance of your application.
  • To close your application while the installer is upgrading it.

Changing window class names in MFC

Unfortunately, FindWindow is only really guaranteed to return your application’s main window if you use a unique class name. If you’re using MFC, you’ll find this a little difficult: MFC automatically generates class names of the form “Afx:400000:8:10011:0:7e0c0b”.

» read more

Using ON_COMMAND_RANGE and ON_UPDATE_COMMAND_UI_RANGE

mfc

The ON_COMMAND_RANGE and ON_UPDATE_COMMAND_UI_RANGE macros are useful when you want to treat a group of commands similarly. In this case, it’s the commands for changing list view style. The command IDs must be contiguous, and you must specify the lower one first.

» read more

RJ45/UTP Crimps

(Seen from the bottom of the connector, so that the tab is facing away from you, and the gold pins are facing towards you) Pin 1 is on the left. Pin 8 is on the right.

» read more

Many to One Dependencies

mfc

Using a modal dialog as a main window

If you ask the MFC AppWizard to generate a dialog-based application, it generates code that looks like this:

» read more

Switching Toolbars

MFC provides support for automatically switching menus when the active MDI child changes. Why doesn’t it automatically switch toolbars?

» read more

Win32 Threads in C++

Some code.

/* thread.cpp
 */

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <process.h>

class Thread
{
    HANDLE m_hThread;
    UINT m_idThread;

public:
    Thread()
        : m_hThread(NULL), m_idThread(0)
    {
    }

    virtual ~Thread()
    {
        CloseHandle(m_hThread);
    }

    bool Start()
    {
        unsigned threadId;
        HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, StaticThreadRoutine,
                        this, CREATE_SUSPENDED, &threadId);
        if (!hThread)
            return false;

        m_hThread = hThread;
        m_idThread = threadId;
        ResumeThread(hThread);

        return true;
    }

    unsigned Join()
    {
        WaitForSingleObject(m_hThread, INFINITE);

        DWORD result;
        GetExitCodeThread(m_hThread, &result);

        return result;
    }

protected:
    virtual unsigned Run() = 0;

private:
    static unsigned __stdcall StaticThreadRoutine(void *pParams)
    {
        return static_cast<Thread *>(pParams)->Run();
    }
};

class MyThread : public Thread
{
protected:
    virtual unsigned Run()
    {
        Sleep(1000);

        return 0;
    }
};

int main(void)
{
    MyThread *myThread = new MyThread;
    myThread->Start();

    myThread->Join();
    delete myThread;

    return 0;
}
» read more

Including resources in Static Library projects

mfc

Introduction

Consider the following situation:

You’ve got an MFC application, which uses a lot of static libraries to do a lot of the work. These libraries need to interact with the user (perhaps they’ve got dialog boxes in them). Unfortunately, Visual C++ and MFC effectively force you to store all of your resources in the main application .rc file. This makes it difficult to use the static library (with the same resources) in multiple projects. Moreover, it makes the library dependent on the main application, for the resource IDs.

» read more

Finding duplicate files

$ find . -type f -print0 |
    xargs -0 md5sum > MD5SUMS
$ sort < MD5SUMS | uniq -D -w 32 > DUPLICATES

…or the complicated way…

» read more

Streaming to Winamp

rio-receiver

Since the Audio Receiver Manager (the server) uses HTTP to stream the MP3 data to the Rio Receiver, it’s possible (with some work) to stream directly to Winamp. Here’s how.

» read more

Advanced Searches in emplode v2.0

empeg

emplode v2.0 adds the ability to search your music database. It provides two methods of doing this: simple searches (which are hopefully so simple that I won’t explain them here), and advanced searches.

» read more

Building a DLL with Jam

jam

Introduction

empeg’s code base contains several Windows DLL projects. I’m going to investigate getting these built with jam the same way as I did for the MFC applications – by building a simple project with the AppWizard, and getting the project built.

» read more

Remote Debugging With Visual C++

visual-studio

Overview

This document contains some quick tips for getting remote debugging with Visual C++ working. The document was originally written by Roger Lipscombe to cover VC5. Rei Wilkinson reviewed it, and added some stuff for VC6 use.

» read more

Building an MFC Application with Jam

jam

Introduction

Since the majority of our Windows applications are written using MFC, it’s a useful experiment to get jam to build a freshly-generated MFC application. Once we’ve got this working, we can turn our attention to the things that make our build process different.

» read more

RPC_X_NULL_REF_POINTER - what?

com

I just came across a problem where IEnumFoo::Next was returningRPC_X_NULL_REF_POINTER. Of course, the first thing that I did wasundertake a search in MSDN, and with Google to see if I could find anyexplanation of what the problem is.

» read more

Many to One Dependencies

visual-studio

There are times when you want to have multiple input files in a Visual C++ project configured to generate the same output file. For example, you want to catenate a bunch of files to generate a file to be #included.

» read more

TMC PCI48AF Motherboard

pci48af pci48af

A while back, I was trying to get a computer built out of some spare parts to run Linux in the corner of the office. However, I had some trouble with random lockups. I think it had something to do with the memory configuration of the motherboard.

» read more

Moving Message Sign

A couple of weeks ago, we got an LED message board at work. They had them on offer at Maplin (if I recall correctly). Anyway, the manual with the board is singularly useless. It’s labelled “Moving Message Sign”, and has a picture of the display with “Taiwan Kingpul” on it.

» read more

Asus A7V Windows Box

hardware pc-builds

As mentioned here, my Pentium II-400 got fried by an ocuk power supply. As they say, however: Every cloud has a silver lining. With a dead computer, I could finally persuade my girlfriend that some long-overdue upgrades were necessary.

» read more

Overclockers.co.uk Power Supplies

hardware pc-builds

I don’t know if there’s something in particular about Overclockers.co.uk, but we’ve not had any good experiences with their power supplies. We’ve had two power supplies from ocuk, and they’ve both gone horribly wrong, and fried a whole shedload of hardware.

» read more