Appendix D
The Assist Library for .NET
The introduction ended with a piece of advice: copy the recipes once, into a shared library that every project references, rather than into each project separately. This appendix describes the library I built when I took my own advice.
Its name is Assist. Chapter 17 explains where the name comes from: the CFATS Manager library has Assist as its root namespace, because it began as a general toolkit that I carried from one engagement to the next for about twenty years. That toolkit had a SQLHelper, an ObjectState base class, a LogWriter, a DateHandler, a set of encryption providers and a few hundred other classes. Some of them were good. Many of them were exactly the code that the "way it's often written" sections of this book warn against, and I wrote them.
The new Assist keeps the name and the jobs, and replaces the code. It is the recipes of Chapters 1 to 17, finished and packaged: 29 NuGet packages for .NET 10, copyright ImproveCode.com, each with its own tests, XML documentation and a README that maps the old classes to the new ones. You don't need it to use this book. Every recipe stands on its own, and you can keep copying the listings into your own shared library. The packages are for readers who would rather reference the finished version and spend their time on their own application.
What is in it
The packages follow the chapters. A small core has no dependencies at all, and each area adds only the third-party package it needs, so a console tool that reads SQL Server does not pull in MailKit, QuestPDF or the Graph SDK.
- Assist.Core is the base of everything else. It holds
ResultandError(Recipe 5.5), the retry helper, guard clauses and validators (Chapter 8), theEmailAddressandUsPhoneNumbervalue types, safe parsing, business days and time zones (Chapter 15), and the ambient correlation ID that logging and HTTP share. - Integration packages wrap one external library each:
Assist.Emailon MailKit,Assist.IO.Sftpon SSH.NET,Assist.Documents.Excelon ClosedXML,Assist.Documents.Pdf.QuestPdfon QuestPDF, and so on. - Packages that need services register themselves with one
AddAssist...extension method, validate their options at startup and log throughILogger<T>. None of them readsConfigurationManageror swallows an exception.
The packages target .NET 10 only. The book's listings target .NET 8 or later and still work there; the library uses the newer runtime because I don't want to maintain it for three frameworks. Where it could, a package stays on the major version I verified in Appendix C. Assist.Data.SqlServer, for example, references Microsoft.Data.SqlClient 6.1.4, and Assist.Jobs.Quartz stays on Quartz 3.x. The Microsoft.Extensions packages move to the 10.x line that matches the runtime.
The library source also includes a small WPF desktop application in its samples folder that uses the data, caching, configuration, logging, e-mail, export and job packages together, if you want to see them wired up in one place.
Chapters and packages
The table maps each chapter to the packages that carry its recipes. A chapter can appear more than once.
| Chapter | Package | What it covers |
|---|---|---|
| 1 | Assist.Data | Db helper, mapping, paging, safe filters |
| 1 | Assist.Data.SqlServer | Typed parameters, TVPs, bulk copy |
| 1 | Assist.Data.Oracle | The same helper on ODP.NET |
| 2 | Assist.Data.SqlServer | Error classifier, catalog queries |
| 3 | Assist.Caching | Cache-aside, typed keys, single flight |
| 3 | Assist.Caching.Redis | Redis behind the JSON cache |
| 4 | Assist.Logging | Rolling files, scopes, masking, runs |
| 4 | Assist.Logging.Serilog | One-call Serilog setup |
| 5, 8, 15 | Assist.Core | Results, retry, guards, dates |
| 6 | Assist.Configuration | Validated options, connection strings |
| 6 | Assist.Configuration.AzureKeyVault | Prefixed Key Vault secrets |
| 7 | Assist.Security | Passwords, AES-GCM, HMAC, tokens |
| 7 | Assist.DirectoryServices | Active Directory lookups |
| 7 | Assist.DirectoryServices.Graph | Entra ID through Microsoft Graph |
| 9 | Assist.Email | Sender, templates, queue, test senders |
| 10 | Assist.IO | Safe paths, atomic writes, watcher, zip |
| 10 | Assist.IO.Sftp | SFTP with a pinned host key |
| 10 | Assist.IO.Ftp | FTPS when SFTP is not offered |
| 11 | Assist.Documents | CSV writer, reader and importer |
| 11 | Assist.Documents.Excel | Excel export and import |
| 11 | Assist.Documents.Pdf | Merge, split and stamp PDFs |
| 11 | Assist.Documents.Pdf.QuestPdf | Generated reports and invoices |
| 11 | Assist.Documents.Reporting | SSRS rendering over HTTP |
| 11 | Assist.Documents.Word | Word templates without Office |
| 12 | Assist.Xml | JSON defaults, safe XML, conversion |
| 13 | Assist.Http | Typed clients, resilience, tokens |
| 13 | Assist.Http.Wcf | Legacy SOAP and WCF calls |
| 14 | Assist.Jobs | Timed and daily jobs, queues, services |
| 14 | Assist.Jobs.Quartz | Cron schedules with Quartz.NET |
| 17 | Assist.Geography | Points, distances, geocoding |
Chapter 2 is mostly T-SQL, and T-SQL belongs in your migration scripts, not in a NuGet package. Chapter 16 is about the shape of a web application, so it has no package of its own; the pieces a migrated site needs (configuration, logging, data access, caching) come from the packages above.
Getting the packages
The packages are not on nuget.org. You get them from ImproveCode.com as a set of .nupkg files with matching .snupkg symbol packages, all at the same version. If you have the source, pack.ps1 builds, tests and packs all 29 in one step and writes them to artifacts\packages. The script stops before packing if a single test fails.
There are two sensible places to put the files. For one developer or a small team, a folder on a file share works. For a team with a build server, push them to a private feed (Azure Artifacts, GitHub Packages, ProGet or anything else that speaks the NuGet v3 protocol):
.\pack.ps1 -Version 1.0.1
.\pack.ps1 -Source https://pkgs.example.com/nuget/v3/index.json `
-ApiKey $env:FEED_API_KEY
Either way, add a nuget.config next to your solution file. Package source mapping makes sure that Assist.* only ever comes from your source, and everything else only from nuget.org. Without the mapping, anyone who publishes a package called Assist.Core on a public feed could end up in your build.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org"
value="https://api.nuget.org/v3/index.json" />
<add key="assist" value="C:\packages\assist" />
</packageSources>
<packageSourceMapping>
<packageSource key="assist">
<package pattern="Assist.*" />
</packageSource>
<packageSource key="nuget.org">
<package pattern="*" />
</packageSource>
</packageSourceMapping>
</configuration>
Then reference only what you use. The packages pull in their own dependencies, so a project that references Assist.Data.SqlServer gets Assist.Data, Assist.Core and Microsoft.Data.SqlClient with it.
dotnet add package Assist.Data.SqlServer --version 1.0.0
dotnet add package Assist.Configuration --version 1.0.0
dotnet add package Assist.Logging --version 1.0.0
A nightly job, end to end
The first listing is the kind of program I have written at almost every client: a console tool that a scheduler starts at night, does one thing to the database and exits with a code the scheduler can alert on. It uses four packages. Assist.Configuration binds and validates the settings, Assist.Data.SqlServer runs the SQL, Assist.Logging writes the rolling log file, and LoggedRun gives the run its ID, its start and finish lines and its exit code (Recipe 4.6).
using System;
using Assist.Configuration;
using Assist.Data.SqlServer;
using Assist.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ImproveCode.Nightly;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddAssistRollingFile(o => o.FileNamePrefix = "nightly-");
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddValidatedOptions<CleanupSettings>();
builder.Services.AddAssistSqlServer(o => o.ConnectionString =
ConnectionStringGuard.GetRequired(
builder.Configuration, builder.Environment, "AppDb"));
builder.Services.AddSingleton<StaleOrderCleanup>();
using IHost host = builder.Build();
host.Services.ValidateOptionsOnStart(); // fail now, not at 2 a.m.
var cleanup = host.Services.GetRequiredService<StaleOrderCleanup>();
var logger = host.Services
.GetRequiredService<ILogger<StaleOrderCleanup>>();
RunOutcome run = await LoggedRun.ExecuteAsync(
logger, "CloseStaleOrders", cleanup.RunAsync);
return run.ExitCode;
The work itself lives in a small class with its settings next to it:
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using Assist.Configuration;
using Assist.Data;
using Assist.Data.SqlServer;
using Microsoft.Extensions.Options;
namespace ImproveCode.Nightly;
public sealed class CleanupSettings : IOptionsSection
{
public static string SectionName => "Cleanup";
[Range(1, 3650)]
public int StaleAfterDays { get; set; } = 90;
}
public sealed class StaleOrderCleanup(
Db db, IOptions<CleanupSettings> options, TimeProvider clock)
{
public Task<int> RunAsync(CancellationToken ct)
{
DateTime cutoff = clock.GetUtcNow().UtcDateTime
.AddDays(-options.Value.StaleAfterDays);
return db.ExecuteAsync(
"""
UPDATE dbo.SalesOrder
SET Status = 'Closed'
WHERE Status = 'Open' AND OrderedUtc < @Cutoff;
""",
c => c.SqlParameters().AddDateTime2("@Cutoff", cutoff),
cancellationToken: ct);
}
}
Count what is not in these two files. There is no connection to open or close: Db opens a pooled connection per call and disposes it even when the command fails. There is no try/catch: LoggedRun logs the exception once, with the run ID on every line, and turns it into exit code 1. There is no DateTime.Now: the clock is injected, so a test can pass a fake one. The connection string goes through ConnectionStringGuard, which refuses a password in appsettings.json outside Development and adds an Application Name so the DBA can see which program holds the session. And the settings are checked before any work starts, so StaleAfterDays: 0 stops the program with a message that names the key, not a stack trace from the middle of an UPDATE.
Both files compile against the 1.0.0 packages with nullable reference types on and implicit usings off.
From the old Assist to the new one
I did not port the old library. I read it, class by class, and decided for each one whether its job still existed, and if so which recipe did that job properly. The answer is written down: every package README ends with a table called "Migrating from the old Assist classes" that lists each old class or method and what replaces it, including the ones I dropped and why. If you inherited code that uses a homegrown framework of your own, those tables are a fair model for the inventory you will need.
A few of the decisions show the pattern.
SQLHelper and SQLManager. The old data layer was the Data Access Application Block's SQLHelper plus a SQLManager class with more than three hundred methods, most of them building SQL with string.Format. Its replacement is Db with typed, sized parameters (Recipes 1.2 and 1.3), and one small query class per area of the application. The generic methods have direct successors: GetData becomes QueryAsync<T>, ExecuteSP becomes ExecuteProcedureAsync, and the schema helpers become SqlServerSchema. The methods that existed only to glue strings together have no successor, on purpose.
ObjectState. Almost every old class inherited ObjectState, with its ErrorOccurred flag, its ErrorMessage string and its HandleException method that caught everything. Callers were supposed to check the flag, and many didn't. The new code returns Result or Result<T> for failures the caller should expect and lets real exceptions propagate (Chapter 5). The audit fields that lived on ObjectState became the immutable AuditInfo record, stored in UTC. ObjectState.Query, which carried SQL text all the way to the screen, is gone.
LogWriter. The old LogWriter.AppendText wrote a line to a text file named by hand from DateTime.Now, and failed silently. Its replacement is ILogger<T> with the rolling file provider from Assist.Logging. For the months in between, the package includes a static LogHelper with the old method names. Every method on it is marked [Obsolete] with the diagnostic ID ASSIST0001, so the compiler's warning count tells you how much of the migration is left. When it reaches zero, you delete the shim.
The encryption providers. This one needed the most care. The old Assist.Security.Provider namespace had DES, RC2, TripleDES and Rijndael providers with keys and IVs in XML key files, and Assist.Security.Block had an encryptor with a key written into the source. All of them used CBC mode with no integrity check, and there were years of data encrypted with them in real databases. You can't just delete that code; you need it one last time to read the old values.
So Assist.Security.Legacy reproduces decryption only. There is no way to encrypt new data with a legacy cipher. LegacyKeyFile reads the old XML key files, LegacyDecryptor decrypts with the old algorithms, and LegacyDataMigrator decrypts an old value and encrypts it again with AesGcmEncryptor in one call. No keys from the old code are included; you supply them from your old key files or configuration. Every type in the namespace is [Obsolete] with diagnostic ID ASSISTLEGACY001, and you suppress it in the migration project only, so the legacy types cannot creep back into application code.
The listing shows the decrypt-and-re-encrypt path for one column. It reads rows that still hold the old value, writes the new AES-GCM value next to it, and clears the old one in the same statement, so the job can stop and restart at any point.
#pragma warning disable ASSISTLEGACY001 // this project only
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Assist.Data;
using Assist.Data.SqlServer;
using Assist.Security;
using Assist.Security.Legacy;
namespace ImproveCode.Migration;
public sealed record LegacyTaxId(int CustomerId, byte[] TaxIdOld);
public sealed class TaxIdMigration(Db db, IDataEncryptor encryptor)
{
public async Task<int> RunAsync(string keyFile, CancellationToken ct)
{
LegacyKeyMaterial keys = LegacyKeyFile.Load(keyFile);
var migrator = new LegacyDataMigrator(encryptor);
IReadOnlyList<LegacyTaxId> rows =
await db.QueryAsync<LegacyTaxId>(
"""
SELECT CustomerId, TaxIdOld
FROM dbo.Customer
WHERE TaxIdOld IS NOT NULL AND TaxId IS NULL;
""",
cancellationToken: ct);
foreach (LegacyTaxId row in rows)
{
string context = $"Customer:{row.CustomerId}:TaxId";
string value = migrator.ReEncryptString(
LegacyCipherAlgorithm.TripleDes, row.TaxIdOld, keys,
context);
await db.ExecuteAsync(
"""
UPDATE dbo.Customer
SET TaxId = @TaxId, TaxIdOld = NULL
WHERE CustomerId = @Id;
""",
c =>
{
var p = c.SqlParameters();
p.AddVarChar("@TaxId", 200, value);
p.AddInt("@Id", row.CustomerId);
},
cancellationToken: ct);
}
return rows.Count;
}
}
The context string binds each encrypted value to its row and column, as in Recipe 7.2, so a value copied from one customer to another will not decrypt. The IDataEncryptor comes from the normal registration, with the keys read from a secret store:
using Assist.Security;
using Assist.Security.Legacy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ImproveCode.Migration;
public static class SecurityRegistration
{
public static IServiceCollection AddAppSecurity(
this IServiceCollection services, IConfiguration config) =>
services
.AddAssistPasswordHashing(o => o.AddStandardLegacySchemes())
.AddAssistEncryption(o =>
config.GetSection("Encryption").Bind(o));
}
AddStandardLegacySchemes handles the other half of the old security story: password hashes. Old tables held unsalted MD5 or SHA-1 digests. You can't recompute a proper hash without the password, but you can wrap the old digest: Pbkdf2PasswordHasher.WrapLegacyHash runs PBKDF2 over the old digest bytes and stores the result in the new format. From that moment the weak digest is gone from the database. When the user next signs in, Verify returns SuccessRehashNeeded, and you store a normal hash of the password you now have in hand.
Two practical notes from running this kind of migration. CBC without a MAC cannot always tell you that you used the wrong key; sometimes it returns garbage instead of failing. Decrypt a sample, look at the values, and only then run the whole table. And keep the old column until the job reports zero rows left and the application has run on the new column for a while. Dropping it is the last step, not the first.
Not everything had a successor. The old ServerInfo.Resolve "protected" connection strings with ROT13, UserInfo held plain-text passwords, and DateHandler returned January 1, 1901 when it meant "no date". Those classes are simply gone, and the README tables say so.
Checklist
- Reference only the
Assist.*packages a project uses; each one brings its own dependencies. - Put a
nuget.configwith package source mapping next to the solution, soAssist.*comes only from your folder or private feed. - Register each area with its
AddAssist...method and callValidateOptionsOnStartin tools that don't start a host. - Return
RunOutcome.ExitCodefrom scheduled tools so the scheduler can alert on failures. - When you replace an old helper, read the package README's migration table first; it lists what was dropped and why.
- Use the obsolete
LogHelpershim only as a bridge, and track itsASSIST0001warnings down to zero. - Move legacy-encrypted data with
LegacyDataMigratorin a separate project that suppressesASSISTLEGACY001, and spot-check decrypted values before running a whole table. - Wrap old MD5 or SHA-1 password digests now, and let
SuccessRehashNeededfinish the job at sign-in.