Sunday, January 4, 2026

PendingModelChangesWarning Exception When Applying EF Migrations that Involve ASP.NET Core Identity

I have a couple of personal projects that use ASP.NET Identity for user management, and both of them ran into the same problem when running Entity Framework migrations with a dedicated project as shown in the Aspire examples. That is, a Worker Service project that runs the migrations in a BackgroundService.

The error looked like this:

System.InvalidOperationException: 'An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'MyContext' has pending changes. Add a new migration before updating the database. See https://aka.ms/efcore-docs-pending-changes. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.'

As suggested, I tried generating a new migration, but it was empty. After much AI-assisted debugging, it seemed to be an issue with the length of the columns on a couple of built in tables/classes:
  • IdentityUserToken
    • LoginProvider
    • Name
  • IdentityUserLogin
    • LoginProvider
    • ProviderKey
Some searching suggested that the default lengths of these have changed over the years and that they are adjustable for that reason. I have never specified the lengths in my code, so I don't know how they are being resolved to values different from what's in my DB. And this is only a problem when I run the migrations with the Worker Service project. When run from the command line tool, everything is fine.

As the exception mentions, there is a way to ignore this error, but then it would be ignored for all such future problems where you really forgot to add a migration.

The solution I found is to specify the lengths of the fields in OnModelCreating of my context:

builder.Entity<IdentityUserToken<string>>(entity =>
{
    entity.Property(m => m.LoginProvider).HasMaxLength(128);
    entity.Property(m => m.Name).HasMaxLength(128);
});
 
builder.Entity<IdentityUserLogin<string>>(entity =>
{
    entity.Property(m => m.LoginProvider).HasMaxLength(128);
    entity.Property(m => m.ProviderKey).HasMaxLength(128);
});

Thursday, January 1, 2026

Using Azure Functions with Managed Identity and SQL, Blob, Queue, and Event Grid Triggers

Like a good coding nerd, I spent (a surprising amount of) time figuring out how to Azure Functions with the following trigger types, all while using a managed identity:

  • SQL Table
  • Blob
  • Blob using Event Grid
  • Queue
Microsoft's documentation and logging in Azure is spread out. Twitter's Grok AI did a great job of helping pull it together when things weren't working.

To start, I created the 2 usual Aspire projects using Visual Studio 2022 and .NET 9, the ServiceDefaults and AppHost projects.

I then created my Functions project in Visual Studio 2022 using .NET 9 and the Functions project template, choosing the queue trigger template. This brings me to my first 2 complaints.

Complaint #1: The Functions template does not support the use of central package management. If your solution currently does you will immediately have a broken project until you adjust the project file and Directory.Packages.props. Knowing this, I used a project that does not use CPM.

Complaint #2: Azure Functions tooling is available 3 different ways on Windows, none of which I consider standard. 
  • There's a command line tool "func" that you install with an MSI called Azure Functions Core Tools. I would have expected templates that you install with the dotnet CLI.
  • There's something in Visual Studio that you need to update from the Options menu. It doesn't update by itself as far as I know. It's not just an extension, you have to hunt for it in the menus.
    Click that button and there's no progress meter. Just an ephemeral message in the bottom right corner of VS. I would have expected an extension or something that updates with VS every couple of weeks like VS does.
  • The Azure command line tool, azd. The docs say it requires the Azure Functions Core Tools, so maybe azd just calls func.
Which one is the latest? There's a github repo for func, so maybe that one. I don't know where the VS tooling lives on the internet.

Here is my AppHost.cs. I started with using named connections for the queue and storage connections, but when it came to configuring them in Azure it started getting very complex, so it's using the defaults. The SQL connection is for the SQL Table trigger. More details below.

var builder = DistributedApplication.CreateBuilder(args);
 
var db = builder.AddConnectionString("db");
 
var migrations = builder.AddProject<Projects.MigrationService>("migrationservice")
    .WithReference(db)
    .WaitFor(db);
 
var storage = builder.AddAzureStorage("storage")
    .RunAsEmulator(az => az.WithLifetime(ContainerLifetime.Persistent))
;
 
builder.AddAzureFunctionsProject<Projects.QueueTriggerFunction>("queuetriggerfunction")
    .WithHostStorage(storage)
    .WaitFor(storage)
    .WithReference(db)
    .WaitFor(db)
    .WaitForCompletion(migrations)
    ;
 
builder.Build().Run();

Over the years, a couple of Function defaults have driven me to distraction leading to my next 2 complaints.

Complaint #3: local.settings.json file is claimed to contain some secret values, so it is not included for commit by default in .gitignore. However, one critical value that everyone who works with the repo needs is "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated".

Complaint #4: something about the default logging setup makes sure only warning and above logging makes it to the Azure output. The Azure console relies SOLELY on this output to determine if your function ran, so logging something is critical. (Never mind that some other part of Azure knows it ran your function.)

I want local.settings.json committed, and I want to use the facility .NET Core already has for per-dev settings, secrets.json. Plus, using Aspire means the Function's project never needs settings in a config file anyway.

I also found some code that fixes the default exclusion of Information and below logging.

This is my Function project's Programs.cs. I added a simple config class and put a value for it in secrets.json to make sure the code uses it.


using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using QueueTriggerFunction;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Data;
using Microsoft.EntityFrameworkCore;
 
var builder = FunctionsApplication.CreateBuilder(args);
 
builder.AddServiceDefaults();
 
builder.ConfigureFunctionsWebApplication();
 
builder.Services
    .AddApplicationInsightsTelemetryWorkerService()
    .ConfigureFunctionsApplicationInsights();
 
builder.Logging.Services.Configure<LoggerFilterOptions>(options =>
{
    // The Application Insights SDK adds a default logging filter that instructs ILogger to capture only Warning and more severe logs. Application Insights requires an explicit override.
    // Log levels can also be configured using appsettings.json. For more information, see /azure-monitor/app/worker-service#ilogger-logs
    LoggerFilterRule? defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName
        == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
    if (defaultRule is not null)
    {
        options.Rules.Remove(defaultRule);
    }
 
    // Add a new rule to capture Information and above for AI
    options.AddFilter("Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider",
        LogLevel.Information);
    options.MinLevel = LogLevel.Information;
});
 
builder.Services.AddOptions<MyConfigurationSecrets>()
    .Configure<IConfiguration>((settings, configuration) =>
    {
        configuration.GetSection("MyConfigurationSecrets").Bind(settings);
    });
 
builder.Configuration
       .SetBasePath(Environment.CurrentDirectory)
       .AddJsonFile("local.settings.json", optional: true)
       .AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true)
       .AddEnvironmentVariables();
 
builder.Services.AddDbContext<DataContext>(optionsBuilder =>
{
    optionsBuilder.UseSqlServer(
        builder.Configuration.GetConnectionString("db"),
        b =>
        {
            b.MigrationsAssembly("Data");
            b.EnableRetryOnFailure();
        });
});
 
builder.Build().Run();

There's a Migrations WebJob project called Data like the ones seen in Aspire examples that creates the DB and a simple table. How the table gets created isn't important, so I'm not including that here. I will show the steps for enabling table change tracking later, though.

A word on NuGet versions as of December 2025:

  • Aspire 13 libraries
  • Latest Functions libraries
  • Latest .NET 9 libraries, except for Microsoft.Extensions.Configuration.UserSecrets, which is the latest 10.
