SQL Server · Create
Write to two databases, each with its own service
Two databases in one application, in three scenarios: one service per database, an order placed in the CRM (the source of truth) and recorded in a reporting database (an event log), and a retry of the copy. One ArxMsSqlDbService per database, each with its own connection string and schema catalog, registered as keyed services and injected by key.
Set up for this page
Besides the sample itself, it uses SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleCatalog.cs (the tables' ids, keys, lookups and display names); SampleContext.Direct.cs (dbContext.Direct); MsSqlDirectHelper.cs (the checks behind dbContext.Direct), in the files below.
dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.
Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:
await dbContext.Direct.EnsureDatabaseExistsAsync(REPORTING_DATABASE);
var reportingDirect = dbContext.Direct.ForDatabase(REPORTING_DATABASE);
await reportingDirect.ExecuteAsync(
"DROP TABLE IF EXISTS order_event; "
+ "CREATE TABLE order_event (id bigint IDENTITY(1, 1) PRIMARY KEY, order_number varchar(20) NOT NULL UNIQUE, account_name nvarchar(200) NOT NULL, "
+ "total decimal(14, 2) NOT NULL, recorded_at datetimeoffset NOT NULL DEFAULT SYSDATETIMEOFFSET())");
using var scope = provider.CreateScope();
var desk = scope.ServiceProvider.GetRequiredService<OrderDesk>();1 Register one service per database, by key (in ASP.NET Core: builder.Services)
Register one service per database, by key (in ASP.NET Core: builder.Services).
Already in scope: connectionString (string)
var services = new ServiceCollection();
// Each database has its own schema catalog: only the tables that database has.
services.AddKeyedSingleton("crm", (_, _) => new ArxMsSqlDbService(connectionString, SampleCatalog.Build()));
services.AddScoped<OrderDesk>();
return services.BuildServiceProvider();Defined once in this sample.
private sealed class OrderDesk
{
private readonly ArxMsSqlDbService _crm;
private readonly ArxMsSqlDbService _reporting;
public OrderDesk([FromKeyedServices("crm")] ArxMsSqlDbService crm, [FromKeyedServices("reporting")] ArxMsSqlDbService reporting)
{
_crm = crm;
_reporting = reporting;
}
/// <summary>The source of truth first, in one CRM transaction; then the copy in reporting.</summary>
public async Task<ArxRecordId> PlaceOrderAsync(string accountName, string orderNumber, decimal total)
{
ArxRecordId orderId = null!;
await _crm.RunBatchAsync(async batch =>
{
var account = new ArxEntity("account");
account["name"] = accountName;
await batch.CreateAsync(account);
var order = new ArxEntity("sales_order");
order["order_number"] = orderNumber;
order["account_id"] = new ArxEntityReference("account", account.RecordId);
order["ordered_on"] = DateTime.UtcNow;
order["total"] = total;
orderId = await batch.CreateAsync(order);
});
// Committed in the CRM. If this next write fails, the order still stands: retry the event later.
await RecordEventAsync(accountName, orderNumber, total);
return orderId;
}
/// <summary>Records the order in reporting. Returns false when it was already recorded (safe to call again).</summary>
public async Task<bool> RecordEventAsync(string accountName, string orderNumber, decimal total)
{
var orderEvent = new ArxEntity("order_event");
orderEvent["order_number"] = orderNumber;
orderEvent["account_name"] = accountName;
orderEvent["total"] = total;
try
{
await _reporting.CreateAsync(orderEvent);
return true;
}
catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.UniqueViolation)
{
return false;
}
}
}Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT name
FROM sys.databases
WHERE name IN ('arx_samples', 'arx_sdk_reporting');Expect: 2 rows: the CRM database and the reporting database.
2 Place an order in the CRM, then record it in reporting
The source of truth first, in one CRM transaction; then the copy in reporting.
Already in scope: desk (OrderDesk)
var orderId = await desk.PlaceOrderAsync("Fourth Coffee", "SO-6001", 149.70m);Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT o.order_number, o.total, a.name AS account
FROM sales_order o
JOIN account a ON a.id = o.account_id
WHERE o.order_number = 'SO-6001';
-- In the arx_sdk_reporting database:
SELECT order_number, account_name, total, recorded_at
FROM arx_sdk_reporting.dbo.order_event
WHERE order_number = 'SO-6001';Expect: the order in the CRM (Fourth Coffee, 149.70), and its event in reporting.
3 Recording the same event again (a retry after a failure) is harmless
Recording the same event again (a retry after a failure) is harmless: the order number is unique there.
Already in scope: desk (OrderDesk)
var recordedAgain = await desk.RecordEventAsync("Fourth Coffee", "SO-6001", 149.70m);Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
-- In the arx_sdk_reporting database:
SELECT count(*)
FROM arx_sdk_reporting.dbo.order_event
WHERE order_number = 'SO-6001';Expect: 1: the retry didn't record a second event.
Good to know
Each database has its own transactions: ARX can't make a write to two databases atomic (there's no distributed transaction). Write the source of truth first and commit it, then write the copy. Make the copy safe to repeat (here the event is unique per order number), so a failed copy can simply be retried.
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
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.SQL --version 1.0.0-rc.1 dotnet add package Microsoft.Extensions.DependencyInjection --version 8.0.1 - Database: a SQL Server 2022 (tested with 16.0.4225.2) database with the sample schema.
- Configuration: set
ARX_SAMPLES_SQLSERVERto its connection string. Nothing is hard-coded. - Source code: replace
Program.csand add the 6 other files below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
Runs the sample. Generated for this page; it reads the connection string from the environment.
using ArxSamples.MSSQL;
using ArxSamples.MSSQL.Operations.Create.AdvancedCases;
// 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 Advanced4_TwoDatabases().RunAsync(new SampleContext(connectionString));
The sample, as it is in the repository.
using ARX.SDK;
using ARX.SDK.SQL.Services;
using ARX.SDK.Services;
using Microsoft.Extensions.DependencyInjection;
using static ArxSamples.MSSQL.SampleOutput;
namespace ArxSamples.MSSQL.Operations.Create.AdvancedCases;
/// <summary>
/// Two databases in one application, in three scenarios: one service per database, an order placed in the CRM (the
/// source of truth) and recorded in a reporting database (an event log), and a retry of the copy. One <see cref="ArxMsSqlDbService"/> per database, each with its own connection string and schema catalog,
/// registered as keyed services and injected by key.
/// </summary>
/// <remarks>
/// Each database has its own transactions: ARX can't make a write to two databases atomic (there's no distributed
/// transaction). Write the source of truth first and commit it, then write the copy. Make the copy safe to repeat (here
/// the event is unique per order number), so a failed copy can simply be retried.
/// </remarks>
public sealed class Advanced4_TwoDatabases : ISample
{
private const string REPORTING_DATABASE = "arx_sdk_reporting";
public string Name => "create-advanced-4-two-databases";
public string Title => "Write to two databases, each with its own service";
public async Task RunAsync(SampleContext dbContext)
{
// Setup only: create the reporting database and its table (plain SQL, not ARX).
await dbContext.Direct.EnsureDatabaseExistsAsync(REPORTING_DATABASE);
var reportingDirect = dbContext.Direct.ForDatabase(REPORTING_DATABASE);
await reportingDirect.ExecuteAsync(
"DROP TABLE IF EXISTS order_event; "
+ "CREATE TABLE order_event (id bigint IDENTITY(1, 1) PRIMARY KEY, order_number varchar(20) NOT NULL UNIQUE, account_name nvarchar(200) NOT NULL, "
+ "total decimal(14, 2) NOT NULL, recorded_at datetimeoffset NOT NULL DEFAULT SYSDATETIMEOFFSET())");
await using var provider = Scenario1_RegisterOneServicePerDatabase(dbContext);
using var scope = provider.CreateScope();
var desk = scope.ServiceProvider.GetRequiredService<OrderDesk>();
await Scenario2_PlaceAnOrderThenRecordItAsync(desk, reportingDirect);
await Scenario3_ARetryOfTheCopyIsHarmlessAsync(desk, reportingDirect);
}
/// <summary>1. Register one service per database, by key (in ASP.NET Core: builder.Services).</summary>
private static ServiceProvider Scenario1_RegisterOneServicePerDatabase(SampleContext dbContext)
{
Step("1. Register one service per database, by key (in ASP.NET Core: builder.Services)");
var reportingConnectionString = dbContext.Direct.ConnectionStringFor(REPORTING_DATABASE);
var services = new ServiceCollection();
// Each database has its own schema catalog: only the tables that database has.
services.AddKeyedSingleton("crm", (_, _) => new ArxMsSqlDbService(dbContext.ConnectionString, SampleCatalog.Build()));
services.AddKeyedSingleton("reporting", (_, _) => new ArxMsSqlDbService(reportingConnectionString, ArxSchemaCatalog.Create()
.Table("order_event", ArxIdColumn.Generated<long>("id"))
.Build()));
services.AddScoped<OrderDesk>();
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT name
* FROM sys.databases
* WHERE name IN ('arx_samples', 'arx_sdk_reporting');
* -- Expect: 2 rows: the CRM database and the reporting database.
* ===========================================================
*/
return services.BuildServiceProvider();
}
/// <summary>2. The source of truth first, in one CRM transaction; then the copy in reporting.</summary>
private static async Task Scenario2_PlaceAnOrderThenRecordItAsync(OrderDesk desk, MsSqlDirectHelper reportingDirect)
{
Step("2. Place an order in the CRM, then record it in reporting");
var orderId = await desk.PlaceOrderAsync("Fourth Coffee", "SO-6001", 149.70m);
Show($"CRM: order {orderId} committed; reporting: {await reportingDirect.CountAsync("order_event", "order_number = @p0", "SO-6001")} event");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT o.order_number, o.total, a.name AS account
* FROM sales_order o
* JOIN account a ON a.id = o.account_id
* WHERE o.order_number = 'SO-6001';
*
* -- In the arx_sdk_reporting database:
* SELECT order_number, account_name, total, recorded_at
* FROM arx_sdk_reporting.dbo.order_event
* WHERE order_number = 'SO-6001';
* -- Expect: the order in the CRM (Fourth Coffee, 149.70), and its event in reporting.
* ===========================================================
*/
}
/// <summary>3. Recording the same event again (a retry after a failure) is harmless: the order number is unique there.</summary>
private static async Task Scenario3_ARetryOfTheCopyIsHarmlessAsync(OrderDesk desk, MsSqlDirectHelper reportingDirect)
{
Step("3. Recording the same event again (a retry after a failure) is harmless");
var recordedAgain = await desk.RecordEventAsync("Fourth Coffee", "SO-6001", 149.70m);
Show($"second attempt recorded a new row: {recordedAgain}; events for SO-6001: {await reportingDirect.CountAsync("order_event", "order_number = @p0", "SO-6001")}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* -- In the arx_sdk_reporting database:
* SELECT count(*)
* FROM arx_sdk_reporting.dbo.order_event
* WHERE order_number = 'SO-6001';
* -- Expect: 1: the retry didn't record a second event.
* ===========================================================
*/
}
/// <summary>An application service that writes to both databases. Each service comes in by its key.</summary>
private sealed class OrderDesk
{
private readonly ArxMsSqlDbService _crm;
private readonly ArxMsSqlDbService _reporting;
public OrderDesk([FromKeyedServices("crm")] ArxMsSqlDbService crm, [FromKeyedServices("reporting")] ArxMsSqlDbService reporting)
{
_crm = crm;
_reporting = reporting;
}
/// <summary>The source of truth first, in one CRM transaction; then the copy in reporting.</summary>
public async Task<ArxRecordId> PlaceOrderAsync(string accountName, string orderNumber, decimal total)
{
ArxRecordId orderId = null!;
await _crm.RunBatchAsync(async batch =>
{
var account = new ArxEntity("account");
account["name"] = accountName;
await batch.CreateAsync(account);
var order = new ArxEntity("sales_order");
order["order_number"] = orderNumber;
order["account_id"] = new ArxEntityReference("account", account.RecordId);
order["ordered_on"] = DateTime.UtcNow;
order["total"] = total;
orderId = await batch.CreateAsync(order);
});
// Committed in the CRM. If this next write fails, the order still stands: retry the event later.
await RecordEventAsync(accountName, orderNumber, total);
return orderId;
}
/// <summary>Records the order in reporting. Returns false when it was already recorded (safe to call again).</summary>
public async Task<bool> RecordEventAsync(string accountName, string orderNumber, decimal total)
{
var orderEvent = new ArxEntity("order_event");
orderEvent["order_number"] = orderNumber;
orderEvent["account_name"] = accountName;
orderEvent["total"] = total;
try
{
await _reporting.CreateAsync(orderEvent);
return true;
}
catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.UniqueViolation)
{
return false;
}
}
}
}
What every sample is given: the connection string (and the ISample interface the samples implement).
namespace ArxSamples.MSSQL;
/// <summary>One documentation sample: a scenario a real application has, shown end to end.</summary>
public interface ISample
{
/// <summary>The name to run it alone: <c>dotnet run -- <name></c>.</summary>
string Name { get; }
/// <summary>One line on what it shows.</summary>
string Title { get; }
Task RunAsync(SampleContext dbContext);
}
/// <summary>
/// What a sample is given. Every sample gets the connection string; the application's service and catalog
/// (SampleContext.Application.cs) and the plain SqlClient read-back helper (SampleContext.Direct.cs) live in their own
/// files, so a sample needs only the files it uses.
/// </summary>
public sealed partial class SampleContext
{
public SampleContext(string connectionString)
{
ConnectionString = connectionString;
}
public string ConnectionString { get; }
}
How the samples print: Step for each scenario, Show for what it did, ShowError for an error caught on purpose.
using ARX.SDK;
namespace ArxSamples.MSSQL;
/// <summary>How the samples print: a numbered step for each scenario, then what it did.</summary>
public static class SampleOutput
{
/// <summary>The start of a scenario: <c>Step("1. By the id Create returned")</c>.</summary>
public static void Step(string text) => Console.WriteLine($" > {text}");
/// <summary>What the scenario did.</summary>
public static void Show(string text) => Console.WriteLine($" {text}");
/// <summary>An ARX error the scenario caught on purpose.</summary>
public static void ShowError(ArxException exception)
=> Console.WriteLine($" caught {exception.GetType().Name}: {exception.Message}");
}
The application's schema catalog: every table's id column and keys, and its selection sets.
using ARX.SDK.Services;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ArxSamples.MSSQL;
/// <summary>An account's industry. Stored in account.industry (smallint) as the enum's number.</summary>
public enum Industry : short
{
Retail = 1,
Manufacturing = 2,
Healthcare = 3,
Finance = 4,
Technology = 5
}
/// <summary>
/// The application's schema catalog: every table's id column and keys, and every picklist (selection set),
/// defined once.
/// </summary>
/// <remarks>
/// <para>
/// <b>Ids.</b> Every table the application writes is declared with its one id column: its name, its .NET type, and
/// whether the database generates it (<c>ArxIdColumn.Generated</c>: identity, sequence, default) or the caller supplies
/// it (<c>ArxIdColumn.Supplied</c>: a natural id, a client-generated Guid). A table with no id column, such as a log or a
/// table identified by several columns together, is declared <c>ArxIdColumn.NoIdColumn</c>. ARX never reads ids from
/// the database: the developer knows the schema, and an undeclared table is refused (ARX1016).
/// </para>
/// <para>
/// <b>Keys.</b> Optional business keys: one or more columns whose values identify a record, such as an account number,
/// or a region and a SKU together. Create doesn't use them (the database's unique constraints do the enforcing); Update
/// and Delete will be able to find rows by them. <c>ValidateSchemaAsync</c> checks ids and keys against the database
/// when you ask it to.
/// </para>
/// <para>
/// <b>Selection sets.</b> /// A selection set (picklist, option set) is a column that only accepts a fixed list of codes, each with a display
/// text: an account's status (ACTIVE, ON_HOLD, CLOSED), a contact's preferred channel (E, P, S). The catalog tells ARX,
/// for each set:
/// </para>
/// <list type="bullet">
/// <item><b>Name</b>: what an <see cref="ArxSelectionSetValue"/> refers to, for example <c>new ArxSelectionSetValue("AccountStatus", "ON_HOLD")</c>.</item>
/// <item><b>Kind</b>: what the codes are, matching the column: Integer, String, Character, Boolean, Decimal or Guid.
/// (SQL Server has no enum types: a fixed list of text values is a String set, and a CHECK can guard the column.)</item>
/// <item><b>Multiplicity</b>: Single (one code), or several codes stored as bit flags (Flags), a delimited string
/// (Delimited) or a JSON array (Json). SQL Server has no array columns.</item>
/// <item><b>Options</b>: each code with its display text and order. A retired option (<c>IsActive: false</c>) stays
/// readable in old rows, but can't be written any more.</item>
/// </list>
/// <para>
/// Build the catalog once at startup and give it to the service: <c>new ArxMsSqlDbService(connectionString, SampleCatalog.Build())</c>.
/// ARX checks every <see cref="ArxSelectionSetValue"/> against it in memory, before any SQL is sent, and stores the code
/// itself in the column: no lookup table, no extra query. A plain value (a string or number that isn't an
/// ArxSelectionSetValue) isn't checked.
/// </para>
/// <para>
/// The catalog is plain code, so the options can come from wherever you keep them: written out here, taken from a .NET
/// enum (<c>AddEnum</c>), loaded from JSON (<see cref="SetsJson"/> and <see cref="FromJson"/> below), or loaded at
/// startup from your own option table and passed to <c>new ArxSelectionSetDefinition(name, kind, options)</c>. ARX
/// never reads option tables or files itself.
/// </para>
/// </remarks>
public static class SampleCatalog
{
/// <summary>
/// Selection sets kept as JSON, as an application might keep them in a file, a settings store or a database column.
/// Here the JSON is in the class itself; in an application, read it from wherever you keep it
/// (<c>File.ReadAllText("selection-sets.json")</c>, configuration, an HTTP call) and pass it to <see cref="FromJson"/>.
/// "multiplicity" and "active" are optional (Single and true).
/// </summary>
public const string SetsJson = """
[
{
"name": "LeadSource",
"kind": "String",
"options": [
{ "value": "WEB", "text": "Website", "order": 0 },
{ "value": "REFERRAL", "text": "Referral", "order": 1 },
{ "value": "EVENT", "text": "Trade show", "order": 2 },
{ "value": "COLD_CALL", "text": "Cold call", "order": 3, "active": false }
]
},
{
"name": "ContactRating",
"kind": "Integer",
"multiplicity": "Single",
"options": [
{ "value": 1, "text": "Poor" },
{ "value": 2, "text": "Fair" },
{ "value": 3, "text": "Good" },
{ "value": 4, "text": "Very good" },
{ "value": 5, "text": "Excellent" }
]
}
]
""";
public static ArxSchemaCatalog Build()
{
var builder = ArxSchemaCatalog.Create()
// ---------- tables: id column and keys ----------
// Generated bigint ids (IDENTITY): the database fills them in. The keys are the unique columns that also
// identify a record.
.Table("account", ArxIdColumn.Generated<long>("id")).Key("account", "account_number")
.Table("contact", ArxIdColumn.Generated<long>("id")).Key("contact", "email")
// Retrieve: a contact's account_id reads back as a reference to its account, named by the account's
// name; a contact is named by its first and last names.
.Lookup("contact", "account_id", "account")
.DisplayName("account", "name")
.DisplayName("contact", new[] { "first_name", "last_name" }, " ")
.Table("product_category", ArxIdColumn.Generated<long>("id")).Key("product_category", "name")
.Table("product", ArxIdColumn.Generated<long>("id")).Key("product", "sku")
.Table("sales_order", ArxIdColumn.Generated<long>("id")).Key("sales_order", "order_number")
.Table("order_line", ArxIdColumn.Generated<long>("id"))
.Table("data_type_showcase", ArxIdColumn.Generated<long>("id"))
// A natural id: the caller gives the ISO country code.
.Table("country", ArxIdColumn.Supplied<string>("code"))
// A generated uuid id (DEFAULT gen_random_uuid()).
.Table("device", ArxIdColumn.Generated<Guid>("id")).Key("device", "serial_number")
// No id column: a price is identified by its region and SKU together, a compound key.
.Table("price_list", ArxIdColumn.NoIdColumn).Key("price_list", "region", "sku")
// No primary key at all: the same action can be logged twice.
.Table("activity_log", ArxIdColumn.NoIdColumn)
// A partitioned table without an id: a visit is a fact, never updated (Retrieve Advanced8).
.Table("web_visit", ArxIdColumn.NoIdColumn)
// ---------- selection sets ----------
// From a .NET enum: the set is named after the enum ("Industry"), the codes are its numbers (Retail = 1, …),
// the display texts are its member names. Column: account.industry smallint.
.AddEnum<Industry>()
// Written out: String codes with display texts, single choice. Column: account.status varchar(10).
.Add("AccountStatus", ArxSelectionSetKind.String, ("ACTIVE", "Active"), ("ON_HOLD", "On hold"), ("CLOSED", "Closed"))
// Multiple choice, stored as delimited text ("ENTERPRISE,PUBLIC"). RESELLER is retired: rows that have it still
// read back, but new writes can't use it. Column: account.segments nvarchar(200).
.Add(new ArxSelectionSetDefinition("CustomerSegment", ArxSelectionSetKind.String, new[]
{
new ArxSelectionSetOption("SMB", "Small business", 0),
new ArxSelectionSetOption("ENTERPRISE", "Enterprise", 1),
new ArxSelectionSetOption("PUBLIC", "Public sector", 2),
new ArxSelectionSetOption("RESELLER", "Reseller", 3, IsActive: false)
}, ArxSelectionSetMultiplicity.Delimited))
// Single-character codes. Column: contact.preferred_channel char(1).
.Add("ContactChannel", ArxSelectionSetKind.Character, ('E', "Email"), ('P', "Phone"), ('S', "Text message"))
// A fixed list of text values the column's CHECK also guards (SQL Server has no enum types).
// Column: data_type_showcase.mood nvarchar(10).
.Add(new ArxSelectionSetDefinition("Mood", ArxSelectionSetKind.String, new[]
{
new ArxSelectionSetOption("happy", "Happy", 0),
new ArxSelectionSetOption("neutral", "Neutral", 1),
new ArxSelectionSetOption("sad", "Sad", 2)
}));
// Loaded from JSON: LeadSource (contact.lead_source text) and ContactRating (contact.rating smallint).
foreach (var set in FromJson(SetsJson))
{
builder.Add(set);
}
return builder.Build();
}
/// <summary>Reads selection set definitions from JSON (the shape of <see cref="SetsJson"/>).</summary>
public static IEnumerable<ArxSelectionSetDefinition> FromJson(string json)
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() } // "String", "Integer", "Array", … as names
};
var sets = JsonSerializer.Deserialize<List<JsonSet>>(json, options)
?? throw new InvalidOperationException("The selection set JSON is empty.");
foreach (var set in sets)
{
yield return new ArxSelectionSetDefinition(
set.Name,
set.Kind,
set.Options.Select(x => new ArxSelectionSetOption(Code(x.Value, set.Kind), x.Text, x.Order, x.Active)),
set.Multiplicity,
set.DatabaseTypeName);
}
}
/// <summary>A JSON value as a code of the set's kind: JSON has no char, Guid or 64-bit integer of its own.</summary>
private static object Code(JsonElement value, ArxSelectionSetKind kind) => kind switch
{
ArxSelectionSetKind.Integer => value.GetInt64(),
ArxSelectionSetKind.Decimal => value.GetDecimal(),
ArxSelectionSetKind.Boolean => value.GetBoolean(),
ArxSelectionSetKind.Guid => value.GetGuid(),
ArxSelectionSetKind.Character => value.GetString()![0],
_ => value.GetString()! // String and DatabaseEnum
};
private sealed record JsonSet(
string Name,
ArxSelectionSetKind Kind,
List<JsonOption> Options,
ArxSelectionSetMultiplicity Multiplicity = ArxSelectionSetMultiplicity.Single,
string? DatabaseTypeName = null);
private sealed record JsonOption(JsonElement Value, string Text, int Order = 0, bool Active = true);
}
The plain Microsoft.Data.SqlClient read-back helper, for the samples that show what SQL Server stored.
namespace ArxSamples.MSSQL;
/// <summary>plain SqlClient outside the SDK, for the samples that show what SQL Server stored.</summary>
public sealed partial class SampleContext
{
private MsSqlDirectHelper? _direct;
/// <summary>plain SqlClient outside the SDK, used only to reset the tables and to show what was stored.</summary>
public MsSqlDirectHelper Direct => _direct ??= new MsSqlDirectHelper(ConnectionString);
}
Plain Microsoft.Data.SqlClient, not part of ARX: reads rows back so a sample can show what SQL Server stored.
using Microsoft.Data.SqlClient;
using System.Text.RegularExpressions;
namespace ArxSamples.MSSQL;
/// <summary>
/// Plain Microsoft.Data.SqlClient, outside ARX.SDK: resets the sample tables, reads rows back so a sample can show what
/// SQL Server actually stored (printing is SampleOutput.cs). It isn't part of the SDK and isn't how an application uses
/// ARX; it only lets the samples verify and show their results.
/// </summary>
public sealed class MsSqlDirectHelper
{
private readonly string _connectionString;
public MsSqlDirectHelper(string connectionString)
{
_connectionString = connectionString;
}
/// <summary>The same helper pointed at another database on the same server.</summary>
public MsSqlDirectHelper ForDatabase(string database) => new MsSqlDirectHelper(ConnectionStringFor(database));
/// <summary>The connection string of <see cref="ForDatabase"/>'s database, for a second ARX service.</summary>
public string ConnectionStringFor(string database)
=> new SqlConnectionStringBuilder(_connectionString) { InitialCatalog = database }.ConnectionString;
/// <summary>Creates <paramref name="database"/> on the server if it doesn't exist yet (connecting to master).</summary>
public async Task EnsureDatabaseExistsAsync(string database)
{
await using var connection = new SqlConnection(ConnectionStringFor("master"));
await connection.OpenAsync();
// CREATE DATABASE takes no parameters; the name is the sample's own constant, quoted.
await using var create = new SqlCommand($"IF DB_ID(@name) IS NULL CREATE DATABASE [{database.Replace("]", "]]")}]; ALTER DATABASE [{database.Replace("]", "]]")}] SET ALLOW_SNAPSHOT_ISOLATION ON", connection);
create.Parameters.AddWithValue("@name", database);
await create.ExecuteNonQueryAsync();
}
/// <summary>Drops and recreates the sample tables (Schema/sample-schema.sql), batch by batch (split at GO lines).</summary>
public async Task ResetSchemaAsync()
{
await EnsureDatabaseExistsAsync(new SqlConnectionStringBuilder(_connectionString).InitialCatalog);
// The read-backs read committed rows without waiting for locks (snapshot isolation, allowed on this database).
await ExecuteAsync("ALTER DATABASE CURRENT SET ALLOW_SNAPSHOT_ISOLATION ON");
var script = await File.ReadAllTextAsync(Path.Combine(AppContext.BaseDirectory, "Schema", "sample-schema.sql"));
foreach (var batch in Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase).Where(x => !string.IsNullOrWhiteSpace(x)))
{
await ExecuteAsync(batch);
}
}
public async Task ExecuteAsync(string sql)
{
await using var connection = await OpenConnectionAsync();
await using var command = new SqlCommand(sql, connection);
await command.ExecuteNonQueryAsync();
}
public async Task<SqlConnection> OpenConnectionAsync()
{
var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
return connection;
}
/// <summary>
/// Counts committed rows, optionally with a WHERE clause using @p0, @p1, … for <paramref name="parameters"/>. It reads
/// under SNAPSHOT isolation, so it shows what is committed without waiting for another transaction's locks (a
/// READ COMMITTED read would wait for them), and sets READ COMMITTED back on the pooled connection afterwards.
/// </summary>
public async Task<long> CountAsync(string table, string where = "1 = 1", params object[] parameters)
{
await using var connection = await OpenConnectionAsync();
await using var command = new SqlCommand(
$"SET TRANSACTION ISOLATION LEVEL SNAPSHOT; SELECT COUNT_BIG(*) FROM {table} WHERE {where}; SET TRANSACTION ISOLATION LEVEL READ COMMITTED;", connection);
for (var i = 0; i < parameters.Length; i++)
{
command.Parameters.AddWithValue("@p" + i, parameters[i] ?? DBNull.Value);
}
return (long)(await command.ExecuteScalarAsync())!;
}
/// <summary>Reads one row by id as column → value (null for SQL NULL).</summary>
public async Task<Dictionary<string, object?>> RowAsync(string table, long id)
{
await using var connection = await OpenConnectionAsync();
await using var command = new SqlCommand($"SELECT * FROM {table} WHERE id = @p0", connection);
command.Parameters.AddWithValue("@p0", id);
await using var reader = await command.ExecuteReaderAsync();
if (!await reader.ReadAsync())
{
throw new InvalidOperationException($"No {table} row with id {id}.");
}
var row = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i);
}
return row;
}
/// <summary>
/// Reads columns of one row as SQL Server prints them as text (<c>CONVERT(nvarchar(max), column, 126)</c>: ISO 8601
/// for dates, with a datetimeoffset's own offset), which shows the stored value exactly, whatever its type.
/// </summary>
public async Task<Dictionary<string, string?>> TextRowAsync(string table, long id, params string[] columns)
{
await using var connection = await OpenConnectionAsync();
var select = string.Join(", ", columns.Select(x => $"CONVERT(nvarchar(max), [{x}], 126)"));
await using var command = new SqlCommand($"SELECT {select} FROM {table} WHERE id = @p0", connection);
command.Parameters.AddWithValue("@p0", id);
await using var reader = await command.ExecuteReaderAsync();
if (!await reader.ReadAsync())
{
throw new InvalidOperationException($"No {table} row with id {id}.");
}
var row = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < columns.Length; i++)
{
row[columns[i]] = reader.IsDBNull(i) ? null : reader.GetString(i);
}
return row;
}
}
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.
> 1. Register one service per database, by key (in ASP.NET Core: builder.Services)
> 2. Place an order in the CRM, then record it in reporting
CRM: order 1 committed; reporting: 1 event
> 3. Recording the same event again (a retry after a failure) is harmless
second attempt recorded a new row: False; events for SO-6001: 1