SQL Server · Update

Turn update errors into messages

An edit screen turns update errors into messages, in two scenarios: what the database refuses (a taken account number, a negative employee count, a website too long), and what ARX refuses before the database (a NULL to find the row by, nothing to write). Each failed update leaves the account as it was.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names).

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var taken = new ArxEntity("account");
taken["name"] = "Errors: taken number";
taken["account_number"] = "ACC-U901";
await service.CreateAsync(taken);
var account = new ArxEntity("account");
account["name"] = "Errors: the account being edited";
account["account_number"] = "ACC-U902";
account["employee_count"] = 20;
var id = await service.CreateAsync(account);

1 What the database refuses

The database refuses: each error has a code to choose the message by.

Already in scope: service (ArxMsSqlDbService), id (ArxRecordId)

C#
var attempts = new (string Field, object Value)[]
{
    ("account_number", "ACC-U901"),
    ("employee_count", -3),
    ("website", "https://example.com/" + new string('x', 250))
};

foreach (var (field, value) in attempts)
{
    var change = new ArxEntity("account");
    change.RecordId = id;
    change[field] = value;

    try
    {
        await service.UpdateAsync(change);
    }
    catch (ArxDatabaseException error)
    {
        Console.WriteLine($"{field}: {error.Code}, the user sees \"{ForTheUser(error)}\"");
    }
}
Used above

Defined once in this sample.

private static string ForTheUser(ArxException error) => error.Code switch
{
    ArxErrorCode.RecordNotFound => "This account no longer exists.",
    ArxErrorCode.UniqueViolation => "That account number is already in use.",
    ArxErrorCode.CheckViolation => "One of the values isn't allowed.",
    ArxErrorCode.ValueTooLong => "One of the values is too long.",
    _ => "The change couldn't be saved."
};

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT account_number, employee_count, website
FROM account
WHERE name = 'Errors: the account being edited';

Expect: 1 row, ACC-U902, employee_count 20, website NULL: none of the three changes was stored.

2 What ARX refuses before the database

ARX refuses before the database: a NULL to find the row by, or an update with nothing to write.

Already in scope: service (ArxMsSqlDbService), id (ArxRecordId)

C#
var byNullNumber = new ArxEntity("account");
byNullNumber["account_number"] = null;
byNullNumber["employee_count"] = 1;

var nothingToWrite = new ArxEntity("account");
nothingToWrite.RecordId = id;

foreach (var (change, options) in new[] { (byNullNumber, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") }), (nothingToWrite, (ArxUpdateOptions?)null) })
{
    try
    {
        await service.UpdateAsync(change, options);
    }
    catch (ArxValidationException error)
    {
        Console.WriteLine(error.Message);
    }
}

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT count(*)
FROM account
WHERE account_number IS NULL AND employee_count = 1;

Expect: 0.

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.SQL --version 1.0.0-rc.1
  4. Database: a SQL Server 2022 (tested with 16.0.4225.2) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_SQLSERVER to its connection string. Nothing is hard-coded.
  6. Source code: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleCatalog.cs), then replace Program.cs and add the other file below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment.

using ArxSamples.MSSQL;
using ArxSamples.MSSQL.Operations.Update.RealCases;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_SQLSERVER")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_SQLSERVER environment variable to your SQL Server connection string.");

await new RealCase2_HandleErrors().RunAsync(new SampleContext(connectionString));
RealCase2_HandleErrors.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.Services;
using static ArxSamples.MSSQL.SampleOutput;

namespace ArxSamples.MSSQL.Operations.Update.RealCases;

/// <summary>
/// An edit screen turns update errors into messages, in two scenarios: what the database refuses (a taken account
/// number, a negative employee count, a website too long), and what ARX refuses before the database (a NULL to find
/// the row by, nothing to write). Each failed update leaves the account as it was.
/// </summary>
public sealed class RealCase2_HandleErrors : ISample
{
    public string Name => "update-real-2-handle-errors";

    public string Title => "Turn update errors into messages";

    public async Task RunAsync(SampleContext dbContext)
    {
        var taken = new ArxEntity("account");
        taken["name"] = "Errors: taken number";
        taken["account_number"] = "ACC-U901";
        await dbContext.Service.CreateAsync(taken);

        var account = new ArxEntity("account");
        account["name"] = "Errors: the account being edited";
        account["account_number"] = "ACC-U902";
        account["employee_count"] = 20;
        var id = await dbContext.Service.CreateAsync(account);

        await Scenario1_WhatTheDatabaseRefusesAsync(dbContext, id);

        await Scenario2_WhatArxRefusesFirstAsync(dbContext, id);
    }

    private static string ForTheUser(ArxException error) => error.Code switch
    {
        ArxErrorCode.RecordNotFound => "This account no longer exists.",
        ArxErrorCode.UniqueViolation => "That account number is already in use.",
        ArxErrorCode.CheckViolation => "One of the values isn't allowed.",
        ArxErrorCode.ValueTooLong => "One of the values is too long.",
        _ => "The change couldn't be saved."
    };

    /// <summary>1. The database refuses: each error has a code to choose the message by.</summary>
    private static async Task Scenario1_WhatTheDatabaseRefusesAsync(SampleContext dbContext, ArxRecordId id)
    {
        Step("1. What the database refuses");

        var attempts = new (string Field, object Value)[]
        {
            ("account_number", "ACC-U901"),
            ("employee_count", -3),
            ("website", "https://example.com/" + new string('x', 250))
        };

        foreach (var (field, value) in attempts)
        {
            var change = new ArxEntity("account");
            change.RecordId = id;
            change[field] = value;

            try
            {
                await dbContext.Service.UpdateAsync(change);
            }
            catch (ArxDatabaseException error)
            {
                Show($"{field}: {error.Code}, the user sees \"{ForTheUser(error)}\"");
            }
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT account_number, employee_count, website
         * FROM account
         * WHERE name = 'Errors: the account being edited';
         * -- Expect: 1 row, ACC-U902, employee_count 20, website NULL: none of the three changes was stored.
         * ===========================================================
         */
    }

    /// <summary>2. ARX refuses before the database: a NULL to find the row by, or an update with nothing to write.</summary>
    private static async Task Scenario2_WhatArxRefusesFirstAsync(SampleContext dbContext, ArxRecordId id)
    {
        Step("2. What ARX refuses before the database");

        var byNullNumber = new ArxEntity("account");
        byNullNumber["account_number"] = null;
        byNullNumber["employee_count"] = 1;

        var nothingToWrite = new ArxEntity("account");
        nothingToWrite.RecordId = id;

        foreach (var (change, options) in new[] { (byNullNumber, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") }), (nothingToWrite, (ArxUpdateOptions?)null) })
        {
            try
            {
                await dbContext.Service.UpdateAsync(change, options);
            }
            catch (ArxValidationException error)
            {
                ShowError(error);
            }
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM account
         * WHERE account_number IS NULL AND employee_count = 1;
         * -- Expect: 0.
         * ===========================================================
         */
    }
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. What the database refuses
      account_number: UniqueViolation, the user sees "That account number is already in use."
      employee_count: CheckViolation, the user sees "One of the values isn't allowed."
      website: ValueTooLong, the user sees "One of the values is too long."
  > 2. What ARX refuses before the database
      caught ArxValidationException: ARX1001 InvalidArgument: Match column 'account_number' of 'account' is null. In SQL '= NULL' never matches, so the call would find nothing.
      caught ArxValidationException: ARX1001 InvalidArgument: The update of 'account' has nothing to write: every attribute is a match column (id (column id)) or ArxIgnore.