Introduction
Introduction
Every consultant has a folder they never delete. Mine is called work, and it has followed me from laptop to laptop for more than twenty years. It holds the code, the documents and the leftovers of forty-five client engagements: energy and pipeline companies, mortgage and payroll processors, a school district, a hospital district, insurers, software vendors and government contractors. When I finally indexed it, the folder held about 1.9 million files.
The index told me something I had half known for years. I had written the same code over and over.
Across those engagements I found 436,849 C# files that someone wrote by hand, and 68,998 SQL files. I found a class called Utility 463 times. I found an EmailHelper 342 times. Twenty-nine engagements had their own homegrown logging class. Thirty had a hand-rolled data access helper. Thirty-one had built some kind of cache. Twenty-eight had written code to send e-mail, read Active Directory, validate input and convert dates, and almost every one had done it slightly differently, with a slightly different set of bugs.
None of this happened because the developers were careless. Most of them were good. They were under deadline, the framework of the day didn't offer what they needed, and copying last year's helper class into this year's project was the fastest way to ship. Then the helper class was copied again. By the time anyone noticed, the code was in production in a dozen places, and nobody remembered why the retry loop slept for exactly 3,000 milliseconds.
This book is the set of recipes I wish I could have dropped into every one of those projects.
What this book is
Improve Code is a cookbook. Each chapter takes one job that business applications do again and again (talking to SQL Server, logging, handling errors, sending e-mail, moving files, producing Excel and PDF output, calling web services, running background jobs) and gives you reusable code for doing it well on modern .NET.
Every recipe follows the same pattern:
- Problem: what goes wrong in real systems, and why it matters.
- The way it's often written: the version I found again and again in the field. It is short, generic and rewritten from scratch, but if you have maintained enterprise .NET code you will recognize it.
- The improved recipe: complete, compiling code for .NET 8 or later that you can copy into your own project.
- How it works: the reasoning behind each choice, so you can adapt the code instead of cargo-culting it.
- Variations and pitfalls: the edge cases, the alternatives, and the mistakes I have watched people make with the improved version too.
Some recipes add a short On .NET Framework section, because many of you still support applications on .NET Framework 4.x and will be for years.
What this book is not
This is not a tour of every feature in C# 12, and it is not a book about architecture patterns with tidy diagrams. It does not try to convert you to microservices, Domain-Driven Design or any other methodology. The recipes work in a ten-year-old monolith as well as in a new service.
It is also not a collection of client code. The archive I describe is the research behind the book, not its content. Everything you see in the "way it's often written" sections was written fresh to illustrate a pattern that appeared in many places, and no client is named. The one exception is Chapter 17, a case study of CFATS Manager, a product I built and own, where you will see real excerpts from a real codebase that has lived from Visual Studio 2008 to Visual Studio 2022.
Who it's for
I wrote this for working .NET developers: the people who keep business applications running, add features to them, and quietly fix the things that break at two in the morning. You know C#. You have written SQL. You have probably inherited at least one SqlHelper class and a Utility.cs file longer than this introduction. You want code you can trust, and you want to understand why it's better.
If you lead a team that maintains older Microsoft-stack systems, you will also find the book useful as a reference for code reviews. Appendix B is a checklist drawn from the recipes.
What the archive taught me
Before writing any recipes, I measured the archive. A few numbers shaped the whole book.
Most enterprise .NET code is older than you think. Of the 6,535 Visual Studio solutions in the archive, 2,216 were last saved in Visual Studio 2010, 1,480 in Visual Studio 2008 and 1,256 in Visual Studio 2005. Only 321 were saved in Visual Studio 2017 or later. Of 16,433 project files, just 526 used the modern SDK-style format. The code that runs the world's back offices is still largely .NET Framework code, and the recipes respect that.
Teams rebuild the same infrastructure. The table below shows how many engagements had written their own version of each kind of utility. These are the chapters of this book.
| Kind of utility | Engagements |
|---|---|
| Caching | 31 |
| Data access helpers | 30 |
| Security, hashing and passwords | 30 |
| Logging | 29 |
| Exception handling | 29 |
| 28 | |
| Validation | 28 |
| Files and FTP | 27 |
| Background jobs and scheduling | 27 |
| Excel and CSV export | 26 |
Old habits outlive the frameworks that excused them. Empty catch { } blocks appeared in 29 of the 35 engagements with C# code, and throw ex;, which throws away the stack trace, in 25. About 1.9 percent of hand-written C# files built SQL by gluing strings together, and that habit showed up in 30 engagements. Only one in six files that created a SqlConnection wrapped it in a using statement. On the database side, old-style @@ERROR checks were more common than TRY...CATCH, cursors appeared in 24 of 32 engagements, and SELECT * turned up in almost a third of all SQL files. Just 13 engagements used a real logging library, and async/await appeared in fewer than one file in three hundred.
A lot of code is dead. Nearly 41,000 code files sat inside Visual Studio project folders without being part of the project at all. Nobody compiled them, but nobody deleted them either, and every one of them made the codebase harder to read. Another 374,000 code files lived outside Visual Studio entirely: scripts, stored procedures and one-off tools that were never under the same discipline as the main application.
Copies multiply. The archive contains 9,579 groups of folders that are byte-for-byte identical: branch copies, backups named Copy of Copy of, and libraries pasted into every project that needed them. Every copy is a place where a bug fix doesn't arrive.
None of these numbers are an indictment. They are what happens to real software over twenty years. The goal of this book is to give you smaller, sharper building blocks, so that the next copy you make is a good one.
How to use this book
You don't need to read it in order. Each chapter stands on its own, and each recipe is meant to be found when you need it. If you are about to write a stored procedure, read Chapter 2. If a nightly job just failed with nothing useful in the log, read Chapter 4. If you are planning a migration away from Web Forms, start with Chapter 16 and then read the case study in Chapter 17.
A few conventions:
- Code targets .NET 8 or later and C# 12 with nullable reference types enabled. Namespaces start with
ImproveCode.so you can see where each type belongs; rename them to suit your project. - When a recipe needs a NuGet package, the package id is named in the text. I prefer the base class library where it is good enough. Appendix C lists the package versions every listing was compiled against. Appendices D and E describe Assist, the library I built from these recipes, in its .NET and Python editions, along with the Python versions of every listing in the book.
- SQL targets SQL Server 2019 or later. Where a feature needs a specific version, the recipe says so.
- Code lines are kept short so they fit the printed page. In your editor, feel free to let them breathe.
- Connection strings, server names and addresses are placeholders such as
localhost,AppDbandexample.com.
A word on copying
You are welcome to copy the recipes into your own projects. That's what they're for. But copy them once, into a shared library that every project references, rather than into each project separately. The archive behind this book is a twenty-year demonstration of what happens otherwise.
Let's improve some code.