Articles

Notes on SQL Server, automation, and public safety data, written while solving the actual problem.

Automation,

Automating file uploads and cleanup with Python and FTP

Keeping an FTP drop folder clean is tedious by hand. When a process depends on sending recurring log files, a script that uploads, archives, and cleans up on its own saves a lot of babysitting.

This script connects to a remote folder, uploads every CSV in a local folder, moves each sent file into a local archive, then deletes anything older than seven days from both the archive and the remote folder. It only uses Python's standard library.

import time
from ftplib import FTP_TLS
from pathlib import Path

FTP_HOST = "ftp.example.com"
FTP_USER = "upload_user"
FTP_PASS = "change-me"          # load from an environment variable in real use
REMOTE_DIR = "/remote/logs"
LOCAL_DIR = Path(r"C:\DataLogs")
ARCHIVE_DIR = LOCAL_DIR / "Uploaded"
MAX_AGE_DAYS = 7

cutoff = time.time() - MAX_AGE_DAYS * 86400
ARCHIVE_DIR.mkdir(exist_ok=True)

with FTP_TLS(FTP_HOST) as ftp:
    ftp.login(FTP_USER, FTP_PASS)
    ftp.prot_p()                # encrypt the data channel too
    ftp.cwd(REMOTE_DIR)

    # Upload, then archive locally
    for path in LOCAL_DIR.glob("*.csv"):
        with path.open("rb") as f:
            ftp.storbinary(f"STOR {path.name}", f)
        path.replace(ARCHIVE_DIR / path.name)
        print(f"Uploaded {path.name}")

    # Remove old remote files (needs a server that supports MLSD)
    for name, facts in ftp.mlsd(facts=["type", "modify"]):
        if facts.get("type") != "file":
            continue
        modified = time.mktime(time.strptime(facts["modify"][:14], "%Y%m%d%H%M%S"))
        if modified < cutoff:
            ftp.delete(name)
            print(f"Deleted remote {name}")

# Remove old local archive files
for path in ARCHIVE_DIR.glob("*.csv"):
    if path.stat().st_mtime < cutoff:
        path.unlink()
        print(f"Deleted archived {path.name}")

Run it from Task Scheduler or cron. If your server only speaks plain FTP, swap FTP_TLS for FTP and drop the prot_p() call, but treat that as a reason to ask for FTPS or SFTP.

Back to the list

Public safety,

See when calls peak: a call volume dashboard in Power BI

Dispatch centers handle thousands of calls, but staffing schedules are often built from memory of which shifts felt busy. CAD data already holds the answer. Pulling it into Power BI shows call volume by hour, day of week, and call type.

Start by importing the CAD incident table, or a view over it, with at least the call received time, dispatch time, arrival time, call type, and location.

Measures worth building

  • Calls by hour and weekday. A matrix with weekday on rows and hour on columns, formatted as a heat map, shows the peaks at a glance.
  • Call density by area. Plot incidents by latitude and longitude, or by beat or district if those are in your data.
  • Time intervals. Queue time (received to dispatched) and response time (dispatched to on scene).
Avg Queue Time (sec) =
AVERAGEX (
    'Dispatches',
    DATEDIFF ( 'Dispatches'[ReceivedTime], 'Dispatches'[DispatchTime], SECOND )
)

Use averages and the 90th percentile together. Averages hide the long waits that matter most.

Back to the list

SQL Server,

Import XML data into SQL Server with SSIS

XML still shows up in older vendor exports and government data feeds. SSIS has a built-in XML Source that turns an XML file into rows without custom parsing code.

Setting up the package

  1. In Visual Studio, create an Integration Services project and add a Data Flow Task to the control flow.
  2. Open the data flow and add an XML Source.
  3. Point it at your XML file. If you don't have an XSD, click Generate XSD and review the data types it guesses.
  4. Pick the output that matches the element you want, then connect it to an OLE DB Destination for your table.

After a run, check what landed:

SELECT NatureOfCall, COUNT(*) AS Calls
FROM dbo.AddressLogTable
GROUP BY NatureOfCall
ORDER BY Calls DESC;

Generated XSDs often type everything as strings. Set the real types in the XSD before you build the destination table.

Back to the list

SQL Server,

SSMS shortcuts worth learning

Writing SQL is half the job. Running it, reading plans, and finding objects takes the rest. A few shortcuts in SQL Server Management Studio keep your hands on the keyboard.

  • F5 or Ctrl+E runs the highlighted text, or the whole tab if nothing is highlighted.
  • Ctrl+R hides or shows the results pane when you need room to read a long script.
  • Ctrl+Shift+R refreshes IntelliSense so new tables and columns autocomplete.
  • Alt+Break cancels a running query, which you will want the first time you start an accidental cross join.

There is a searchable list on the SQL tools page.

Back to the list

SQL Server,

How to find and fix SQL Server index fragmentation

Inserts, updates, and deletes cause index pages to split, which leaves data stored out of order. SQL Server then reads more pages than it needs to, and range scans slow down.

The sys.dm_db_index_physical_stats function reports fragmentation per index:

