Posts in category “Tutorial”

.NET Deployment Issue: Ghost Dependency

Symptom

  • .NET 8 app with Polly fails on deploy: Could not load file or assembly 'Microsoft.Extensions.Http, Version=9.0.0.0'

Checks

  1. Dependencies

    • No preview packages in .csproj
    • Locked Microsoft.Extensions.Http to 8.0.0
    • Local build clean → Not a package issue
  2. Environment

    • CI/CD fixed to .NET 8 SDK
    • Cleared ~/.dotnet and ~/.nuget
    • Removed caches → Environment clean

Root Cause

  • Deploy script only overwrote files, never cleaned target dir
  • Old HappyNotes.Api.deps.json misled runtime to request v9.0.0.0

Lesson Always wipe target dir before publish:

rm -rf /your/target/directory/*

GitHub CLI Multi-Account Auto-Switcher: Zero-Config Solution

If you juggle work and personal GitHub accounts like I do, constantly checking which account is active before running gh pr create gets old fast. Here's a perfect solution that completely eliminates this friction.

The Problem

Working with multiple GitHub accounts means:

  • Forgetting which account is currently active
  • Getting "No default remote repository" errors
  • Manually running gh auth switch and gh repo set-default
  • Accidentally creating PRs with the wrong account

The Solution

Create a gh wrapper script that automatically detects the current repository's owner, switches to the correct GitHub account, and sets the default repository before executing any command.

Implementation

#!/bin/bash

# Path to original gh binary
ORIGINAL_GH="/usr/local/bin/gh"  # Adjust for your system

# Get current repository's remote URL
remote_url=$(git remote get-url origin 2>/dev/null)

# If not in a git repo, pass through to original gh
if [ $? -ne 0 ]; then
    exec "$ORIGINAL_GH" "$@"
fi

# Extract full repository name (owner/repo) - remove .git suffix
if [[ $remote_url =~ github\.com[:/]([^/]+/[^/]+) ]]; then
    repo_full_name="${BASH_REMATCH[1]}"
    repo_full_name="${repo_full_name%.git}"
    repo_owner=$(echo "$repo_full_name" | cut -d'/' -f1)
else
    exec "$ORIGINAL_GH" "$@"
fi

# Get current active GitHub account
current_user=$("$ORIGINAL_GH" api user --jq '.login' 2>/dev/null)

if [ $? -ne 0 ]; then
    exec "$ORIGINAL_GH" "$@"
fi

# Switch account if needed
if [ "$repo_owner" != "$current_user" ]; then
    echo "→ Repository belongs to $repo_owner, switching from $current_user..." >&2
    "$ORIGINAL_GH" auth switch >/dev/null 2>&1
fi

# Set default repository to avoid "No default remote repository" errors
"$ORIGINAL_GH" repo set-default "$repo_full_name" >/dev/null 2>&1

# Execute original command
exec "$ORIGINAL_GH" "$@"

Setup

  1. Find your original gh path:
which gh
# Use this path in the ORIGINAL_GH variable
  1. Create the wrapper script:
# Save script as ~/.local/bin/gh
chmod +x ~/.local/bin/gh
  1. Adjust PATH priority:
# Add to ~/.bashrc or ~/.zshrc
export PATH="$HOME/.local/bin:$PATH"
  1. Verify setup:
source ~/.bashrc
which gh  # Should show ~/.local/bin/gh

Usage

All GitHub CLI commands now automatically use the correct account:

# In personal repository
gh pr create  # Uses personal account, sets correct default repo

# In work repository  
gh pr create  # Uses work account, sets correct default repo

# All other commands work transparently
gh issue list
gh pr view
gh repo clone username/repo

Advanced: Working with Forks

For forked repositories where you want to view PRs in the upstream repo:

# View your PRs in the upstream repository
gh pr list --author @me --repo upstream-owner/repo-name

# Or temporarily switch to upstream
gh repo set-default upstream-owner/repo-name
gh pr view [PR_NUMBER]

How It Works

  • Extracts repository owner from the current directory's origin remote URL
  • Compares repository owner with currently active GitHub account
  • Automatically runs gh auth switch if accounts don't match
  • Always sets the correct default repository to prevent CLI errors
  • Transparently proxies all other gh commands

Benefits

  • Zero configuration required - works out of the box
  • Zero habit changes needed - still use gh commands normally
  • Eliminates common errors - no more "No default remote repository" messages
  • Multi-account friction eliminated - never think about which account is active again

Perfect for developers who work across multiple GitHub organizations or maintain both work and personal projects.

Mocking Node.js Path Separators: The Dependency Injection Solution

The Problem

Node.js path utilities like path.sep, path.join() are hardcoded to the current platform and readonly - you can't mock them for cross-platform testing:

// Instead of this brittle approach:
function createTempFile(name: string, separator: string) {
  return 'tmp' + separator + name; // Manual string manipulation
}

// Use dependency injection:
function createTempFile(name: string, pathImpl = path) {
  return pathImpl.join('tmp', name);
}

// Now you can test both platforms reliably:
createTempFile('data.json', path.win32)  // → tmp\data.json
createTempFile('data.json', path.posix)  // → tmp/data.json

Why This Works

Node.js provides path.win32 and path.posix as separate implementations. Instead of fighting the platform dependency, embrace it through clean dependency injection. Test Windows logic on Linux, test Unix logic on Windows - no mocking needed.

Technical Note: Testing ILogger with NSubstitute

1. The Challenge

Directly verifying ILogger extension methods (e.g., _logger.LogError("...")) with NSubstitute is difficult. These methods resolve to a single, complex generic method on the ILogger interface, making standard Received() calls verbose and brittle.

void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);

2. The Solution: Inspect the State Argument

The most robust solution is to inspect the state argument passed to the core Log<TState> method. When using structured logging, this state object is an IEnumerable<KeyValuePair<string, object>> that contains the full context of the log call, including the original message template.

3. Implementation: A Reusable Helper Method

To avoid repeating complex verification logic, create a static extension method for ILogger<T>.

LoggerTestExtensions.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using NSubstitute;
using FluentAssertions;

public static class LoggerTestExtensions
{
    /// <summary>
    /// Verifies that a log call with a specific level and message template was made.
    /// </summary>
    /// <typeparam name="T">The type of the logger's category.</typeparam>
    /// <param name="logger">The ILogger substitute.</param>
    /// <param name="expectedLogLevel">The expected log level (e.g., LogLevel.Error).</param>
    /// <param name="expectedMessageTemplate">The exact message template string to verify.</param>
    public static void VerifyLog<T>(this ILogger<T> logger, LogLevel expectedLogLevel, string expectedMessageTemplate)
    {
        // Find all calls to the core Log method with the specified LogLevel.
        var logCalls = logger.ReceivedCalls()
            .Where(call => call.GetMethodInfo().Name == "Log" &&
                           (LogLevel)call.GetArguments()[0]! == expectedLogLevel)
            .ToList();

        logCalls.Should().NotBeEmpty($"at least one log call with level {expectedLogLevel} was expected.");

        // Check if any of the found calls match the message template.
        var matchFound = logCalls.Any(call =>
        {
            var state = call.GetArguments()[2];
            if (state is not IEnumerable<KeyValuePair<string, object>> kvp) return false;
            
            return kvp.Any(p => p.Key == "{OriginalFormat}" && p.Value.ToString() == expectedMessageTemplate);
        });

        matchFound.Should().BeTrue($"a log call with the message template '{expectedMessageTemplate}' was expected but not found.");
    }
}

4. How to Use in a Unit Test

Step 1: Arrange In your test, create a substitute for ILogger<T> and inject it into your System Under Test (SUT).

// In your test class
private readonly ILogger<MyService> _logger;
private readonly MyService _sut;

public MyServiceTests()
{
    _logger = Substitute.For<ILogger<MyService>>();
    _sut = new MyService(_logger);
}

Step 2: Act Execute the method that is expected to produce a log entry.

[Fact]
public void DoWork_WhenErrorOccurs_ShouldLogError()
{
    // Act
    _sut.DoWorkThatFails();

    // ...
}

Step 3: Assert Use the VerifyLog extension method for a clean and readable assertion.

    // Assert
    _logger.VerifyLog(LogLevel.Error, "An error occurred while doing work for ID: {WorkId}");
}

5. Key Advantages of This Approach

  • Robustness: It verifies the intent (the message template) rather than the final formatted string, making it resilient to changes in parameter values.
  • Readability: The test assertion _logger.VerifyLog(...) is clean, concise, and clearly states what is being tested.
  • Reusability: The extension method can be used across the entire test suite.
  • Precision: It correctly targets the specific log level and message, avoiding ambiguity.

Cloudflare DNS Update Script

Motivation: though reinstalling OS is rare, but I still want to automate the DNS update process.

Get API Token

  1. Go to https://dash.cloudflare.com/profile/api-tokens
  2. Click "Create Token"
  3. Use "Edit zone DNS" template
  4. Select your domain in "Zone Resources"
  5. Copy the generated token

Setup API Token in bashrc

Add to ~/.bashrc:

export CF_API_TOKEN="your_api_token_here"

Reload: source ~/.bashrc

Enhanced Update Script

Create update-dns.sh:

#!/bin/bash

# Usage function
usage() {
    echo "Usage: $0 <record_name> [ip_address]"
    echo "       $0 <domain> <subdomain> [ip_address]"
    echo "Examples:"
    echo "  $0 home.example.com                    # Uses Tailscale IP"
    echo "  $0 example.com                         # Root domain with Tailscale IP"
    echo "  $0 server.example.com 192.168.1.100   # Uses specified IP"
    echo "  $0 example.com home                    # Legacy format"
    echo "  $0 example.com @ 1.2.3.4              # Legacy root domain"
    exit 1
}

# Check parameters
if [ $# -lt 1 ]; then
    usage
fi

# Check if API token is set
if [ -z "$CF_API_TOKEN" ]; then
    echo "Error: CF_API_TOKEN not set. Add it to ~/.bashrc"
    exit 1
fi

# Parse arguments - detect format
FIRST_ARG="$1"
SECOND_ARG="$2"
THIRD_ARG="$3"

# Check if first argument contains multiple dots (FQDN format)
if [[ "$FIRST_ARG" == *.*.* ]] || ([[ "$FIRST_ARG" == *.* ]] && [[ "$SECOND_ARG" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]); then
    # FQDN format: script.sh home.example.com [ip]
    RECORD_NAME="$FIRST_ARG"
    CUSTOM_IP="$SECOND_ARG"
    
    # Extract domain by removing first subdomain part
    DOMAIN=$(echo "$RECORD_NAME" | cut -d'.' -f2-)
elif [[ "$FIRST_ARG" == *.* ]] && [ -z "$SECOND_ARG" ]; then
    # Root domain format: script.sh example.com
    RECORD_NAME="$FIRST_ARG"
    DOMAIN="$FIRST_ARG"
    CUSTOM_IP=""
elif [[ "$FIRST_ARG" == *.* ]] && [ -n "$SECOND_ARG" ] && [[ ! "$SECOND_ARG" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # Legacy format: script.sh example.com home [ip]
    DOMAIN="$FIRST_ARG"
    SUBDOMAIN="$SECOND_ARG"
    CUSTOM_IP="$THIRD_ARG"
    
    if [ "$SUBDOMAIN" = "@" ]; then
        RECORD_NAME="$DOMAIN"
    else
        RECORD_NAME="$SUBDOMAIN.$DOMAIN"
    fi
else
    echo "Error: Invalid arguments format"
    usage
fi

# Get IP address
if [ -n "$CUSTOM_IP" ]; then
    NEW_IP="$CUSTOM_IP"
    echo "Using provided IP: $NEW_IP"
else
    if command -v tailscale >/dev/null 2>&1; then
        NEW_IP=$(tailscale ip -4)
        echo "Using Tailscale IP: $NEW_IP"
    else
        echo "Error: tailscale not found and no IP provided"
        exit 1
    fi
fi

# Validate IP format
if ! echo "$NEW_IP" | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' >/dev/null; then
    echo "Error: Invalid IP address format: $NEW_IP"
    exit 1
fi

echo "Updating DNS record: $RECORD_NAME -> $NEW_IP"

# Get Zone ID
echo "Getting Zone ID for $DOMAIN..."
ZONE_RESPONSE=$(curl -s -H "Authorization: Bearer $CF_API_TOKEN" \
    "https://api.cloudflare.com/client/v4/zones?name=$DOMAIN")

ZONE_ID=$(echo "$ZONE_RESPONSE" | jq -r '.result[0].id')

if [ "$ZONE_ID" = "null" ] || [ -z "$ZONE_ID" ]; then
    echo "Error: Could not find zone for domain $DOMAIN"
    echo "Response: $ZONE_RESPONSE"
    exit 1
fi

echo "Zone ID: $ZONE_ID"

# Get Record ID
echo "Getting Record ID for $RECORD_NAME..."
RECORD_RESPONSE=$(curl -s -H "Authorization: Bearer $CF_API_TOKEN" \
    "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$RECORD_NAME&type=A")

RECORD_ID=$(echo "$RECORD_RESPONSE" | jq -r '.result[0].id')

if [ "$RECORD_ID" = "null" ] || [ -z "$RECORD_ID" ]; then
    echo "Error: Could not find A record for $RECORD_NAME"
    echo "Available records:"
    echo "$RECORD_RESPONSE" | jq -r '.result[] | "\(.name) (\(.type))"'
    exit 1
fi

echo "Record ID: $RECORD_ID"

# Update DNS record
echo "Updating DNS record..."
UPDATE_RESPONSE=$(curl -s -X PUT \
    "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
    -H "Authorization: Bearer $CF_API_TOKEN" \
    -H "Content-Type: application/json" \
    --data "{\"type\":\"A\",\"name\":\"$RECORD_NAME\",\"content\":\"$NEW_IP\"}")

SUCCESS=$(echo "$UPDATE_RESPONSE" | jq -r '.success')

if [ "$SUCCESS" = "true" ]; then
    echo "✅ DNS record updated successfully!"
    echo "   $RECORD_NAME now points to $NEW_IP"
else
    echo "❌ Failed to update DNS record"
    echo "Response: $UPDATE_RESPONSE"
    exit 1
fi

Make executable: chmod +x update-dns.sh

Usage Examples

# New FQDN format (recommended)
./update-dns.sh home.example.com                    # Uses Tailscale IP
./update-dns.sh server.example.com 192.168.1.100   # Uses custom IP
./update-dns.sh example.com                         # Root domain with Tailscale IP

# Legacy format (still supported)
./update-dns.sh example.com home                    # Subdomain with Tailscale IP
./update-dns.sh example.com @ 1.2.3.4              # Root domain with custom IP

# Multiple subdomains
./update-dns.sh web.example.com
./update-dns.sh api.example.com
./update-dns.sh db.example.com 10.0.0.5

Features

  • ✅ API token stored securely in .bashrc
  • ✅ Auto-discovers Zone ID and Record ID
  • ✅ Supports custom IP or auto-detects Tailscale IP
  • ✅ Supports root domain updates with @
  • ✅ Input validation and error handling
  • ✅ Clear success/failure messages
  • ✅ Usage help and examples

Alternative: Using flarectl

# Install
go install github.com/cloudflare/cloudflare-go/cmd/flarectl@latest

# Update (simpler)
export CF_API_TOKEN="your_token"
flarectl dns update --zone yourdomain.com --name subdomain --content $(tailscale ip -4) --type A