I let VS publish the function to Azure in a .NET 9, Linux App Service. It created most of the environment variables that start with AzureWebJobsStorage, but I don't remember exactly which ones. I think it populated the storage account to use, but I don't remember how it knew. I also don't remember if I had already configured the managed identity to use, which helped it fill in the values. Anyway, here is the complete configuration:

The client ID value is the one with that name from the managed identity's properties:

The managed identity has the following role assignments for the storage account. They are probably more than is needed for just reading messages and blobs:
  • Storage Blob Data Owner
  • Storage Blob Data Contributor
  • Storage Queue Data Contributor
  • Storage Queue Data Message Processor
  • Storage Account Contributor
Something also assigned it the Monitoring Metrics Publisher role on the Application Insights resource that the function resource uses.

Some of these allow the managed user to list blobs/messages, and certain other ones allow it to read individual blobs/messages. It is not as clear as AWS's explicit list of actions. Again, Grok helped fill in my knowledge. At one point it showed me how to enable diagnostic logging on the storage account and look up the authorization failure in a Log Analytics Workspace.


Queue Trigger

The queue trigger code is almost the stock template code.

using Azure.Storage.Queues.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
 
namespace QueueTriggerFunction;
 
public class QueueTriggerFunction
{
    private readonly MyConfigurationSecrets _myConfigurationSecrets;
    private readonly ILogger<QueueTriggerFunction> _logger;
 
    public QueueTriggerFunction(ILogger<QueueTriggerFunction> logger, IOptions<MyConfigurationSecrets> myConfigurationSecrets)
    {
        _logger = logger;
        _myConfigurationSecrets = myConfigurationSecrets.Value;
    }
 
    [Function(nameof(QueueTriggerFunction))]
    public void Run([QueueTrigger("myqueue-items")] QueueMessage message)
    {
        _logger.LogInformation("Using secret: {Secret}", _myConfigurationSecrets.Secret);
        _logger.LogInformation("C# Queue trigger function processed: {messageText}", message.MessageText);
    }
}

At this point, if you create a queue called myqueue-items and add a text message, the trigger should fire. I did this using the Azure portal. For some reason, even though I'm an Owner on the account, I had to add the following rights for myself to use the storage explorer in Azure:
  • Reader
  • Storage Blob Data Contributor
  • Storage Queue Data Contributor


File Trigger

The file trigger code is also almost as simple as the template:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
 
namespace QueueTriggerFunction;
 
public class FileTriggerFunction
{
    private readonly ILogger<FileTriggerFunction> _logger;
 
    public FileTriggerFunction(ILogger<FileTriggerFunction> logger)
    {
        _logger = logger;
    }
 
    [Function(nameof(FileTriggerFunction))]
    public async Task Run([BlobTrigger("uploads/{name}")] Stream stream, string name)
    {
        using var blobStreamReader = new StreamReader(stream);
        var content = await blobStreamReader.ReadToEndAsync();
        _logger.LogInformation("C# Blob trigger function Processed blob\n Name: {name} \n Data: {content}", name, content);
    }
}

At this point, everything is already set up to allow the file trigger to run when you upload a text file to a blob container called uploads.


SQL Trigger

The SQL trigger code:

using Data;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.Sql;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
 
namespace QueueTriggerFunction;
 
public class SqlTriggerFunction
{
    private readonly ILogger _logger;
 
    public SqlTriggerFunction(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<SqlTriggerFunction>();
    }
 
    // Visit https://aka.ms/sqltrigger to learn how to use this trigger binding
    [Function("SqlTriggerFunction")]
    public void Run(
        [SqlTrigger("[dbo].[TodoItems]", "db")] IReadOnlyList<SqlChange<ToDoItem>> changes,
            FunctionContext context)
    {
        _logger.LogInformation("SQL Changes: " + JsonConvert.SerializeObject(changes));
    }
}

