/samples contains a complete, runnable solution: Scry.Samples.slnx.
| Project | Role |
|---|---|
Sample.Model |
The EF Core model, with the allow-list attributes. The server references it, and the client points at it by path. |
Sample.WebServer |
The ASP.NET Core host: the DbContext, MapScry, MapScryExplorer, and the Blazor host page. Every client below talks to this one back end. |
Sample.CommandHandlers |
The handlers and policies for the model's commands, and the single registration that every host with commands turned on uses. |
Sample.WebClient |
A Blazor WebAssembly UI that writes LINQ against the generated models. |
Sample.ConsoleClient |
A console client that uses an HttpClient, ScryClient.ForHttp and the generated entry point, with no dependency injection container. |
Sample.WpfClient |
A WPF client that binds the same queries to a DataGrid, with the client registered through IHttpClientFactory. |
Sample.WinFormsClient |
A Windows Forms client with the same registration, which binds the queries to a DataGridView. |
Sample.Tests |
Snapshot tests of the rendered UI, the wire traffic, and the explorer endpoint. |
Sample.QueryModels |
A C# class library that contains the generator's output for the sample model, for use by clients in other languages. |
Sample.FSharp |
An F# client that writes queries through Sample.QueryModels. See F#. |
Sample.FSharp.Tests |
Runs the F# queries against the server, hosted in-process, and snapshots the requests and rows. |
Sample.TypeScriptClient |
The console client's queries written in TypeScript, against a model generated from the server's introspection. It also fetches each employee's photo. It is a Node project, outside the solution. See TypeScript. |
Sample.TypeScriptWeb |
Sample.WebClient's pages written in TypeScript and built with Vite: queries and photos, offset and keyset paging, the cached row policy, a live orders table read through a callback or a loop, and the commands page with its pending work. The Vite plugin generates the model. It is outside the solution. See TypeScript. |
Sample.RedisServer, Sample.MessagePipeServer |
Each is a minimal server, meant to be run twice, with a backplane carrying changes from one node to the other. |
Sample.NServiceBusServer, Sample.NServiceBusWorker |
The same over NServiceBus, plus a worker whose handler writes to the database from another process. |
Sample.DisclosureServer |
A host with the disclosure audit turned on. It keeps a record of everything it sends in SQL Server, and serves the explorer over that record. |
Sample.ModelPackageClient |
The console client's first query, generated from Sample.Model packed as a NuGet package. It is outside the solution; see The model as a package. |
The three desktop and console clients show that the client half is not tied to a browser. Client hosts covers what each host needs and how they differ.
The sample uses SQL Server LocalDB, and creates and seeds the database on startup.
dotnet run --project samples/Sample.WebServerThen browse to the URL it prints. The query explorer is at /scry.
The other clients talk to the same server over HTTP, so start it first and leave it running. If the server is not running, each client prints the command above instead of throwing an unhandled exception.
dotnet run --project samples/Sample.ConsoleClientdotnet run --project samples/Sample.ConsoleClient -- --reprice 1dotnet run --project samples/Sample.WpfClientdotnet run --project samples/Sample.WinFormsClientThe WPF and Windows Forms clients build only on Windows. On other operating systems they build as an empty assembly, so the samples solution still builds there.
The model has four sources, which between them cover every kind:
[Queryable]
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = "";
public Status Status { get; set; }
public bool Active { get; set; }
public DateOnly Created { get; set; }
public int? ManagerId { get; set; }
public Employee? Manager { get; set; }
public int DepartmentId { get; set; }
public Department? Department { get; set; }
// A claim check rather than a value: no query reads it, and what a client gets back is a handle
// carrying this row's key. A photo is the case the attribute exists for — bytes nothing wants on
// every row of every query, fetched by the one thing that actually wants to draw them. The check
// that authorizes the fetch is registered by the server; this project references the annotations
// alone, so [AttachmentWith] has no policy type to name here.
[Attachment(ContentType = "image/svg+xml")]
public byte[]? Photo { get; set; }
// Never exposed to clients.
[QueryIgnore]
public decimal Salary { get; set; }
// The other half of that pair: queryable, but never in a URL and never in a cache. [QueryIgnore]
// hides a member outright; [Sensitive] keeps it askable while refusing the two ways its value
// escapes — a query comparing it against a constant travels as a body rather than a URL, where the
// constant would land in every access log on the way, and a response projecting it is sent
// no-store, where a cacheable one would be written to the caller's disk.
[Sensitive]
public string Password { get; set; } = "";
}Salary is marked [QueryIgnore], so it is missing from the generated client model, and the server rejects a raw request that names it.
[Queryable]
public class Order
{
public int Id { get; set; }
public string Region { get; set; } = "";
public decimal Amount { get; set; }
// A collection of values, which EF stores as a JSON column. Present in the sample so the round-trip
// tests cover one end to end: the generator spells its element from the model DLL and the server
// spells it from reflection, and the two stamps only agree if they agree about this member.
[QueryableCollection]
public List<string> Tags { get; set; } = [];
// What the cached row policy on this type reads to know a row needs deciding again. Server-side
// machinery rather than query surface, so it is hidden from clients like anything else Scry was
// not told to expose — a version column need not be one a client can see. A real deployment more
// often maps a rowversion as ulong and lets the database move it; this one writes it, so the
// sample can show a row being re-decided on demand.
[QueryIgnore]
public long Revision { get; set; }
}/// <summary>A keyless EF Core entity mapped to a database view.</summary>
[QueryableView]
public class EmployeeSummary
{
public string Department { get; set; } = "";
public int Headcount { get; set; }
}/// <summary>A POCO that is not part of the persisted model.</summary>
[QueryablePoco]
public class Holiday
{
public string Name { get; set; } = "";
public DateOnly Date { get; set; }
public static IEnumerable<Holiday> Seed() =>
[
new()
{
Name = "New Year",
Date = new(2026, 1, 1)
},
new()
{
Name = "Workers Day",
Date = new(2026, 5, 1)
},
new()
{
Name = "Christmas",
Date = new(2026, 12, 25)
}
];
}EmployeeSummary is a keyless entity over a database view that the seed routine creates.
public DbSet<Department> Departments => Set<Department>();
public DbSet<Employee> Employees => Set<Employee>();
public DbSet<Order> Orders => Set<Order>();
public DbSet<EmployeeSummary> EmployeeSummaries => Set<EmployeeSummary>();
public DbSet<Asset> Assets => Set<Asset>();
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<EmployeeSummary>()
.HasNoKey()
.ToView("EmployeeSummary");
// Table-per-hierarchy: the derived types share the base table and are told apart by a
// discriminator, which is what OfType narrows on.
builder.Entity<Vehicle>();
builder.Entity<Building>();
}services
.AddScry<SampleContext>(_ =>
{
// Holiday is a [QueryablePoco]: it has no table, so the server supplies its rows. Every
// [QueryablePoco] type must be registered here or AddScry throws at startup.
_.AddPocoSource(_ => Holiday.Seed());
// Department.Handbook and Employee.Photo are [Attachment]s, and one exposed without a
// check is a startup failure. Registered here rather than by [AttachmentWith] because
// the model project references the annotations alone and has no server type to name.
_.AddAttachmentPolicy<Department, HandbookPolicy>();
_.AddAttachmentPolicy<Employee, PhotoPolicy>();
_.MaxPageSize = 200;
// A row policy whose decision is too slow to run per row in SQL, so it runs in C# and
// the server remembers what it answered. Revision is what tells it a row has changed
// and needs deciding again — see /docs/policies.md and the /permissions page.
_.AddCachedPolicy<Order, long, RegionAccessPolicy>(_ => _.Revision);
// Repeat a query while nothing has been written and the answer is a 304 rather than a
// re-execution. Optional, and off until a freshness source says how to tell — see
// /docs/caching.md.
_.UseDeltaFreshness<SampleContext>();
// What a cached response belongs to. This server has sources whose answers depend on
// who asked — the row policy above, and Department.Handbook's attachment check — and
// MapScry refuses to start without this. The sample has no sign-in, so the caller
// half is a constant; a real app returns its tenant or its principal, and a client
// signing in as someone else is then never handed the previous one's rows.
//
// The grants version is the other half, and is the part worth copying. A response
// varies by what the caller is allowed to see, and QueryFreshness only watches the
// database — so a grant changing outside it would move nothing, and a cache holding
// the old rows would go on answering with rows the caller has since lost.
_.CacheScope = _ => $"sample-{_.RequestServices.GetRequiredService<RegionGrants>().Version}";
// Live queries: the /live pages. Off until a server says how many it will hold open,
// which is also what maps the route — see /docs/live-queries.md.
_.MaxSubscriptions = 100;
// The interceptor above reports this server's own saves, at once and by entity. This
// watches the database's change marker for everything it cannot see: a bulk update,
// another node, a script run by hand.
_.UseDeltaChanges<SampleContext>();
// Commands: the /commands page and the /live pages' Reprice. Off until a server says
// how many it will have in flight, which is also what maps the routes — see
// /docs/commands.md.
_.UseSampleCommands();
// An AI agent's way in: the schema, queries and commands over MCP, at /mcp. Off
// until a server says what an agent may do — see /docs/mcp.md.
_.Mcp = ScryMcpAccess.ReadWrite;
});Holiday has no table, so its rows are registered explicitly; see POCO sources. MaxPageSize is lowered from the default of 1000 to 200.
app.MapScry("/api/query");app.MapScryExplorer(_ =>
{
_.Route = "/scry";
// This sample always exposes the explorer. The default guard is Development-only — in a real
// app, run in Development or set EnableGuard to your own check (e.g. an admin authorization).
_.EnableGuard = _ => true;
});The sample always exposes the explorer, so it can be browsed in any environment. A real app should leave the default Development-only guard in place, or replace it with an authorization check; see Query explorer.
The server also returns 304 Not Modified for a repeated query, using Delta as the freshness source behind the ETag. This takes two settings inside AddScry, shown in the registration above.
The client half is a DelegatingHandler in Sample.WebClient. It resends the request with If-None-Match, and on a 304 rebuilds the response from what it kept last time. Neither half is part of Scry; Caching and 304 explains both.
<!-- The server model, pointed at by path. NOT referenced. -->
<ScryModelDll>$(MSBuildThisFileDirectory)..\Sample.Model\bin\$(Configuration)\net11.0\Sample.Model.dll</ScryModelDll><ItemGroup>
<ProjectReference Include="..\..\src\Scry.SourceGenerator\Scry.SourceGenerator.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\Sample.Model\Sample.Model.csproj" ReferenceOutputAssembly="false" />
<CompilerVisibleProperty Include="ScryModelDll" />
<CompilerVisibleProperty Include="ScryModelStamp" />
</ItemGroup>
<!-- Resolved against the project before the compiler sees it, as the shipped targets do. -->
<PropertyGroup Condition="'$(ScryModelDll)' != ''">
<ScryModelDll>$([MSBuild]::NormalizePath('$(MSBuildProjectDirectory)', '$(ScryModelDll)'))</ScryModelDll>
</PropertyGroup>
<Target Name="ComputeScryStamp"
AfterTargets="ResolveProjectReferences"
BeforeTargets="GenerateMSBuildEditorConfigFile;CoreCompile"
Condition="Exists('$(ScryModelDll)')">
<GetFileHash Files="$(ScryModelDll)" Algorithm="SHA256">
<Output TaskParameter="Hash" PropertyName="ScryModelStamp" />
</GetFileHash>
</Target>The sample uses project references rather than the NuGet package, so it writes out the generator wiring that Scry.Client's buildTransitive targets would normally supply. See Source generator.
var services = builder.Services;
services.AddHttpClient(
"scry",
_ => _.BaseAddress = new(builder.HostEnvironment.BaseAddress));
services.AddScryClient(
"/api/query",
_ => _.GetRequiredService<IHttpClientFactory>().CreateClient("scry"));
services.AddScoped<ScryQuery>();Sample.ModelPackageClient is generated from Sample.Model consumed as a NuGet package rather than as a project. This is the layout for a model that one team publishes and other teams consume (The model as a package). The project is outside Scry.Samples.slnx, because the package has to exist before the project can restore. pack-model.ps1 packs the model into the project's feed folder, at a version derived from the package's content, so the NuGet cache never serves a stale copy:
pwsh samples/Sample.ModelPackageClient/pack-model.ps1dotnet run --project samples/Sample.ModelPackageClientIts build fails if the model, or the EF Core it depends on, ends up in the project's references or output. Keeping them out is the point of the package reference the project demonstrates.
The UI declares whatever shapes it wants:
record EmployeeRow(string Name, Status Status, string? Manager, string Department);
record RegionSummary(string Region, decimal Total, int Count);A filter, an ordering, and a projection that reaches through two navigations:
employees = await Query
.Employee
.Where(_ => _.Active)
.OrderBy(_ => _.Name)
.Select(_ => new EmployeeRow(_.Name, _.Status, _.Manager!.Name, _.Department!.Name))
.ToListAsync();A group-by with aggregates:
regions = await Query
.Order
.GroupBy(_ => _.Region)
.Select(_ => new RegionSummary(_.Key, _.Sum(_ => _.Amount), _.Count()))
.ToListAsync();And a query parameterized by captured local variables. The client evaluates the values and sends them as constants, which is how an app builds a filtered query at runtime:
fullTimers = await Query
.Employee
.Where(_ => _.Status == status)
.OrderBy(_ => _.Name)
.Take(top)
.Select(_ => new EmployeeRow(_.Name, _.Status, _.Manager!.Name, _.Department!.Name))
.ToListAsync();Employee.Photo is an [Attachment]. No query reads it. Instead, each row comes back with a handle that carries the row's key. So the projection has to include Id next to the photo, because that is the key used to fetch the bytes. Leaving it out is a build error, not a runtime error.
// The photo is not a value this row carries: the query brings back a handle, and Id has to be
// projected beside it because that is the key the bytes are fetched by.
record EmployeePhoto(int Id, string Name, ScryAttachment Photo);// No bytes travel with this. Every row comes back holding a handle to its photo and the
// key that handle is redeemed by; the response is the same size whether the photos are
// eight bytes or eight megabytes.
photos = await Query
.Employee
.OrderBy(_ => _.Name)
.Select(_ => new EmployeePhoto(_.Id, _.Name, _.Photo))
.ToListAsync();The page renders the names from that response, and only then fetches the bytes: one request per face, each authorized separately by the server's IAttachmentPolicy:
// One request per face, each authorized on its own terms by the server's IAttachmentPolicy.
foreach (var photo in photos)
{
if (await FaceAsync(photo.Photo) is { } face)
{
faces[photo.Id] = face;
}
}/// <summary>
/// Redeems one handle for its bytes, or null when the row holds no photo — a readable row with an
/// empty column, which the server answers with a 204 rather than by refusing. The caller owns the
/// stream and disposes it; a real photo would stream rather than land in memory whole, which this
/// one does only because it ends up in an <c>img</c> tag. The media type below is the one
/// <c>Employee.Photo</c> declares, and the one the fetch was served as.
/// </summary>
static async Task<string?> FaceAsync(ScryAttachment photo)
{
await using var bytes = await photo.OpenAsync();
if (bytes is null)
{
return null;
}
var buffer = new MemoryStream();
await bytes.CopyToAsync(buffer);
return $"data:image/svg+xml;base64,{Convert.ToBase64String(buffer.ToArray())}";
}Employee.Photo declares ContentType = "image/svg+xml", so the fetch is served with that content type rather than as generic bytes. This lets the explorer and the sidecar offer the download as an .svg file. Department.Handbook declares text/plain and downloads as .txt. See Content type.
Three of the four employees have a photo. Carol has none, and the page draws an empty circle for her rather than an error. A readable row with nothing in the column returns 204, which is different from the 404 returned for a refusal. Open the sidecar on the running sample to see the four fetches listed as ATTACHMENT next to the queries: three 200s and a 204.
Order is scoped by a cached row policy. Deciding which regions a caller may see takes a lookup against another system. In the sample that system is RegionGrants, which stands in for a permissions service and sleeps for 25ms to show that a query cannot afford the lookup for every row.
/// <summary>
/// Scopes <see cref="Order"/> to the regions the caller is granted. Written as a cached policy rather
/// than an ordinary <c>IReturnablePolicy</c> because the decision is a lookup against another system —
/// far too slow to run per row inside every query, and unchanging often enough to be worth remembering.
/// </summary>
public sealed class RegionAccessPolicy(RegionGrants grants) :
ICachedRowPolicy<Order>
{
/// <summary>
/// Which set of answers this call belongs to. The sample has no sign-in, so there is one caller and
/// one scope, exactly as <c>CacheScope</c> has one; a real app returns the tenant or the principal
/// resolved from <c>context.Services</c>. Never from a request header — decisions are remembered
/// per scope, so a caller choosing its own scope key is a caller choosing its own permissions.
/// </summary>
public string ScopeKey(ScryPolicyContext context) => "sample";
/// <summary>
/// The expensive part. It runs off the query path — for a row that is new, one whose
/// <see cref="Order.Revision"/> has moved, and every row the first time a scope is read — and never
/// again just because a query ran.
/// </summary>
public bool Allow(Order row, string scopeKey, ScryPolicyContext context) =>
grants.Allows(scopeKey, row.Region);
}So the policy runs in C# rather than in SQL, and the server caches its decisions. The query the server runs contains a membership test over the keys this caller is allowed to see. That is why the LINQ on the page is the same as it would be for any other source: nothing in it shows that the policy is cached.
The /permissions page makes the caching visible, since a cache that works looks exactly like no cache at all. It shows how many times the expensive decision has actually run, and has three buttons:
| Action | Decisions | Why |
|---|---|---|
| Run the query again | unchanged | Every row already has a decision. An ordinary policy would have filtered them all again. |
| Revise an order | +1 | The order's Revision rises past the watermark, the highest revision already decided for this caller, so that one row is decided again, without anything telling the cache to do so. An inserted row is decided correctly on its first read in the same way. |
| Revoke a region | +3 | The grant changed, and no column records that, so the server tells the cache. The caller's cached decisions are discarded and made again. |
The second and third rows are the two cases worth understanding. Revising an order calls nothing on the cache:
// A row changed. Nobody tells the cache anything here: the next query sees a revision past the
// watermark this scope was decided up to, and decides that one row on the spot. An insert by
// any writer at all is correct on its first read for the same reason.
app.MapPost(
"/api/orders/{id:int}/touch",
async (int id, SampleContext data) =>
{
var order = await data.Orders.FindAsync(id);
if (order is null)
{
return Results.NotFound();
}
// Named explicitly: Scry's async terminals and EF's are both in scope here, and they are
// not the same method — this one has to run against the database.
order.Revision = await EntityFrameworkQueryableExtensions.MaxAsync(data.Orders, _ => _.Revision) + 1;
await data.SaveChangesAsync();
return Results.NoContent();
});Revoking a region has to tell the cache, or the change never reaches a query at all:
// A grant moved. Nothing about any order changed, so no version column could notice and no
// query would ever decide those rows again — the cache has to be told, and telling it is part
// of the authorization path rather than a cache optimization.
app.MapPost(
"/api/grants/{region}",
(string region, bool allowed, RegionGrants grants, ScryPolicyCache cache) =>
{
grants.Set("sample", region, allowed);
cache.InvalidateScope<Order>("sample");
return Results.NoContent();
});Order.Revision is marked [QueryIgnore]: a version column is server machinery, not part of the query surface, so clients never see it. Sample.Tests\CachedPolicyPageTests.cs drives the page and asserts those three counts, so a test checks the table above.
This sample also has 304s turned on, and the two features conflict unless the host accounts for it. Revoking a grant writes nothing to the database, so Delta's freshness token cannot change. A caller holding an ETag gets a 304, the query never runs, and the caller keeps showing rows it no longer has access to, however promptly InvalidateScope was called. So the grants version is part of the cache scope:
_.CacheScope = _ => $"sample-{_.RequestServices.GetRequiredService<RegionGrants>().Version}";ConditionalQueryTests.RevokingAGrantInvalidatesTheEtagWithoutAWrite tests this, and fails without that version. The page also requests its own rows with Cache-Control: no-cache, because on a 304 the server decides nothing, so the counter would never change.
The Live link opens four pages over one query (open orders, and a count of them). Each page consumes a live query in a different way: a callback, an await foreach, an IObservable<T> with System.Reactive, and one subscription shared by two components through MessagePipe. Scry.Client references none of those libraries; the sample does.
Open a page in two tabs and press a button in one. Both tabs update, and neither reloads.
| Control | What it shows |
|---|---|
| Reprice an order | The RepriceOrder command, sent over whichever transport the switch selects. ScryChangeInterceptor reports its handler's SaveChanges, with no code written for it. |
| Reprice in bulk | An ExecuteUpdate, which no interceptor sees, followed by a call to ScryChanges.Notify<Order>() to report the change. |
| SSE / SignalR | The same pages over a hub. The transport belongs to the ScryClient, so no page changes. |
| The region grants on the Permissions page | A policy-cache invalidation: rows appear and disappear without any write to them. |
The server also sets UseDeltaChanges, so a write from anywhere else, such as SQL Server Management Studio, also shows up within a second.
The other clients run the same query from a Live checkbox (WPF, Windows Forms) or a command-line argument:
dotnet run --project samples/Sample.ConsoleClient -- --liveA backplane connects several processes that share one database. Sample.WebServer cannot run that way, because it builds a new database on each launch. So each backplane has a minimal server whose Program.cs contains the registration and little else. The first process started builds the database and prints the command that starts the second process against it.
NServiceBus needs nothing installed, since the sample runs on the learning transport:
dotnet run --project samples/Sample.NServiceBusServer -- --urls http://localhost:5101Start the worker with the command the server prints. Then watch the server from the console client, and from a second terminal send the command that the worker handles:
dotnet run --project samples/Sample.ConsoleClient -- --live --server http://localhost:5101dotnet run --project samples/Sample.ConsoleClient -- --reprice 1 --server http://localhost:5101The server forwards RepriceOrder to the worker instead of handling it, and the worker's reply completes it. The first console prints the table again, for a row written by a process that hosts no Scry endpoint, and the second prints the outcome. NServiceBusSampleTests runs the same exchange in-process.
Sample.RedisServer and Sample.MessagePipeServer need Redis running on localhost:6379. Start one instance on :5101, and a second on :5102 with the printed command. Watch the first, and send --reprice 1 --server http://localhost:5102 to the second. These servers turn the poll off, so any change that arrives must have come over the backplane. A real deployment leaves the poll on.
The Commands link opens a live table of employees, with a button for each command and a form to hire someone. None of the buttons refreshes the table. The table is a live query, so whatever a command writes arrives as the query's next answer.
| Try | What it shows |
|---|---|
| Deactivate a row | SetEmployeeActive. The row's Delete button becomes enabled when the next answer arrives. The button follows the row's CanDeleteEmployee, which is the delete policy's condition evaluated in the database. |
| Delete an inactive row | DeleteEmployee. The row is gone from the table in the next answer. |
| Delete Alice, once deactivated | The handler refuses, because Alice manages other employees. The result is a Failed outcome that carries the handler's own message. |
| Rename to a name containing "slow" | The handler takes five seconds, longer than the server's sync window and the client's wait, so the pending-work panel opens and tracks the command until it completes. |
| Hire | CreateEmployee, which returns the new row's id through the typed outcome. |
Each of the other clients shows a different aspect. The console client's --reprice prints the outcome, and awaits Completion when the outcome is Pending. The Windows Forms client renames the selected row and lists PendingWork, whose change notifications arrive on the UI thread. The WPF client binds its Rename button to an ICommand whose CanExecute combines the facade's CanRenameEmployee with whether a row is selected, and raises CanExecuteChanged again on CapabilitiesChanged. The F# client renames an employee, and hires one through the typed outcome.
async Task RenameSelected()
{
if (grid.CurrentRow?.DataBoundItem is not EmployeeRow row)
{
status.Text = "Select an employee to rename.";
return;
}
try
{
var outcome = await query.Commands.RenameEmployee(new() {Id = row.Id, Name = renameTo.Text});
status.Text = outcome.Status switch
{
ScryCommandStatus.Completed => $"Renamed {row.Name} to {renameTo.Text}.",
ScryCommandStatus.Pending => "Still renaming. It is listed under pending work.",
_ => outcome.Error
};
}
catch (Exception exception) when (exception is HttpRequestException or ScryRequestException or ScryPermissionException)
{
status.Text = exception.Message;
}
}
// The store says it changed on the context the command was sent from — the UI thread, since
// RenameSelected runs there — so the list is redrawn with no Invoke.
void ShowPendingWork() =>
pending.DataSource = work.Items.Select(Describe).ToList();
static string Describe(ScryPendingCommand item)
{
var line = $"{item.Command} {string.Join(", ", item.Keys)}: {item.Status}, {item.Elapsed.TotalSeconds:0.0}s";
if (item.Error is { } error)
{
return $"{line} — {error}";
}
return line;
}// The XAML shape of a capability: an ICommand whose CanExecute is what the server last said this
// caller may send, and whether there is a row to send it against. WPF re-reads it whenever
// CanExecuteChanged is raised, which the window does as either of those moves.
sealed class RenameEmployeeCommand(
ScryQuery query,
Func<EmployeeRow?> selected,
Func<string> name,
Action<string?> report) :
ICommand
{
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter) =>
query.Commands.CanRenameEmployee &&
selected() is not null;
public async void Execute(object? parameter)
{
if (selected() is not { } row)
{
return;
}
try
{
var outcome = await query.Commands.RenameEmployee(new() {Id = row.Id, Name = name()});
report(
outcome.Status switch
{
ScryCommandStatus.Completed => $"Renamed {row.Name}.",
ScryCommandStatus.Pending => "Still renaming.",
_ => outcome.Error
});
}
catch (Exception exception)
{
report(exception.Message);
}
}
public void Raise() =>
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}Sample.Tests snapshots the actual HTTP exchange for the first query:
[
{
RequestUri: {
Path: http://localhost/api/query,
Query: {
q: {"version":1,"root":"Employee","pipeline":[{"$type":"where","predicate":{"$type":"member","path":"Active"}},{"$type":"orderBy","key":{"$type":"member","path":"Name"},"descending":false},{"$type":"select","projection":{"members":["Name","Status",{"name":"Manager","value":{"$type":"node","node":{"$type":"member","path":["Manager","Name"]}}},{"name":"Department","value":{"$type":"node","node":{"$type":"member","path":["Department","Name"]}}}]}}],"stamp":"{scrubbed stamp}"}
}
},
RequestMethod: GET,
ResponseStatus: OK 200,
ResponseHeaders: {
Cache-Control: no-cache, private,
Scry-Schema-Stamp: {Scrubbed},
Scry-Url-Limit: 4096
},
ResponseContent: {"version":2,"kind":"List","payload":[{"name":"Aaron","status":"FullTime","manager":"Alice","department":"Engineering"},{"name":"Alice","status":"FullTime","manager":null,"department":"Engineering"},{"name":"Carol","status":"Contractor","manager":null,"department":"Sales"}],"stamp":"{scrubbed stamp}"}
}
]Four projected columns are requested, and four are returned. Salary is neither requested nor returnable.
A command that completes within the sync window takes one request and gets one receipt:
POST /api/query/command
{"version":1,"command":"SetEmployeeActive","id":"0b9d4f7e-3a51-4c2e-8f60-6d1a2e9c7b14","payload":{"id":4,"active":true},"stamp":"…"}
200 application/json
{"version":1,"id":"0b9d4f7e-3a51-4c2e-8f60-6d1a2e9c7b14","status":"Completed","stamp":"…"}
A slow rename sends the same request, but the response is a stream: the pending receipt immediately, then the outcome when the handler finishes.
200 text/event-stream
event: result
data: {"version":1,"id":"6e0f…","status":"Pending","stamp":"…"}
event: result
data: {"version":1,"id":"6e0f…","status":"Completed","stamp":"…"}
Sample.DisclosureServer is a separate host with the disclosure audit turned on. Every answer is committed as a row in the application's own database before it is sent. If the database does not accept the row, the answer is not sent:
services
.AddScry<SampleContext>(_ =>
{
// What the model needs before any server will start: see Sample.WebServer.
_.AddPocoSource(_ => Holiday.Seed());
_.AddAttachmentPolicy<Department, SignedIn<Department>>();
_.AddAttachmentPolicy<Employee, SignedIn<Employee>>();
// Every answer is a committed row in this database before it is sent, and an answer
// the database does not take is not given. The application's own database, so that
// recording adds nothing that can be down to the path of an answer.
_.UseSqlServerDisclosureAudit(
database.ConnectionString,
store =>
{
// The record is kept as a log is: a new segment of it each month, and
// two years of them. The oldest is then dropped, and what it held can no
// longer be asked. Set Retire to write it somewhere else first.
store.RollAfter = TimeSpan.FromDays(30);
store.Keep = 24;
store.Clock = clock;
},
audit =>
{
audit.Node = "sample";
audit.Clock = clock;
// A row is recorded by its key, and a source with none has to be given one or
// owned up to: a view by what its rows are grouped on.
audit.Key<EmployeeSummary>(_ => _.Department);
// Left out of the record: a calendar is nobody's to ask after, and neither is
// the logo or the handbook a department publishes. An answer of nothing but
// these is sent as it would be with the audit off. One that reads anything
// else is recorded, with a marker where a holiday, a logo or a handbook was.
audit.Exclude<Holiday>();
audit.Exclude<Department>(_ => _.Logo, _ => _.Handbook);
});
// A query asked by URL may be kept by the caller's own cache, which has to ask before
// using its copy again. Being told the copy still stands is a 304, and is recorded
// before it is said. Nothing writes to this sample's rows once it has started, so an
// answer stands for as long as the server does. A real host reads a change marker
// here, as Sample.WebServer does with Delta — and then keeps the record in a database
// of its own: Delta reads the database's log position, which every answer recorded
// beside the rows would move, so no recorded answer would ever be found unchanged.
_.QueryFreshness = (_, _) => new(started);
// Whose cache an answer belongs in: the caller's, since what is sent depends on who asks.
_.CacheScope = _ => _.User.Identity?.Name;
});dotnet run --project samples/Sample.DisclosureServerThe audit records everything under a caller's name, so the host has a stand-in for signing in. Sign in as alice and run a few queries in the query explorer at /scry, then sign in as auditor and open /scry-disclosures to see who was sent what. The stand-in signs the visitor in as whatever name a link gives, with no password. It lets the sample show the audit without also being an authentication sample, and is not a pattern to copy.
// The record, read back. Shut to everybody but the one person whose job it is — a real host
// puts its own authorization here, and RequireAuthorization on what this returns.
app.MapScryDisclosureExplorer(_ =>
{
_.EnableGuard = DemoSignIn.IsReviewer;
_.EnableExport = DemoSignIn.IsReviewer;
// Off unless a host turns it on, and it cannot be taken back: on here so there is
// something to try it against.
_.EnableErase = DemoSignIn.IsReviewer;
});It is separate from Sample.WebServer so that the record contains only what was requested from this host, and so that the larger sample runs without recording anything.
Its front page links to two queries sent by URL. The first, a count of the orders, is recorded as sent. Reloading it returns 304, which is recorded as a confirmation. The second reads the holidays. The sample excludes holidays from the record, along with a department's logo and handbook, so requesting them records nothing and needs nobody signed in.
/IntegrationTests hosts the same model in a real ASP.NET Core test server against LocalDB, and tests the full round trip through the typed client. That includes checking that a hand-crafted request naming an ignored property is rejected:
[Test]
public async Task DisallowedPropertyRejectedWith400()
{
const string json = """
{
"version": 1,
"root": "Employee",
"pipeline": [
{
"$type": "where",
"predicate": {
"$type": "binary",
"op": "GreaterThan",
"left": { "$type": "member", "path": "Salary" },
"right": { "$type": "const", "value": "100", "tag": "Decimal" }
}
}
]
}
""";
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await http.PostAsync("/api/query", content);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
}CommandRoundTripTests does the same for commands. It sends every generated command over HTTP to a host running the sample's own handlers, and checks the typed result, the enum payload sent by name, a slow rename's streamed receipt, and a delete arriving as a live query's next answer. CommandHttpTests and CommandHubTests test the command routes and hub methods themselves, against their own model.