SELECT
    s.name  AS SchemaName,
    t.name  AS TableName,
    i.name  AS IndexName,
    ps.avg_fragmentation_in_percent,
    ps.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ps
JOIN sys.indexes AS i ON ps.object_id = i.object_id AND ps.index_id = i.index_id
JOIN sys.tables  AS t ON i.object_id = t.object_id
JOIN sys.schemas AS s ON t.schema_id = s.schema_id
WHERE ps.avg_fragmentation_in_percent > 10
  AND ps.page_count > 1000
ORDER BY ps.avg_fragmentation_in_percent DESC;

LIMITED mode is fast and enough for this check. Skip small indexes; under about 1,000 pages, fragmentation rarely matters.

A common starting rule: reorganize between 10% and 30%, rebuild above 30%. The script generator writes that logic for a single index.

Back to the list

SQL Server,

Lock a SQL Server user to a single stored procedure

Giving an outside application or a new staff member direct table access raises the risk of mistakes and SQL injection. A safer pattern is to let them run specific stored procedures and nothing else.

Because of ownership chaining, a user with EXECUTE on a procedure can run it even without permissions on the tables it touches, as long as the procedure and tables share an owner.

CREATE USER [DispatchUser] FOR LOGIN [DispatchUser];

-- No role memberships beyond public, no table permissions.
GRANT EXECUTE ON OBJECT::dbo.UpdateCallLogs TO [DispatchUser];

-- Optional: make the intent explicit
DENY SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO [DispatchUser];

Test by connecting as that user and trying a plain SELECT against a table. It should fail, and the procedure should still run.

Back to the list

Public safety,

Using JSON to connect public safety applications

CAD, mobile data terminals, and records systems all need the same facts about an incident: where it is, what it is, and who is assigned. Older interfaces pass fixed-width or delimited flat files. JSON is easier to read, easier to extend, and supported by nearly every modern API.

{
  "incident_id": "CAD-2023-0492",
  "priority": "HIGH",
  "call_type": "Traffic Accident",
  "location": {
    "address": "100 Main St",
    "latitude": 42.2412,
    "longitude": -88.3162
  },
  "units": ["M31", "E31"]
}

Adding a field to JSON doesn't break a consumer that ignores it, which is a big improvement over flat files where one new column shifts everything after it. SQL Server can read it directly with OPENJSON.

Back to the list

Automation,

Building a C# folder watcher as middleware

When two applications can't talk to each other directly, a small service in the middle can. A common case is a legacy system that drops text files into a folder. A C# watcher picks them up, parses them, and writes the records to SQL Server.

using System;
using System.IO;
using System.Threading;

public static class FolderWatcher
{
    public static void Main()
    {
        using var watcher = new FileSystemWatcher(@"C:\LegacyDataInbox", "*.txt")
        {
            NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
            EnableRaisingEvents = true
        };
        watcher.Created += OnNewFile;

        Console.WriteLine("Watching for files. Press Enter to stop.");
        Console.ReadLine();
    }

    private static void OnNewFile(object sender, FileSystemEventArgs e)
    {
        // The file may still be open by the writer; wait until it can be read.
        for (int attempt = 0; attempt < 10; attempt++)
        {
            try
            {
                string[] lines = File.ReadAllLines(e.FullPath);
                Console.WriteLine($"{e.Name}: {lines.Length} lines");
                // Parse lines and insert into SQL Server here.
                return;
            }
            catch (IOException)
            {
                Thread.Sleep(500);
            }
        }
        Console.WriteLine($"Could not read {e.Name}");
    }
}

For production, run this as a Windows Service (a .NET Worker Service works well), log to a file or the event log, and move processed files to an archive folder so a restart doesn't reprocess them.

Back to the list

SQL Server,

Generate XML from SQL queries with FOR XML PATH

When a third-party system wants XML, SQL Server can build it directly from a query. FOR XML PATH turns rows into elements, and column aliases that start with @ become attributes.

SELECT
    c.CallNumber AS [@CADNumber],
    ct.Name      AS NatureOfCall,
    c.CreatedOn  AS Received
FROM dbo.[Call] AS c
JOIN dbo.CallType AS ct ON c.CallTypeID = ct.CallTypeID
FOR XML PATH('Incident'), ROOT('Incidents');

That returns one <Incidents> root with an <Incident CADNumber="..."> element per call. To write it to a file on a schedule, call the query from PowerShell or an SSIS package.

Back to the list

Automation,

Delete old files on a schedule with PowerShell

Full disks are one of the most common reasons an application falls over. Logs, reports, and temp folders grow until something stops. A short PowerShell script on a schedule prevents that.

$Path   = "C:\SomeFolder"
$Days   = 8
$Cutoff = (Get-Date).AddDays(-$Days)

Get-ChildItem -Path $Path -Recurse -File -Force |
    Where-Object { $_.LastWriteTime -lt $Cutoff } |
    Remove-Item -Force -WhatIf

Run it once with -WhatIf to see what would be deleted. When the list looks right, remove -WhatIf and schedule it in Task Scheduler.

Back to the list