Chapter 17
Case Study: CFATS Manager
Every other chapter in this book is built from patterns I saw at many clients, rewritten from scratch so no client's code appears on the page. This chapter is different. CFATS Manager is my own product, and the code you will see here is mine. I designed it, I wrote it, and I kept it running from the Visual Studio 2008 era to Visual Studio 2022. CFATS Manager is protected by a U.S. patent held by the author ([patent number]).
CFATS stands for Chemical Facility Anti-Terrorism Standards, the U.S. Department of Homeland Security program for high-risk chemical facilities. A covered facility has to show that it meets a set of risk-based performance standards (RBPS): perimeter security, access control, personnel surety, training, drills, incident reporting, record keeping and more. CFATS Manager gives a facility's security staff one place to keep the records an inspector expects to see. It also tells those people, by e-mail, when something is about to slip.
A case study belongs in a recipe book for a simple reason. Recipes are easy to nod along to when they are written fresh for the page. It is harder, and more useful, to watch them applied to a real system with real history. That history includes a 4,849-line data class, more than 200 pages that each copy the same session code, and an alert service that was never migrated. The code in this chapter is the code I would write differently today. I show the original, explain why it was written that way, and give the modern .NET version. Every modern listing compiles against .NET 9. The SQL was run against SQL Server LocalDB.
A few ground rules for this chapter. CFATS data includes Chemical-terrorism Vulnerability Information, which the law protects. None of it appears here. Excerpts from the product are abridged, re-wrapped to fit the page, and stripped of anything that names a customer, a person or a place. When you see // ... inside an original listing, I removed code.
Recipes
- 17.1Replacing String-Built Queries in SQLManagerSQLManager has one public method for nearly every query the product runs: GetIncidentFromID, GetDrillFromID, GetAudit, GetAuditRBPS1 through…
- 17.2From ObjectState to Results and Exceptions in the Usage LayerEvery Usage class in CFATSLibrary has the same shape. It holds an ObjectReference (the model being saved) and a State (an ObjectState with…
- 17.3One Transaction for a Multi-Table Insert ProcedureSaving an incident in CFATS Manager touches several tables: the incident row, a row linking the incident to its facility, and a person row for…
- 17.4One Home for Session State Instead of 223 CopiesAlmost every CFATS page needs the current user, the current menu and the currently selected facility. Each page gets them the same way: it declares…
- 17.5The Alert Manager as a Modern Worker ServiceCFATS Manager's alerts are the part of the product that reaches people who are not logged in. When a piece of security equipment has been out of…
- 17.6Alert E-mail with MailKitThe alert service and several pages send mail through EmailHelper, a wrapper over System.Net.Mail.SmtpClient. Microsoft now marks SmtpClient as not…
What CFATS Manager does
The best description of a product is its page list. The web application has about 295 .aspx pages, and once the test pages are set aside they fall into clear modules:
- Facility profile. Facility details, contacts and their roles, a site map with aerial imagery, and the facility's chemicals of interest.
- Audits. A questionnaire for each of the 18 risk-based performance standards (
AuditRBPS1_1.aspxthroughAuditRBPS18.aspx), an audit wizard, and audit reports. - Training and drills. Training records, drill records with participants, and uploaded sign-in sheets and certificates.
- Personnel surety. Records of the screening done on people with access, and exports that support DHS submissions.
- Daily operations. Visitor logs, a daily security checklist with questions, and security-equipment outages.
- Incidents. Three kinds: incidents, threats and near misses, each with its own input form.
- Documents. Uploads stored in SQL Server, classified by document type and sub-type.
- Alerts. A green, yellow and red status for each facility, an alert history, and per-facility alert settings that decide who gets e-mailed and when.
- Reports. About 115 RDLC report definitions, shown on screen and exported to PDF or Excel.
- Administration. Users, permissions, titles, organizations and menus. Each facility's menu is stored in the database.
The users are a facility security officer (FSO) at each site, a corporate security officer (CSO) above several sites, and administrators. Those two job titles show up in the code itself: the alert service looks up contacts by title to decide who to e-mail.
Architecture
The repository holds six projects, plus a setup project for the alert service. Only three of them are in the Visual Studio 2022 solution.
| Project | Framework | Role |
|---|---|---|
| CFATS | .NET Framework 4.7.2 | Web Forms application |
| CFATSLibrary | .NET Framework 3.5 | Shared library |
| CFATSWebControls | .NET Framework 3.5 | Custom server controls |
| CFATSDatabase | VS 2010 database project | Schema and procedures |
| CFATSAlertManager | .NET Framework 4.0 | Windows service |
| SLWebApp | Silverlight | Dead, ignored |
CFATS is the web application: about 800 C# files and 150,000 lines, with eight master pages, a site map, ASMX web services for autocomplete and maps, and the RDLC reports. It uses the ReportViewer WebForms control (version 15, from NuGet), AJAX Control Toolkit, Bootstrap 5 and jQuery.
CFATSLibrary is the heart of the system, about 43,000 lines. Its root namespace is Assist, not CFATS. That is a clue to its history: the library was a general toolkit before it was a product library. Some of its parts were written for CFATS and some came from earlier work.
CFATSWebControls is small, about 900 lines: a confirm button, a drop-down checkbox list, a menu generator and rounded-corner panels from the days before CSS did that.
CFATSDatabase is a Visual Studio 2010 database project (.dbproj, the format before SSDT). It holds 111 tables, 187 stored procedures, 137 views, 11 functions and one SQL Server Agent job, all scripted out of Management Studio.
CFATSAlertManager is a Windows service that wakes on a timer, finds facilities whose alerts have aged, and sends escalating e-mails. It is still a Visual Studio 2010 project. The repository README says so plainly: there was no need to migrate it.
Inside the library the layering is easy to see from the folder names:
CFATS (Web Forms pages, code-behind)
| reads Session, builds a Model object from controls
v
Assist.Usage FacilityUse, IncidentUse, AuditUse, ...
| one class per business entity; returns data
| and an ObjectState describing success or failure
v
Assist.Data.SQLServer
SQLManager one method per query (4,849 lines)
SQLUtility DataRow -> Model mappers, parameter builders
SQLProxy ad-hoc queries, scalar helpers
SQLHelper Microsoft Data Access Application Block
|
v
SQL Server: views (vw*), procedures, lookup tables
Alongside these layers sit Assist.Model (plain classes such as Facility, Incident, Drill, Training, VisitorLog) and cross-cutting helpers: DateHandler, ErrorHandler, ServerInfo (configuration), SecurityManager, EmailHelper, FileManager, MenuManager, XMLManager and a small Geography namespace for the maps.
A page uses the library the same way everywhere. It reads the current user and facility from session, builds a model object from its text boxes, hands that object to a Usage class and checks the ObjectState that comes back. The Usage class creates a SQLManager, calls one method, copies the manager's state, and maps the DataSet to a model with SQLUtility. SQLManager builds the SQL and calls Microsoft's Data Access Application Block, the classic SQLHelper from 2001, to run it. The product shipped with that block, and it is Microsoft's code, so I don't reproduce it here.
The library that traveled
CFATSLibrary did not stay in one product. The same classes, SQLManager, SQLUtility, SQLProxy, DataUtility, EmailHelper, FileManager and a BasePage, turn up in between 5 and 18 of my other client engagements. That depends on the class: the data classes traveled furthest. Across the whole archive there are 277 classes named SQLManager, 278 named SQLUtility and 342 named EmailHelper. Not all of them are mine, but a good share descend from this library.
Several things made it portable:
- No dependency on the product. The data, e-mail, file and date classes reference nothing in the web project. You could copy the folder into a new solution and build it.
- One connection string, one call.
new SQLManager(connectionString).GetData(sql)got a new team to its first screen of data in an afternoon. That ease is the whole reason a library spreads. - No exceptions to catch. Every class reported failure through an
ObjectStateobject instead of throwing. Developers who were nervous about exceptions liked that. It's also the part I regret most, as Recipe 17.2 explains. - .NET Framework 3.5. Targeting an old framework meant the DLL loaded into anything from a 3.5 WinForms tool to a 4.8 web site.
What didn't age well is the same list, read from the other side. A library that is easy to copy gets copied, not referenced, so each engagement ended up with its own fork and its own fixes. Building SQL with string.Format was quick to write and became the biggest liability. Swallowing errors into a state object made failures quiet. Reading configuration through static ServerInfo calls made every class hard to test. And the 3.5 target that made the DLL load anywhere also kept it away from async, using declarations, nullable reference types and everything else in this book.
Lessons from Visual Studio 2008 to Visual Studio 2022
The repository is a geological record. The library's project file still says OldToolsVersion 3.5, which means it was created in Visual Studio 2008 and upgraded in place. The database scripts were generated in May 2011 and still start with USE and the development database's name. There are .svn folders from the Subversion years beside a Git history. The repository it lives in was first created for a different internal project, and I kept it rather than lose the migration history. Here is what I learned from carrying all of that forward.
Upgrade what you deploy every week. Leave what you don't, and write down why. The web application moved to .NET Framework 4.7.2, a Visual Studio 2022 solution, and NuGet packages for ReportViewer 15, Bootstrap 5 and jQuery 3. It is deployed often, and it was worth it. The alert service stayed a Visual Studio 2010 project on .NET 4.0, and the README says so in one sentence. That sentence is worth more than it looks: nobody wastes a day wondering whether it was forgotten.
A library at the lowest framework is a library frozen in time. Keeping CFATSLibrary on .NET 3.5 let one DLL serve the web app, the alert service and other engagements. It also meant no async, no HttpClient, no TimeProvider and no modern C# features, for a decade. Today I would multi-target (net48;net8.0) in an SDK-style project, which gives old callers a build and new code the modern language.
Binary references drift. A common folder holds prebuilt copies of CFATSLibrary.dll, CFATSWebControls.dll and the AJAX Control Toolkit, and the README suggests linking to them "to speed things up." That works until the DLL in common is three fixes behind the source in the next folder. Reference projects, or publish the library as a package with a version number.
Copy-paste is a design decision. There are 18 RBPSn model classes, 18 RBPSnUse classes, 18 tblAuditRBPSn tables, 18 audit views and 18 nearly identical GetAuditRBPSn methods. One table of questions keyed by standard, with one set of classes, would have been a quarter of the code. When the regulation changed a standard, it would also have been a data change, not a release.
Test pages are not tests. 64 of the 295 pages are Test*.aspx: TestEmail, TestDataSQLManager, TestAlertManager and so on. They were how I tried things, and they shipped with the product. A unit-test project would have caught the UpdateIncidentFile bug in Recipe 17.2. A test page only catches what you remember to click.
Security debt is invisible until you look. Re-reading the data layer for this chapter, I found queries that build WHERE clauses from strings, and a login query I would not write today. If you maintain a long-lived product, schedule a pass that does nothing but read the data layer for string-built SQL and credential handling, with Chapter 7 open beside you. Do it before someone else does it for you.
The database outlives the code. The pages, the frameworks and the tools all changed around it. The views, procedures and tables scripted in 2011 are still there, and the green, yellow and red status logic in GetFacilityAlerts is still the logic the product uses. Invest in the schema: names, keys, transactions, UTC. It is the part you will keep.
A realistic modernization roadmap
No one rewrites a working compliance product in one go. The customers' inspections don't wait. This is the order I would do it in, with each step shippable on its own.
- Make it buildable from source in one step. Add CFATSAlertManager and the database to the solution. Convert the database project to an SDK-style SQL project (
Microsoft.Build.Sql) and strip theUSElines. Replace DLLs incommonwith project references. Add a build pipeline. - Close the security gaps first. Parameterize every string-built query (Recipe 17.1), starting with authentication and anything that takes a
string. Move credentials out ofweb.configinto protected configuration or a vault, and hash passwords properly (Chapter 7). - Turn the library into a multi-targeted package. SDK-style project,
net48;net8.0, nullable enabled for new files only. FixHandleExceptionso it logs and rethrows instead of swallowing. - Replace the alert service with the worker in Recipes 17.5 and 17.6. It is small, self-contained, and the highest-value fix: it is the part that e-mails people.
- Stop the session copying in the Web Forms app with a base page (Recipe 17.4, On .NET Framework), adopted as pages are touched.
- Strangle the web app. Put an ASP.NET Core application in front with YARP, which routes unported URLs to the Web Forms site. Port one module at a time, starting with the simplest (visitor logs) and ending with audits. Collapse the 18 RBPS copies into one data-driven module as you port it.
- Move reports last. The 115 RDLC files are the most expensive to move. They can be rendered on modern .NET with the community
ReportViewerCore.NETCorepackage, moved to SQL Server Reporting Services, or rewritten as needed with QuestPDF and ClosedXML (Chapter 11). Many have a screen, PDF and Excel variant. Count which ones customers actually run before porting any of them.
Steps 1 to 4 fit in a quarter for one developer and fix most of the real risk. Steps 5 to 7 are a year or more, done alongside feature work. That is fine. The point is that every step leaves the product better and deployable.
Chapter checklist
- Search your data layer for
string.Formatand+nearselect,insert,updateandwhere, and parameterize every hit, starting with login and anything that takes astring. - Find every place an error is captured into a state object or flag, and make sure each one logs. Then move unexpected failures to exceptions and keep results for validation.
- Wrap every multi-statement write procedure in
SET XACT_ABORT ON,BEGIN TRY, a transaction andTHROW, and test the rollback path once by forcing an error. - Count how many pages copy the same session properties. If it's more than a handful, create one base page or context service this week and adopt it as you touch pages.
- Check any timer-driven service for overlapping ticks, send-before-record ordering and a hard-coded tenant or client ID. Replace the timer with
PeriodicTimerin aBackgroundService. - Replace
System.Net.Mail.SmtpClientwith MailKit, send a plain-text part with every HTML mail, and require TLS. - Write one sentence in the README for every project you chose not to migrate, and why.
- Build your shared library from source as a versioned package or project reference, not a DLL copied into a
commonfolder.