As I mentioned, I created the DB and its single table with a WebJob that ran an EF migration. We need to do a few things to make the SQL trigger work:
  1. Add the managed identity to the DB and give it the DB roles needed to read from the DB
    CREATE USER [queue-trigger-user] FROM EXTERNAL PROVIDER;
    ALTER ROLE db_datareader ADD MEMBER [queue-trigger-user];
    ALTER ROLE db_datawriter ADD MEMBER [queue-trigger-user];
    ALTER ROLE db_ddladmin ADD MEMBER [queue-trigger-user];
    
  2. Enable change tracking on the DB
    ALTER DATABASE [function-test]
    SET CHANGE_TRACKING = ON
    (CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
    
  3. Enable change tracking on the table
    ALTER TABLE [dbo].[ToDoItems]
    ENABLE CHANGE_TRACKING;
    
  4. Grant the DB identity the ability to see change tracking events on the table
    GRANT VIEW CHANGE TRACKING ON OBJECT::dbo.ToDoItems TO [queue-trigger-user];
    
We also need to configure the "db" connection string. None of the examples on the SQL DB connection string page in Azure are correct. The closest one is the "ADO.NET (Microsoft Entra integrated authentication)" one, except with the managed identity's Client ID in place of the User ID, and Authentication = "Active Directory Managed Identity".

If things are not working, one place I found errors is in the traces in the Live Metrics view of the Application Insights. Nothing showed in the Failures view when the SQL trigger wasn't showing.

Complaint #5: Logging in Azure for Functions, and Azure in general, is in so many places, unlike AWS and its CloudWatch system. There seems to be a lot more that needs to be enabled manually, like when diagnosing access problems to storage. Also, inconsistent time display. Some allow switching between local and UTC, some are only local, some are only UTC. Long delays in some cases e.g. 5 minutes between a function running and it showing in the console.

Complaint #6: The ways to allow resources in Azure to access other resources are too many. And once you've chosen a method, there can be many different ways to configure that one method. E.g. providing a config entry for each storage service (blob/table/queue) vs. a different one that points to the overall storage account. In the storage account case it tries one approach, then another. If you've accidentally provided a config that's partially one and partially the other, you'll have a hard time trying to understand why it's unhappy.

At this point the SQL trigger was working properly.

Event Grid-Based Blog Trigger

I read somewhere that at scale the direct blob trigger is not the best choice and that you should use an Event Grid-based blob trigger. The code looks like this:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
 
namespace QueueTriggerFunction;
 
public class FileTriggerEventGridFunction
{
    private readonly ILogger<FileTriggerEventGridFunction> _logger;
 
    public FileTriggerEventGridFunction(ILogger<FileTriggerEventGridFunction> logger)
    {
        _logger = logger;
    }
 
    [Function(nameof(FileTriggerEventGridFunction))]
    public async Task Run([BlobTrigger("uploads-eventgrid/{name}", Source = BlobTriggerSource.EventGrid)] Stream stream, string name)
    {
        using var blobStreamReader = new StreamReader(stream);
        var content = await blobStreamReader.ReadToEndAsync();
        _logger.LogInformation("C# Blob trigger function via event grid Processed blob\n Name: {name} \n Data: {content}", name, content);
    }
}

Almost the same as the blog trigger, but the Source is set to Event Grid. This is not the same as a pure Event Grid trigger, which would receive an object that describes the event instead of a ready-to-use Stream.

You wire the storage event to the function as a web hook, so you have to build a funky URL to call. This page details how to build it. Overall it's

https://<FUNCTION_APP_NAME>.azurewebsites.net/runtime/webhooks/blobs?functionName=Host.Functions.<FunctionName>&code=<BLOB_EXTENSION_KEY>

The BLOB_EXTENSION_KEY comes from the App keys section of your function resource

In my case I wanted only uploads in a specific container to fire events so I had to specify a filter on the event e.g.

/blobServices/default/containers/uploads-eventgrid/blobs/

After all that my Event Grid function started firing when I loaded to uploads-eventgrid.

Summary

I do not find Azure easy to work with. Granted, I've only ever deployed my own little personal projects, while I have built an actual production-quality project in AWS with a team. But the differences in the consistency of experience across services in Azure vs. AWS is glaring. There are fewer ways to do things in AWS, and that's probably due to the history and organization of each company. Azure is starting to introduce AI helpers directly in Azure, but I haven't found them nearly as helpful as pasting errors into Grok. As long as you can find those errors.

Friday, July 5, 2024

Invalid Signature on AWS SNS Message

Amazon Web Services has a service called Simple Notification Service, which does what it says on the tin: it sends notification messages. In my case, I was sending SNS messages to an Azure Function via HTTP calls when an email is undeliverable.

These messages have a cryptographic signature and a link to the certificate that AWS used to sign the message. You can use these to ensure the message came from AWS unchanged. Amazon has libraries to do this in various languages. I was using the .NET one.

I captured the message by having the Node-based Azure function log it to the console e.g.

console.log(request.body);

I copied the output from the Invocation list in Azure Functions and put it in a .json file.

I wrote some C# code to load the file from disk, then loaded it into an AWS SNS Message object with its ParseMessage method. Finally, I called IsMessageSignatureValid on the message. It returned false. Huh?

I suspected that something about logging it to the Azure UI or saving it to disk had somehow mangled it. Maybe something got double escaped/encoded.

To double check what AWS sending I subscribed an AWS SQS queue to it so that I could see what that captured. I knew you could look at the messages in the AWS UI.

Looks the same doesn't it? Other than the cut off UnsubscribeURL, which isn't where the problem is.

I saved it to disk and looked through it character by character. I finally noticed the one in the AWS UI had 2 spaces instead of 1 between these 2 bits:

multipart/alternative;  boundary

The AWS UI puts the contents in a <textarea> tag, which preserves all whitespace. The Azure UI uses a <span>, which does the usual HTML thing of condensing all subsequent spaces to 1, unless they are &nbsp; characters.

I put an extra space in the file I'd created from Azure's UI and IsMessageSignatureValid finally returned true.


Sunday, July 9, 2017

Dependency Inversion and Microsoft Web Technologies

When I started learning C# and ASP.NET about 10 or 15 years ago (!!), we rendered HTML with Web Forms and published services with ASMX Web Services. A little while later we moved on to WCF services.

One of the limitations of those technologies was that the framework would only call the default, parameterless constructor of the page and service classes. To allow unit testing, I used "poor man's" dependency injection (DI), which I learned from Jean-Paul Boodhoo's videos on DnRTV. This is the approach where you have 2 constructors: a default one that calls the other one, which takes instances of all needed dependencies. The default constructor created instances of concrete classes that implemented interfaces. E.g.

I don't remember using, or even looking to mock frameworks. I think we created custom mocks by creating test classes that implement the interfaces and allowed customizing responses. I'm not sure which inversion of control (IoC) containers existed for C# then, or mock frameworks. If they existed, they were probably open source, which was frowned on at the bank at the time, even if just for testing. If they were allowed it involved some paperwork, anyway. (Banks like to have big companies they can call when they need support and who will be around a while.) Our pages and unit tests looked something like this:

This is fine if all you want to do is unit test. But what if you want to do integration testing, where you mock out the layer where you cross into other people's code e.g. the database or an external service? You'd have to do something like this:

This wasn't something we tried to do at the time. We were a pretty inexperienced bunch. (Programming at a bank vs. programming at a software company is like practicing law at a bank vs. at a law firm.)

If I'd have known more about the dependency inversion principle then, I would have been very skeptical about putting up with this limitation. I would have immediately gone searching for ways to insert something into the web request pipeline to control page and service creation. If I need to replace an implementation at the bottom of a dependency graph, it should be as easy as replacing one interface registration in an IoC container.

Searching the web now it looks like it was possible, but not in an a way that made you feel good. They look like hacks, or the domain of .NET experts. If you wanted to stick to the SOLID principles, though, it's what you should have done.

I do find it surprising that Microsoft gave us frameworks based primarily on object oriented languages (C#, VB.NET) that didn't let you observe object-oriented (OO) practices. Every example from that time involved creating instances of concrete classes in the page or service classes themselves. I even remember one example that told developers to drag and drop a new SqlConnection object onto every page. Not very maintainable. Perhaps Microsoft didn't think the existing MS web developers of the day could embrace these concepts, so many being ASP/VB6 devs.

Whatever the reason, these limitations lead to some particularly gnarly code, completely lacking in abstractions and injection points. For example, the WCF service I'm currently tearing apart to allow mocking out the bottom-most layer. It goes something like this:

The WCF class calls static methods. The first time one of them is called, it initializes a static instance, that is, a singleton, of an object that has instances of database and service classes. If you replace one of those instances during a test, you must set it back to null for reinitialization when you're done, or have every test set it before it runs. This is what you get when you ignore the SOLID principles.

It wasn't until ASP.NET MVC 3 that Microsoft built IoC into ASP.NET MVC from the start, allowing controllers to take dependencies in constructors. Until then, people used IoC containers that implemented the complex looking code that allowed using DI in ASP.NET. I'm still surprised that it took so long for them to bake this in.

The next time I look at a technology that is based primarily on an OO language, I'll be looking for the injection points, no matter how complex they are to use. If they don't exist, the technology will need a very compelling reason for me to use it.

Saturday, February 18, 2017

WebAuthenticationBroker and OAuth2 UserCancel Error

Windows Phone 8.1 programming can be a little... opaque. Yes, I was working on a Phone 8.1 project. My phone can't be upgraded to 10. I'm in the less than 1% of phone users.

I wanted to build an app that can do OAuth2 authentication, so I started with an example from IdentityServer3.Samples on GitHub. It uses WebAuthenticationBroker to present the OAuth server's UI to the user. A client with an ID of "implicitclient" was missing from Clients.cs, but I just copied one of the JavaScript implicit flow clients. The sample worked - I could get both an ID token and an access token at the same time.

I created a similar Client.cs in my existing project and pretty much copied the sample WinPhone example. I could get an ID token from my server and I could get an access token. But not both at the same time.

The WebAuthenticationResult.ResponseStatus value was WebAuthenticationStatus.UserCancel, a very generic error that has many sources. The ResponseErrorDetail property had a more specific error number, 2148270093. I couldn't find many references to this number on the web, but in its hex form, 0x800C000D, I found results. It's a "URL moniker code" produced by IE meaning INET_E_UNKNOWN_PROTOCOL. The description is "The protocol is not known and no pluggable protocols have been entered that match." Still not much to go on.

The callback URL for Phone 8.1 apps starts with ms-app://, which I thought maybe wasn't being recognized. I pointed my Phone app at the sample server and I could get both tokens at the same time.

I debugged the Phone app and grabbed the URL from both my auth server and the sample one. The sample server's callback URL was quite a bit shorter. It started to dawn on me that Phone 8.1 uses IE11 and that it might have a fairly conservative URL size limit. It turns out it's 2083, which is not long enough to hold both of my server's tokens. My signing certificate's key is twice the size of the sample servers, making the token signature twice as long.

So, how to shorten the URL?

I was needlessly including some claims, so I cut them out. I read that elliptical curve keys are shorter, which makes for shorter signatures. IdentityServer3 doesn't have support for EC certificates out of the box, so that would have been some work.

Then I finally stumbled across the idea of reference tokens. It turns out that they are the typical way to shorten an OAuth2 callback URL. Instead of the entire access token the URL contains a short identifier. Clients send the identifier to the server and the server looks it up from its database.

After 3 or 4 days of beating my head against the wall, problem solved. Now I can login.

Wednesday, December 14, 2016

Don't be Afraid of SingleOrDefault - Much Worse, Performance Problem Edition

I found another example at work of someone not taking advantage of SingleOrDefault when making Linq-to-Sql calls, but in a much worse way. I previously mentioned the use of Any() and First() in https://jamesmclachlan.blogspot.ca/2014/05/dont-be-afraid-of-singleordefault.html.

The new example constructs a query and calls Any() to test for the presence of at least 1 result. Any() is very efficient on its own because it uses SQL's EXISTS to just check for at least 1 record without reading anything about the record. This isn't a problem on its own.

Unfortunately, this was followed by a call to ToList() and then [0] to get the first item, instead of First(). The effect of ToList()[0] is to run the query and pull every one of the matching records into memory and then take the first item. First() at least tells SQL to only return the TOP 1 item.

Even worse is that because of faulty logic the code fails to add any query parameters, loading ALL of the records in the system of a particular type. Production has many tens of thousands of such records. Luckily, it only does this in a very specific case. If anyone has ever seen a problem they haven't reported it.

So it's not enough to hunt down uses of First() and FirstOrDefault(). We also need to look for ToList()[0], or perhaps all uses of All().


Friday, October 14, 2016

Handling User Data Securely - Really, Really Securely

Imagine you're building a web app that requires a password from a user for encryption. This password is not the same as their login one, it's used only for encrypting and decrypting their data in the browser. The user enters the password, the app uses it to generate an encryption key that the browser can use and then encrypts and uploads data. Later, the user types the password in again so that they can work with the encrypted data.

One of the things your app promises is that it never stores the password on the server in any form that another party could intercept or crack. And if someone compromises the user's computer or it gets stolen or seized the app promises that there is no trace of the password left behind.

This means never including the password or a hash of it on any posts to the server, neither in form submissions nor AJAX calls nor in something like ASP.NET Webforms view state. Similarly, the app must not save the password in any form to a persistent store like the browser's local storage or one of the database systems that some browsers support.

What options do you have for building such a system with a typical web system that involves form posts like ASP.NET MVC or WebForms?

There are 3 ways a web app typically persists data that the user enters from one page to another:
  1. cookies written to disk by the browser and sent back to the server with the page request
  2. a view state system that includes bits of data in hidden form fields
  3. session storage in the browser to leave data behind for the resulting page to read
The first 2 obviously send data to the server, so they are not solutions. The third one does't send data to the server, and it might seem as good as being only in memory. However different browsers treat it differently. They don't all clear it when you close the browser, and if the browser dies or the power goes out it may be left on disk.

You might be tempted to encrypt the value before writing it to view state or session storage, but who controls that encryption key? If you do, then you have to manage it and may have to reveal it under court order. If you generate a key in the user's browser, then you have the same problem of storing something between page views.

You conclude that the you can only hold the user's password in memory, meaning a JavaScript variable. The problem is that they disappear every time you visit another page. The easiest solution to program is for the app to ask the user to enter their password on every page that needs it. Not exactly a delightful experience.

Obviously you want to minimize the number of times the user enters their password. One approach would be for the app to have a field that collects the password, perhaps at the top. The rest of the page performs AJAX-y form posts that submit encrypted data, receives HTML from the server and updates the DOM with the response. Something like WebForms' UpdatePanel or Ajax.BeginForm in MVC.

If the user navigates to another part of the app that doesn't need the password, though, they have to reenter it when they return. This might be an advantage because the app only asks for the password in applicable contexts. Users would learn to do everything they need to before navigating, or they'd use 2 browser windows or tabs.

You could get the number of times the user needs to enter the password down to once per use session by using a single page app (SPA). If the app is all JavaScript and AJAX calls for data then it can keep the variable holding the password alive for the entire duration of use. If the user closes the window the password evaporates. (Well, it might still be sitting in RAM or on disk in a virtual memory file, but this seems beyond our control in a browser.)

SPAs have an entirely different development process that you may have to learn, especially if you are used to server side web development (ask me how I know :). Putting your time in to learn will be worth it, though, if you want to give the user the best possible experience of entering a secure value exactly once.

Sunday, July 17, 2016

Code Learnability vs. Feature Addability

I'd like to talk about made up words.

No, really I'd like to talk about the tension between making a code base easy to learn vs. the ease of adding things to it, specifically about web applications.

Imagine you had a slider control for your code that went from "easy to learn" to "easy to maintain".

When you slide the control all the way over to "easy to learn", most of the classes disappear along with all of the interfaces and many if statements appear. Methods balloon in size and contain duplicate logic because there are so few classes to encapsulate it. It's very easy to trace data and logic through calls up and down the stack. Anyone reading the code will come across all of the decisions it makes. The reader won't have a good sense of why the code does what it does, though. The lack of little methods like DetermineRanking or classes like RankingEngine mean that such code lives all over the place.

At "easy to learn", you can give a new developer your codebase and they'll be productive very quickly with little mentoring. Need to add a new data field when adding a customer? Just find the giant AddCustomer method or click button event handler and change line 654. A quick bit of functional testing shows that more related logic lives down on line 1233.

Oops, the same logic appears in SaveCustomer and now you can add a customer with a new field but users can't update it. QA or, even worse, customer support opens a bug, new developer finds duplicate logic, copy, paste, fixed. Again and again.

In some organizations, this is totally acceptable to devs, managers and customers. They can hire less skilled, cheaper developers and undercut the competition. Their customers are probably buying the software for some cost center in their business, so spending as little as possible is the goal. Everyone here operates at the low end of some market, which might make sense at the moment. As the dev shop or the customer grows they'll try to level up the software they make or use.

(The field of Economics contains an idea that ideally every product exists at every quality and price point so that everyone can afford the version of a product that fits precisely with their income. If there were only shacks and mansions to live in you'd have to live in a shack until you can afford a mansion. Better to have a wide range of housing options, especially within a neighbourhood.)

I'll bet the development shop's employee turnover is pretty high, though. As soon as a dev learns a little more about development they look for a more advanced employer. Again, some companies accept this and keep hiring from the ever growing pool of junior developers, which is fine.

I'll also bet that successfully adding features takes weeks, including writing code and back and forth with QA. Such code is not unit testable, so people find all bugs during end to end manual or automated testing.

At the other end of the slider, "easy to maintain", classes and interfaces abound, if statements largely disappear, but the structure obfuscates the code's flow. Frameworks and libraries, like inversion of control (IOC) containers and request pipeline handlers, automatically set up actions and dependencies. This means that for the app to know what to do with a class or method you only have to put a specific interface or attribute on it.

The experienced developer's productivity goes way up and bugs go way down because of unit testability and the inherent design (e.g. code no longer allows the string "0" or "1" for values, it uses booleans). However, the major trade off is the learning curve and cognitive load of the code base. The concept count goes through the roof. With so many classes and seemingly magic behaviour, new developers need a lot of guidance with the design. That could be in person or in a recorded video or design docs.

(I recently experienced this myself looking at code samples that rely exclusively on IOC containers to resolve dependencies. Some containers use an easy to follow "map interface IFoo to class Foo" syntax, while others use "map all of Foo's interfaces to Foo". The latter makes it harder to find the thing that maps IFoo to Foo with Visual Studio's Find All References because IFoo doesn't appear in the mapping. I even found one IOC container with a convention-based mapping method like "map all classes in assembly X to the interfaces matching their names". This meant that neither the classes nor the interfaces appear in the container setup code. Unless you find the conference video or series of blog posts where the author goes from original code to the heavily refactored version, you can end up puzzling over the approaches you see.)

Adding features now takes days and involves mostly one way trips through QA.Production bug counts due to actual code problems go down.

The code now requires more experienced developers who demand higher pay. This causes the software to cost more. Customers are happy to pay, though, because the software "just works", which they need to keep their profit centers working. Turnover drops.

There is a joke (belief?) in programming that the more complicated and obscure the code the more job security you have because only you know how to update it. This depends on what makes the code complicated, though, and what the benefit is to the company. Are you using well documented but advanced libraries that do a lot of heavy lifting, or are you writing 1000 line methods of bit shifting code with single letter variables?

Friday, April 1, 2016

It Doesn't Matter How They Get The Data

I was reading about using the SecureString class. This is a class that encrypts a string so that it is readable only on the current machine so that it does not hang around in plain text. Strings in C# are immutable, so they stick around until they are garbage collected, even if you set your reference to a string to String.Blank (""). The typical use is to collect the value from the user directly into a SecureString and shuttle it around on the current machine. As soon as it leaves the machine it must be turned back into a plain string, which is not a best practice.

I was looking into using SecureString in ASP.NET to handle a password. That password is passed in in plain text, and probably again when you actually use it, so there would be more than 0 instances in clear text in memory. Most StackOverflow answers point this out, but it would at least cut down on the number of instances as it is passed from method to method. Strings are a value type, meaning that every time you call another method with one as an argument .NET creates another copy.

In addition, I kept coming across the same kind of comment:

Yeah, no one has ever been able to read a remote, web-accessible machine's memory. Until they could.

This reminded me of a comment a co-worker made about something you could do with a value from one of our databases: "How could anyone get it?"

It doesn't matter.

How did they get the Ashley Madison data? How did they get the Sony data? How did they get the U.S. Office of Personnel Management data?

It doesn't matter.

What matters is what more they can do with it. This is called "pivoting", or using one breach to hop a level deeper. Security through obscurity works until your whole database appears on the web. Any SQL system is one SQL injection vulnerability away from giving up everything. Any software involved in serving web requests is a buffer-overflow bug away from barfing memory.

Practice defense in depth to limit a small compromise from becoming much bigger.



Friday, March 13, 2015

Assert.DoesNotThrow Does not Preserve Stack Traces

Just a short post about an issue with an NUnit feature.

It has an assertion called DoesNotThrow that takes a delegate function as an argument. If the delegate throws an exception then NUnit will throw its own exception. The method is great at pointing out exactly where the code under test is. However, if an exception does occur, NUnit reports the exception type, but looses the original stack trace. There have been enough occurrences of lost stack traces that I've stopped using it. Now I just comment the actual test line and let the exception bubble up to the test runner.

Wednesday, March 4, 2015

Make Classes not Enums

The main C# code base I work with at work is full of generic objects and methods written to use enums to drive behaviour. I'm not sure of the reason. The people who created it have all since moved on, so I don't know who to ask. All I can do is live with the giant switch statements and undo them into classes when I can. Why classes? Let's take a look.

The full example code base on which the gists are taken is available in https://github.com/claq2/MakeClassesNotEnums.

The (Evil) Enums Way


Say you have a service that creates different kinds of backup jobs. One of its arguments is an enum that indicates what kind of job to create. It returns only 1 kind of object, Job, that is not abstract. This object represents all the different possible kinds of jobs. A property, JobType, indicates whether it's for backing up files or a SQL database.

In this example, creating a job means calling a single CreateJob method that takes an enum argument that indicates the type. This might seem contrived, as in "who would build this", but it's easy for a UI to consume. Show the user a drop down with the job types and call the one method with the user's choice in the enum.

In object oriented programming there is something called the Single Responsibility Principle. It states that a class should have only 1 reason to change. Another way to put it is that a class should have exactly 1 concern. The enum approach violates this in at least 2 ways.

First, the Job class represents all possible job types. It needs properties for every job type. A change to any job type or the addition of a new one means changes to this class. Some properties apply to all types and some apply to only some types. How do upstream developers of the Job class know which properties to fill in for each type? They have to look at the documentation. I hope they don't miss one of the comments.

Second, the JobService has 3 concerns - determining which type of job to build, verifying the values and mapping input values to properties. If any of these aspects change this class must be updated. The more you need to change it, the more risk there is that you will introduce a bug. Especially if the switch has many clauses with pages of complex logic.

The cyclomatic complexity of this method is already 7, meaning you need at least 7 unit tests to completely cover it. This approach will only get harder to test fully and understand. There's already a little extra logic for Sql2014Jobs. How long before the logic becomes so tied together that you have to write tortured logic to get exactly what you want?

Think about what load and save methods in the JobService class will look like. Nearly the same - more switches with extra if statements for the special cases.

The (Righteous) Classes Way


There are 2 sources of cyclometric complexity in a system - the conditions that the business defines and those created by developers. You usually can't reduce the business's conditions, but you should be able to control the developer-created ones. The way you do this in an object oriented system is usually with classes and inheritance.

In this example one might wonder why the interface doesn't already know what kind of job it need to create in response to the user's actions. Well, it does. Outside of a text-menu driven console app, there shouldn't be any logic needed to decide what to create. The user chose to click on a button or use a drop down to pick the job type. The UI now has enough information to call a job-specific method and expect a job-specific result. Hence, separate job service classes.



No conditional logic. The logic for SQL 2014 jobs is contained in a class that only has to do with SQL 2014 jobs. Any change to File jobs does not involve anything related to any other job or the services. As written, the services don't really add any value to consumers. They could just use the job constructors themselves. Imagine they had load and save methods, though. Those methods will be specific to the job types.

The logic for constructing the SQL 2014 job's instance name and for rejecting non-root path file job is now in those classes. There is no chance that a change to file job logic could impact other job types.

A Hybrid Approach


Let's say you have a system that looks like the first example that has a single method and for non-technical reasons you cannot easily change the interface. Are you stuck? No.

Change the service to be or use a factory, as in the factory pattern. Job-specific logic is still in separate classes and the service now has just 1 responsibility - to invoke the right service and return the result.

It is a lot more code than the original enum-only version, but it more closely follows the SOLID principles that make software more maintainable. The other classes are the same as in the class version, except the AbstractJob class. It now has an abstract ToJob method that each specific job class must implement to convert itself into a generic Job object. Again, this logic is encapsulated inside each specific class.

Summary


Enums and switches make for less code, but over time it becomes harder to understand and more easily broken. In an object-oriented language classes are there to segregate logic and responsibility for better maintenance. It's a little more code, but you will introduce less bugs.

Wednesday, January 21, 2015

Handling Exceptions: Everything You Ever Wanted To Know

Exceptions have been around for a long time, but some seemingly experienced people still struggle with them. I will explain how to handle and communicate them in various .NET applications.

All exceptions in .NET inherit from System.Exception. You can't throw an instance of just any class; it must inherit from Exception. So, catching Exception means that nothing will get past your catch clause.

If there is a specific type of exception that you know you can handle, you must catch it before more general exception types. The class inheritance structure indicates which exceptions are more specific. ArgumentNullException inherits from ArgumentException, which inherits from Exception. So, if you want to handle the null exception differently from the argument exception, you must catch the null exception first. Each exception will be caught only once and by the first catch block that matches.

You can also add a "finally" clause after your catch clauses, in which you run code that must be run whether there was an error or not.

In the above examples and the following ones you'll see a variable called ex that holds the Exception object. You don't have to declare such a variable if you don't need a reference to it. Also, omitting the exception is the same as catch (Exception).


Default Exception Handling


Before we discuss how and when to handle exceptions, let's first look at how .NET handles them if our code doesn't.

Here is the code for a set of apps that throw exceptions in different ways: https://github.com/claq2/Exceptions

Console


Any exception in a console app, whether on the main thread, a new Thread/ThreadPool thread or started with the await keyword produces this:

Very straightforward, no ambiguous choices for the end user.

WinForms


When a WinForm application generates an exception on the UI thread that the code doesn't handle (e.g. in a button click event handler), .NET shows the user this:

What's a user to do? In my opinion, this is too much information for a non-developer to deal with, and the user has no idea what each choice's implications are. Do not rely on this dialog for end users. We'll see how to avoid this later.

If you start a thread, either using new Thread or ThreadPool.QueueUserWorkItem, and it generates an uncaught exception, .NET will terminate the application:

I have a Debug option here because Windows knows I have a debugger installed (Visual Studio). Again, we'll see how to prevent this later. The runtime will log this in the Application Event log along with the stack trace.

An exception thrown on a thread started with await results in the same prompt as the exception on the UI thread.

When you let .NET's manage your threads one thing it gives you is much better exception handling. Though again, the user must make an uninformed choice. The runtime doesn't add anything to the event logs because it handled the exception.

WebForms


An exception on the thread that is executing a web page request (e.g. in Page_Load or a button click event) shows:
Also known as "the yellow page of death". Only this request has come to an end. The system is still serving other requests. By default, when the request originates outside of the web server there is no stack trace giving away potentially sensitive information about the app. When viewed on the web server it will show more information. There is no event log entry because the runtime handled the exception.

The same thing happens when an uncaught exception is thrown on a thread started with await. Again, .NET handles it gracefully.

A truly insidious thing happens when a ThreadPool thread or one started with new Thread throws an unhandled exception: the .NET worker process dies. The symptom might be invisible to the user that caused it, but every request that w3wp.exe process was serving will come to an end. If the app uses in-process session state, those sessions will be lost. If the app uses Windows authentication, all of the auth sessions are gone and users will need to re-authenticate. (Ask me how I know! :) We'll see how to guard against this later. The runtime will record the exception along with the stack trace in the Application event log.

By default, the settings for an Application Pool (the thing the runs your ASP.NET website AKA the worker process w3wp.exe) will disable the pool if something kills the pool 5 times in 5 minutes. This is called Rapid-Fail Protection. When this kicks in, IIS returns HTTP 503, Service Unavailable for subsequent requests. If you find yourself having to disable this feature then I hope it's a short term mitigation while you hunt for the thing that's throwing exceptions on background threads.

WCF


An exception thrown on the main thread or an async thread sends an HTTP 500 error with this XML:


<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
<faultstring xml:lang="en-US">The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the &lt;serviceDebug&gt; configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.</faultstring>
</s:Fault>
</s:Body>

</s:Envelope>


The WCF proxy that Visual Studio/wsdl.exe generates throws a System.ServiceModel.FaultException. As the text above indicates, you can have the server send the server code's stack trace by changing a web.config setting. This might be acceptable in a development environment, but you don't want your service leaking implementation details in production.

Exceptions on background threads kill your ASP.NET worker process, w3wp.exe, just like WebForms. It's the same engine and threading mechanism. Again, the runtime records it in the Application event log.

MVC


Like WebForms, both exceptions on the thread processing a request and on a thread started with await result in an error page:
And like WebForms, an exception on a background thread (new Thread, ThreadPool) kills the w3wp.exe process serving the request, with all the same effects. This includes an Application event log.

WebAPI and HttpClient


WebAPI is very webby. Exceptions on the main thread and async threads that are not wrapped up into an HttpError and HttpResponseException result in an HTTP 500 Internal Server error and the following JSON:

{"Message":"An error has occurred."}

You can have WebAPI send more information by setting config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always in WebApiConfig.cs's Register method. With this enabled, an exception not thrown as an HttpResponseException will send:

{"Message":"An error has occurred.","ExceptionMessage":"Oh noooo!","ExceptionType":"System.Exception","StackTrace":"   at MVC.Controllers.ExceptionController.Get() in c:\\Users\\xyz\\Documents\\GitHub\\Exceptions\\MVC\\Controllers\\ExceptionController.cs:line 19\r\n   at ..."}

Oddly enough, wrapping up a caught exception in an HttpError and throwing HttpResponseException will cause the stack trace to be null.

There are 2 ways to detect an error with HttpClient: examine HttpResponseMessage.IsSuccessMessage or call HttpResponseMessage.EnsureSuccessStatusCode to get an HttpRequestException. EnsureSuccessStatusCode will not deserialize the above message. It's up to you to turn it into an object after determining that IsSuccessMessage is false. Here I've built my own class in a console application that has most of the same properties as HttpError, because HttpError lives in System.Web.Http.dll, which is part of the WebApi.Core package. I also needed a custom exception type so that I could specify the stack trace:

I understand that HttpClient is not specifically for interacting with WebAPI, but I am a little surprised that nothing natively converts WebAPI error responses into exceptions on the client side. ServiceStack built handy client and service components that share an error message format. This allows the client to reconstruct exceptions for you.

WPF


WPF applications have a consistent approach that I like. In all instances the application dies with this message:

Like a console application, there is no choice for the user. I like this because the state of the application is unambiguous.

Handling Exceptions


The general rule to catching exceptions is to catch only ones about which you can do something. For example, catch a timeout exception so that you can retry on behalf of the user. Or ignore an exception when deleting something that isn't there.

There are a few situations where you want to catch all exceptions:

  1. In background threads. As mentioned above, any unhandled exception in a background thread will kill your process, including your ASP.NET worker process.
  2. When you want to translate one application layer's exceptions or .NET exceptions into another layer's exception type.
  3. You want to throw a different exception in order to remove the stack trace.
  4. It's the last stop in your application's stack and you want to log the exception before letting it propagate up or out. For example Application_Error in Global.asax.cs.
  5. You want to handle all exceptions in a generic way instead of letting them reach the runtime engine.

"Safety Net" Pattern for Background Threads



I once saw this described as the safety net pattern, but I can't find the term in general use. You can see where it gets its name, though. Another name might be the Pokeman pattern, as in, you gotta catch 'em all.

Translating Exceptions



There are times you want to put some context around an exception for the next layer up so that they know which operation failed and whether there's something to be done about it. Include the current exception in the new one so that it gets put into the new exception's InnerException property. That way when it finally gets logged by something near the top of the call stack all of the error information will be present.

A similar approach is to purposely not include the current exception in the new exception. You want to do this when you want to be sure that potentially sensitive details don't escape a layer. In this case, you want to consider logging the inner exception before it is lost to upper layer logging.

Centralized Logging and Handling




Some systems, like ASP.NET WebForms/MVC and WebAPI provide a way to catch all unhanded errors, at which point you can log and transform the output. You can also perform extra steps like emailing support. This can remove an awful lot of try/catch and error logging code from individual methods.

Custom Exceptions


Before creating a custom exception or a set of them you need to think about what you want to get out of them. Generally, a custom exception communicates that you've reached a very particular condition that you want to identify from other conditions. That way you can log it and trace it back to a single line of code and potentially let users know what they need to do.

For example, business logic can be complex. It's usually a good idea to have a custom exception that represents a business layer failure, like not providing a needed bit of data. It's not enough, though, to throw this single exception type for every rule failure. You could hardcode the message to show e.g. "No IP address specified", "Invalid IP address specified", but then your app is limited to one language of user. (If you've ever used FxCop or Visual Studio's Code Analysis then you are probably familiar with the "move string to resource file" warning :)

What's needed is one of the following:

  1. A collection of specific custom exceptions all inheriting from a layer-specific parent exception class. The parent class is for the convenience of the next layer up so that it can catch all layer-specific exceptions and handle them differently from other libraries' errors or .NET's.
  2. A single layer-specific parent exception and a collection of error codes/enum values, each representing a particular condition.
An app can then map the collection of exceptions or the error codes/enum values to matching culture-specific strings. .NET provides Resource classes for this scenario.

If you use the error code/enum approach, put the value in the Data dictionary property that is part of the .NET Exception class. This is effectively a dictionary of <Object, Object> into which you can stuff whatever you like in order to send values up the call stack. Don't add properties to your custom exception. You may find yourself having to hand your custom exception to some generic handler that won't know about your properties. It will also save having to perform a slightly expensive cast to your custom type to get the property. Generic handlers will only need to query the Data property for the error code. Keep the key in a public static property.


The alternative is an exception for each error instead of an enum value. Each exception should look up its own error message from a culture-specific Resource class. This approach is more in line with how .NET does things. Some drawbacks are the extra code and that the exceptions will only be understood by other .NET or SOAP-based systems. There is no standard way to send exceptions over, say, JSON.

This way you can send a language-specific message to the user and log in another language.

Anti-patterns and Common Mistakes


Catch-Log-Throw


Doing this all the way up the call stack will fill your logs with the same error again and again, each time adding another call to the stack. This makes logs much harder to read. Did the same error really happen just once? How do you accurately count the number of errors?

Do centralize your logging and stick to the strategy. In the above case you would remove the try and the catch block. Just let the exceptions propagate up the stack.

Throw ex


To propagate a caught exception up the stack as-is, just "throw". When you "throw ex", you create a new exception with the same type as the caught one, but the call stack in the exception starts from where you threw it. The stack trace from the one that you caught is no longer available to upper layers. I don't know of a good reason to "throw ex". I've only ever seen it lead to poor debugging sessions and confusing logs.

Complex Exception Families


Don't group your custom exceptions under other custom exceptions. For instance, if you have a SaveCustomerException and a LoadCustomerException, don't make them inherit from CustomerOperationException that inherits from a base CustomException class. It's needlessly complicated. No code needs to catch this vs. the specific exception or the base custom one.

The worst approach I've seen is a combination of custom exceptions that each have their own embedded enum of reasons. Translating these into a single custom exception and single enum value ends up looking like this:

Now every time there is a new exception reason in one of those enums this method needs another case statement. If there is a new class of exception to catch then we need a  A total waste of time.

Not Using Exception.Data


I've never seen .NET use the Data property, but it is the best place to put custom information, rather than adding properties to your custom exceptions. If you feel you must use custom properties, use Data as a backing store so that it is available without casting to your custom type.

Friday, November 21, 2014

Code is like Wet Sand Built on Wet Sand

The softness of software means that everything we build is sitting on a liquefaction zone. Everything works until someone decides to change the underlying structure. A NodeJS package changes and breaks your code. Entity Framework 6 removes a feature that you need and now your have to refactor your data layer. Chrome adopts the latest CSS revision and text now doesn't appear on your page.

We need updates to software to fix bugs and make development tasks easier. If we didn't do that we'd still be developing with assembler and running DOS. We also need to retire old things because the combinations of things to support grow exponentially over time. Like that estimate before the invention of the transistor that we'd one day need every grown woman in America to be a phone operator, we'd need every high school grad to be a software tester to test all the combinations.

The most common approach to keeping software flexible is to keep areas of functionality with an app very specific and to use abstractions so that no one part knows how another part works. In object oriented programming these are known as the SOLID principles.

Now, if you and your team have the time, skill and discipline to obey these principles, your codebase can survive changes for many years without it getting much harder to modify. But companies need to make deadlines to make money, not everyone knows these ideas and sometimes people just want to be done with a task. Damn real world :)

One way companies mitigate the amount of code they have to maintain is to drop support for things in their products. No more Windows XP and Internet Explorer 6 patches. jQuery 2.x and AngularJS 1.3 need IE9+. Otherwise the testing becomes too onerous, and makes paid products too expensive relative to their value. For free products, this is just too much to ask

I think there is another approach taking shape: planned obsolescence at the app level, not just at the feature/platform level.

The SOLID principles help keep it easy to replace tiny units of code within an app. Lately, though, it feels like people want to expand that approach to entire apps. I've heard people on coding podcasts ask JavaScript developers how they plan to keep a web app running for over 5 years when JS libraries change so fast and the answer is that they don't. They expect the app to be obsolete and to be replaced by something else.

Every app that lives in a cloud system like Azure or Amazon Web Services costs someone some money for every moment it's running or every byte it delivers. Once an app's popularity wanes and the revenue stream drops below the cost of keeping it running it will be decommissioned. Online games are already doing this.

You can see this happening with mobile platforms, too. It's easy to do with hardware that can't be upgraded and costs as much to repair as to replace with the latest version. I have a Windows Phone 7 phone and the flow of new apps for it has almost stopped. Your iPhone 4S can run iOS 8, but it probably shouldn't for performance reasons. As apps start requiring iOS 8+ your 4S and down will be left behind.

As someone who works with some 10+ year old code at work, I support the idea of planned obsolescence at the app level. What would that look like for executables on PCs and servers?

  • A set of small apps with very limited responsibilities. No monolithic services with 20 threads doing 20 different things.
  • Lots of executables. Maybe one that launches the rest, but again, no 1 giant process with a ton of threads.
  • Self-updating. Don't rely on users to keep things up to date. Provide control for the risk-averse enterprise, but limit component use to a year or 2.
Shortly after I started this post Martin Fowler's wrote about "sacrificial architecture", which seems to be a way to deal with retiring large scale systems. Great minds think alike? :)


Saturday, October 11, 2014

How to Fund Childcare in Canada

My idea is this: don't limit the childcare deduction to just people's own kids

In Canada, childcare expenses are tax deductible in the same way that retirement fund (RRSP) contributions are. They come off the total of your income, so you get back whatever percentage your highest tax rate is. The more you make the more the deduction is worth. (Whoever has the lower income in a couple has to claim it.)

I understand the reason an RRSP contribution comes off the top of your income. You're loosing access to money now in hopes that you will be in a lower tax bracket later in life. But I don't quite understand why childcare is treated the same way. Tax law history is not easy to find online. It's probably something to do with the idea that you spend $50 a day to go to work and make $150. You don't get to spend the $50 on yourself or on goods or experiences for your kids. (A good daycare can be a good developmental experience, so this reason doesn't make complete sense.)

Whatever the reason I suggest we let people pay to send other people's kids to day care and let them deduct the cost in the same way. It would be a like a charitable contribution, but worth more than 15% to those in higher tax brackets.

There are a couple of different ways you could run this. One would be to have to pay for a particular child. A group of family and friends would all pay a child's parent(s) some amount towards day care. There would have to be receipts from the child's parent.

Another way would be to have non-profit companies to which anyone could contribute and parents would apply for help. You'd lose some of the contributions to the overhead of running the company, but the benefits would be more widespread.

My next step is to write to all of the federal leaders and maybe even the provincial ones. I'm not a fan of the federal Conservatives, but it wouldn't be the first time that they extended a tax deduction. This might be right up their alley.

Monday, May 26, 2014

Don't Be Afraid of SingleOrDefault

The following is based on an issue I've seen many times in a code base at work, and only recently caused the problem described below.

Consider the following code:


Assume that for good reasons we need to find JobSources by their Source and JobId values. The calling code doesn't have the Id. The "database" doesn't enforce uniqueness of these 2 values as a key, we just assume that every other system that feeds up data behaves this way, too. Well, hope is a better word, as we'll see.

The first time UpdateOrAdd is called, it will find the one and only matching JobSource and update it. Then someone adds a second JobSource for job 2. We again try to update the JobSource with JobId 2 and SourceType File. Success! No exceptions.

Except, we're using Any to see if there are 1 or more items and then updating the first one. The code tolerates the condition of there being more than one item that matches our "key". We have potentially updated the wrong data. Corruption!

Now let's change UpdateOrAdd to use SingleOrDefault:



Not only is the expected shape of the data clear, but it's shorter too. SingleOrDefault returns the 1 item that matches or the default value for the type. For any class type, the default is null. If more than 1 item matches, it throws an exception.

Now on the second call to UpdateOrAdd, we get the following exception:

System.InvalidOperationException: Sequence contains more than one element.

Oh no! A noisy exception, instead of silent data corruption!

Why would someone write code the earlier Any/First stuff? Because some coders are scared of triggering exceptions. More scared of that than corrupting data. Any time I see this pattern in code at work I change it to use SingleOrDefault, or just Single if the item is definitely expected to be present. I've had to convince people that it's better to report a problem than update the wrong item.

Yes, there is a chance that the exception won't happen during testing because the data in the lab might be very clean. Perhaps no one has yet created the conditions there that break your assumption about the shape of the data. It just might be found by a real customer. That customer, though, will report the issue and, more importantly, not lose data.

Monday, May 12, 2014

A Very Practical Use of C# Structs

A programming interview question folks will tell you to be prepared for is "when should you use structs" and the general response is "when you want pass by value behaviour". That is, when you want data to be passed as a copy rather than as a reference.

Ok, but when would you ever want that behaviour? An issue at work recently provided an example: when you can't trust that the thing your object was passed won't be changed. Or that the object you passed in turns out to be the same one passed out later. Here's an example:



There is a class, PersonUsingClasses, that takes items from two data sources and holds on to the references, rather than making copies of all of the properties of each. It then uses those references to construct a new property, DisplayName. I've written such code myself, unaware of the dangers. This class also has a way to convert it back to one of the data source types, ToServicePerson.

A couple of things to notice:
  1. The PersonClassFromService reference sent into the constructor is the same one passed out in ToServicePerson
  2. Someone forgot to remove his debugging code in the constructor.
This means that any changes made to the Service person object inside or outside of the PersonUsingClasses object will appear everywhere at once. Frank changed his salutation in Main to Dr. from outside the class, but the class reflected this change. Also, some code in Main tries to detect if the Age property changed by comparing the input and output objects, and what do you know, there was no change.

One option to fix this is to not hold on to the references passed into the constructor and make copies of every property that matters to PersonClassUsingClasses. That might be a good option, but we need to support recreating the PersonClassFromService object, which could have properties that don't matter. Or, there could be dozens and dozens of properties to track. (I worked at a bank - trust me when I say this happens.)

A nearly equivalent approach is to use return structs from the DB and service:


Now the system copies every property in every input parameter for us because they are structs. It copies every property again when we call ToServicePerson. This means that changing the input parameter does not get reflected in PersonUsingStructs and we can detect the accidental change in the constructor. This approach uses more memory because of all of this copying, but it's not much more than if we'd made copies of every property ourselves in PersonUsingClasses. We've protected the system from accidental changes.

Wednesday, May 15, 2013

Azure Mobile Services HTML Client - This Changes Everything

I started building a web app for tracking my budget. It stores data in a SQL database, so I thought I'd try running it in Microsoft's Azure cloud system. Azure has a web hosting system that is very easy to use and a SQL database system (among many, many other things). The architecture looked like this:

Website and database
Website and database

My first build of the site didn't use authorization and the data in the database couldn't be associated with a particular user. Before .NET 4.0 the out-of-the-box web authentication system was web forms. This meant storing user IDs and passwords in a database and forcing users to create yet another set of credentials on your site.

However, the ASP.NET MVC 4 template leveraged the use of claims-based authentication in .NET 4 and gave you an easy way to let users log in with third party IDs. The included ones are Google, Facebook, Twitter and Microsoft IDs (aka Live IDs). This sounded good to me, so I started down the path of moving my app to the new MVC 4 template. I could log in with my Google ID and received a unique identifier with which to associate my data.  The architecture was now:

Website, database and authorization
Website, database and authorization systems


Shortly after that, I learned about Azure Mobile Services. This is a very handy system that can handle authentication with the same systems as the MVC 4 template, but for smart phones and Windows 8 Store apps. It also integrates with an Azure SQL database. My intention was to use it to create Windows 8 and Windows Phone 7 and 8 clients for my app.

I found out that, while it is technically possible to use an existing database with Azure Mobile Services, there are some hoops through which you must jump to make them talk. I wasn't too far along with my development so I thought it easier to allow the Mobile Service creation wizard to create the database. Soon, I had a little dummy Windows 8 app that could authenticate with my Google ID, and again was receiving a unique ID.

Only, it wasn't the same as the ID I received in the web app. This was a problem, because it meant I couldn't look up data for the same person using their Google ID in both apps. My architecture now looked like this:

Website, database, mobile services and 2 authorization systems
Website, database, mobile services and 2 authorization systems
The cause of the ID mismatch was that the MVC4 template uses Google's OpenID authentication system, while Mobile Services uses Google's OAuth2 system. I had no reliable way of associating one with the other. A little searching around found other people encountering the same problem, and eventually a NuGet package that lets you use Google's OAuth2 system in an MVC 4 web app.

The NuGet package would let me find people's data no matter which app they used. Hardly ideal, though, because it meant extra code just to do the same thing. I suspected there would be other differences between the MVC 4 template's authentication providers and Mobile Services' providers.

My ideal architecture is:



The idea is that the Mobile Service would handle all authorization, and then access a REST endpoint in the website, rather than going directly to the database. This means that the web app would somehow authenticate against and get data from the Mobile Service, just like the other apps.

Besides the centralization of the authorization mechanism, it would also put all the business logic on the server. The Windows 8 and phone apps would be strictly for displaying data. That way any bug fixes to business logic would be web-based, meaning immediate and global. If the logic lived in the Windows and phone apps then I'd have to update them individually, and wait for them to be approved and delivered to people.

It seemed like a pipe dream, because I couldn't find any easily understandable information about how to authenticate against a Mobile Service. Until a few days ago, when I found out that the Mobile Services group published an example HTML client, along with a JavaScript library that can authenticate and get data.

This changes everything.

This is the final piece of the puzzle that will let me create a web app that gets data through Azure Mobile Services.

Actually, there is one change to the architecture needed to keep the REST interface accessible to only the Mobile Service:



That extra User Auth box is an Azure Access Control Service service ID that the Mobile Service will use to access the web service's REST service.