diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ff2da2f4..01188b577 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2560,6 +2560,41 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ### Changed +- **C#: generators qualify framework references as they write them; the runner no longer rewrites + output.** With `csharp.packageNamespaces` on, a package segment can shadow a framework namespace + (`acme::app::system` derives `Acme.App.System`), so a bare `System.Text.Json` inside `Acme.App` + does not compile. The runner used to fix that by rewriting every `System.`/`Microsoft.` reference + in every emitted `.cs` file to `global::`, including the output of owned generators. Each + reference generator now spells framework names through `CSharpNaming.Framework(config, name)` / + `CSharpNaming.FrameworkPrefix(config)`, or its own `Fx` prefix, which is set when a run starts. + Through the runner the output is byte-identical. A generator called directly with package + namespaces on now writes the `global::` form itself. What stays in the runner is a check. A file + that still writes a bare reference that a namespace of the run actually shadows is named in a + warning, with the fix; the warning means that file will not compile. In practice that is an + owned copy ejected from a 1.3.0 candidate. +- **C#: `DbContextGenerator`'s text hooks have `CsWriter` overloads.** `OwnedTypeConfig`, + `FieldTypeConfig`, `DbColumnTypeConfig`, `DefaultValueConfig`, `ReferenceConfig`, + `TphSubtypeFieldConfig`, `EntityConfigTrailer`, `EmitCheckConfig`, `DbSetLine`, + `ContextMemberLines`, `ContextPreambleLines` and `ContextTrailerLines` each take the writer as + their first argument as well. An override writes a nested block with `Braced` (an `OwnsOne(x => + x.Nav, b => { … })`, an `if` around several statements) instead of building one string with + embedded newlines. Each writer overload defaults to its text hook, so an existing override keeps + working and a generator that overrides none writes the same bytes and the same `ConfigureModelNN` + split. What one writer overload writes is one model entry, never split across two methods. An + `OwnedTypeConfig` override that writes nothing leaves the field unconfigured. +- **C#: `Fr019SharedEnum.ProvidedEnumNamespace(SharedEnum, GenConfig)` is public.** It returns the + namespace a provided shared enum is referenced in: the package binding, else + `ProvidedEnumNamespace`. It throws, naming the package, when neither is set. Before, only the + materialized case had a namespace seam (`MaterializedNamespace`). `SharedEnumTypeReference` + calls it, so the two never disagree. +- **C#: an object-typed field a view class cannot carry is reported once by `verify`, not on every + `gen`.** The entity generator leaves an object-typed field off a read-only projection, and a + flattened value object off a write-through entity's `View` read model. It used to print a + warning on every regen. `gen` now prints nothing. `dotnet meta verify` lists each such field once, + when the run includes the entity generator, with the fix. For a projection: remove the field, or + read the value through its entity. For a read model: store the value object `@storage: jsonb`, + which the read model carries. + - **Java and Kotlin: Mustache treats a zero or `NaN` number as a falsy section.** mustache.java treats any non-null `Number` as true, so `{{#count}}…{{/count}}` with `count = 0` rendered its body in Java and dropped it in TypeScript, C# and Python. `com.metaobjects.render.Renderer` now diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index e78de7627..1282b383c 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -251,6 +251,8 @@ run: unflagged cross-file redeclarations (`WARN_OVERLAY_IMPLICIT`), whitespace i The overlay lint reads the raw files, so it runs even when the model does not load; the name and deprecation lints read the loaded model and print nothing when it does not load (the load error is the gate's report). +When the run includes the entity generator, `dotnet meta verify` also lists, once, each object-typed field that +generator leaves off a projection or a write-through read model, with its fix. `gen` prints nothing for it. Mute each with `--no-overlay-lint`, `--no-name-lint`, `--no-deprecation-lint` or `--no-field-lint`, or the matching `META_NO_*_LINT=1`. The codes and message text match Node `meta verify`, gated by `fixtures/model-lint-conformance/` and `fixtures/field-lint-conformance/`. @@ -559,6 +561,21 @@ written. An entry that already carries an indent still reads right, because the common margin before it indents. A `ContextUsings` line is a `using ...;` directive, which the writer prints once, in the order given. +Each of those statement hooks also has an overload that takes the `CsWriter` as its first argument +(`OwnedTypeConfig(CsWriter w, ...)`, `EntityConfigTrailer(CsWriter w, ...)` and the rest, all but +`ContextUsings`). Override that one to write a nested block with `w.Braced(...)`, such as an +`OwnsOne(x => x.Nav, b => { ... })` or an `if` around several statements, instead of returning one string +with embedded newlines. Its default writes what the text hook returns, so an existing text override still +works. What one writer overload writes is a single model entry: `ModelConfigChunkSize` never splits it +across two `ConfigureModelNN` methods. + +**Framework names.** With `csharp.packageNamespaces` on, a package segment can shadow a framework +namespace (`acme::app::system` derives `Acme.App.System`). Each generator therefore writes a framework +reference through its `Fx` prefix (`$"{Fx}System.Text.Json.JsonSerializer"`), or through +`CSharpNaming.Framework(config, name)`, which gives `global::System...` exactly when package namespaces +are on. Nothing rewrites generated text afterwards. If an emitted file still writes a bare reference that +a namespace of the run shadows, the runner names that file in a warning. + **One line at a time.** Each of these is a `protected virtual` hook whose default is the line it replaces; override it, call base, and adjust. On `EntityGenerator`: `ValueObjectMemberAttributes` (the `[JsonPropertyName]` before each value-object member), `ColumnAttributeArguments` (the diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index 843fa01c7..8d22fff97 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -512,6 +512,9 @@ private static Codegen.CodegenDrift.Result RunCodegenDrift(Options opts, List $"warning: {w}")); + // Object-typed fields the entity generator leaves off a view-mapped class: said once, here. + advisories.AddRange(Codegen.Generators.EntityGenerator.UnemittedObjectFields(load.Root, generators.Select(g => g.Unwrap())) + .Select(w => $"warning: {w}")); return Codegen.CodegenDrift.Compute(config, load.Root, generators); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/CodegenCompileConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CodegenCompileConformanceTests.cs index c913fb5b3..a307d5668 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CodegenCompileConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CodegenCompileConformanceTests.cs @@ -109,7 +109,7 @@ private static MetaRoot LoadCorpus() /// The same selections under the opt-in package layout, with the corpus package bound to /// a namespace that has a System segment: a bare System.* reference in a file in - /// it resolves into that namespace, which is what the runner's framework qualification exists for. + /// it resolves into that namespace, which is why every generator writes its framework references through CSharpNaming.FrameworkPrefix. public static TheoryData PackageSelections => new() { { "entity,db-context,filter-allowlist,callable,names", true }, @@ -176,7 +176,7 @@ private static void CompileSelection(string selection, bool includeNames, bool p } // The runner's post-pass: every file goes through it before it is written. - var files = generators.SelectMany(g => g.Generate(ctx)).Select(f => FrameworkQualifier.Apply(ctx.Config, f)).ToList(); + var files = generators.SelectMany(g => g.Generate(ctx)).ToList(); Assert.True(files.Count > 0, $"selection '{selection}' generated no files at all"); // FR-044 — every view-backed report of the corpus (twenty-five today) generates a keyless diff --git a/server/csharp/MetaObjects.Codegen.Tests/DbContextWriterHooksTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DbContextWriterHooksTests.cs new file mode 100644 index 000000000..a76abd879 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/DbContextWriterHooksTests.cs @@ -0,0 +1,231 @@ +// DbContextWriterHooksTests — the CsWriter overloads of DbContextGenerator's text hooks. +// +// Every text hook (OwnedTypeConfig, FieldTypeConfig, DbColumnTypeConfig, DefaultValueConfig, +// ReferenceConfig, TphSubtypeFieldConfig, EntityConfigTrailer, EmitCheckConfig, DbSetLine, +// ContextMemberLines, ContextPreambleLines, ContextTrailerLines) has an overload that takes the +// writer, so an override writes a nested block with Braced instead of building text with embedded +// newlines. Three properties: +// +// * an override that calls base writes exactly what the text hook would (byte-identical); +// * a block written through the writer lands at its place, indented by the writer; +// * what one writer overload writes is ONE model entry, never split across ConfigureModelNN, +// while a generator that overrides no writer overload keeps its entries (and splits) as before. + +using MetaObjects.Codegen.Generators; +using MetaObjects.Codegen.Writer; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class DbContextWriterHooksTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street", "@required": true, "@maxLength": 120 } }, + { "field.enum": { "name": "kind", "@values": ["HOME", "WORK"] } } + ]}}, + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Plain"] } }, + { "field.string": { "name": "note", "@maxLength": 80 } }, + { "field.string": { "name": "uid", "@dbColumnType": "uuid" } }, + { "field.boolean": { "name": "active", "@default": true } }, + { "field.decimal": { "name": "amount", "@precision": 10, "@scale": 2 } }, + { "field.enum": { "name": "statuses", "isArray": true, "@values": ["DRAFT", "LIVE"] } }, + { "field.object": { "name": "home", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { "name": "config", "@objectRef": "Address", "@storage": "jsonb" } }, + { "field.long": { "name": "parentId" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { "name": "refParent", "@fields": "parentId", "@references": "Auth" } } + ]}}, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity", "@required": true, "@default": 3 } } + ]}} + ]}} + """; + + private static MetaRoot Load() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "writer-hooks.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + private static GenContext Ctx(MetaRoot root) => new() + { + Entities = root.Objects(), Root = root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", Dialect = "postgres" }, + }; + + private static string Db(DbContextGenerator g, MetaRoot root) => + g.Generate(Ctx(root)).Single(f => f.Path == "AppDbContext.g.cs").Content; + + // Every writer overload overridden, each calling base. + private sealed class BaseCallingDb : DbContextGenerator + { + public BaseCallingDb(int chunk = 200) { ModelConfigChunkSize = chunk; } + protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx) => base.OwnedTypeConfig(w, owner, entity, field, ctx); + protected override void FieldTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField f, GenContext ctx) => base.FieldTypeConfig(w, owner, entity, f, ctx); + protected override void DbColumnTypeConfig(CsWriter w, string owner, MetaField f) => base.DbColumnTypeConfig(w, owner, f); + protected override void DefaultValueConfig(CsWriter w, MetaObject entity, MetaField f, GenContext ctx) => base.DefaultValueConfig(w, entity, f, ctx); + protected override void ReferenceConfig(CsWriter w, MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) => base.ReferenceConfig(w, entity, reference, ctx); + protected override void TphSubtypeFieldConfig(CsWriter w, MetaObject root, MetaObject subtype, GenContext ctx) => base.TphSubtypeFieldConfig(w, root, subtype, ctx); + protected override void EntityConfigTrailer(CsWriter w, MetaObject entity, GenContext ctx) => base.EntityConfigTrailer(w, entity, ctx); + protected override void EmitCheckConfig(CsWriter w, string owner, MetaObject entity, GenContext ctx) => base.EmitCheckConfig(w, owner, entity, ctx); + protected override void DbSetLine(CsWriter w, MetaObject entity, GenContext ctx) => base.DbSetLine(w, entity, ctx); + protected override void ContextMemberLines(CsWriter w, GenContext ctx) => base.ContextMemberLines(w, ctx); + protected override void ContextPreambleLines(CsWriter w, GenContext ctx) => base.ContextPreambleLines(w, ctx); + protected override void ContextTrailerLines(CsWriter w, GenContext ctx) => base.ContextTrailerLines(w, ctx); + } + + [Fact] + public void A_writer_overload_that_calls_base_writes_what_the_text_hook_would() + { + var root = Load(); + Assert.Equal(Db(new DbContextGenerator(), root), Db(new BaseCallingDb(), root)); + } + + // Finding 9: a nested OwnsOne block, written with Braced, not built as text. + private sealed class NestedOwnedDb : DbContextGenerator + { + protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx) + { + if (field.Name != "config") + { + base.OwnedTypeConfig(w, owner, entity, field, ctx); + return; + } + using (w.Braced($"modelBuilder.Entity<{owner}>().OwnsOne(x => x.Config, b =>", "});")) + { + w.Line("b.ToJson(\"config\");"); + using (w.Braced("if (Database.IsNpgsql())")) + w.Line("b.Property(x => x.Street).HasMaxLength(120);"); + } + } + } + + [Fact] + public void An_owned_type_block_written_through_the_writer_is_indented_at_its_place() + { + var src = Db(new NestedOwnedDb(), Load()); + Assert.Contains( + " modelBuilder.Entity().OwnsOne(x => x.Config, b =>\n" + + " {\n" + + " b.ToJson(\"config\");\n" + + " if (Database.IsNpgsql())\n" + + " {\n" + + " b.Property(x => x.Street).HasMaxLength(120);\n" + + " }\n" + + " });\n", src); + // The flattened value object keeps its default configuration. + Assert.Contains("OwnsOne(x => x.Home", src); + } + + [Fact] + public void An_owned_type_override_that_writes_nothing_leaves_the_field_unconfigured() + { + var src = Db(new SkipOwnedDb(), Load()); + Assert.DoesNotContain("OwnsOne(x => x.Config", src); + Assert.Contains("OwnsOne(x => x.Home", src); + } + + private sealed class SkipOwnedDb : DbContextGenerator + { + protected override void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx) + { + if (field.Name != "config") base.OwnedTypeConfig(w, owner, entity, field, ctx); + } + } + + // Finding 10: several statements from one hook, written as statements, not one string. + private sealed class TrailerBlockDb : DbContextGenerator + { + public TrailerBlockDb(int chunk) { ModelConfigChunkSize = chunk; } + protected override void EntityConfigTrailer(CsWriter w, MetaObject entity, GenContext ctx) + { + using (w.Braced("if (Database.IsNpgsql())")) + { + w.Line($"modelBuilder.Entity<{entity.Name}>().HasIndex(x => x.Id);"); + w.Line($"modelBuilder.Entity<{entity.Name}>().HasComment(\"t\");"); + } + } + protected override void ContextPreambleLines(CsWriter w, GenContext ctx) + { + w.Line("base.OnModelCreating(modelBuilder);"); + w.Line("OnModelCreatingFirst(modelBuilder);"); + } + protected override void DbSetLine(CsWriter w, MetaObject entity, GenContext ctx) + { + w.Line("[System.ComponentModel.Browsable(false)]"); + base.DbSetLine(w, entity, ctx); + } + } + + [Fact] + public void A_writer_entry_of_several_statements_is_written_whole() + { + var src = Db(new TrailerBlockDb(chunk: 200), Load()); + Assert.Contains( + " if (Database.IsNpgsql())\n" + + " {\n" + + " modelBuilder.Entity().HasIndex(x => x.Id);\n" + + " modelBuilder.Entity().HasComment(\"t\");\n" + + " }\n", src); + Assert.Contains( + " {\n base.OnModelCreating(modelBuilder);\n OnModelCreatingFirst(modelBuilder);\n", src); + Assert.Contains( + " [System.ComponentModel.Browsable(false)]\n public DbSet Auths { get; set; } = default!;\n", src); + } + + [Fact] + public void A_writer_entry_is_never_split_across_ConfigureModel_methods() + { + // A chunk of one entry: the trailer block is its own ConfigureModelNN, whole. + var src = Db(new TrailerBlockDb(chunk: 1), Load()); + var at = src.IndexOf("if (Database.IsNpgsql())", StringComparison.Ordinal); + Assert.True(at > 0); + var method = src.LastIndexOf("private void ConfigureModel", at, StringComparison.Ordinal); + var next = src.IndexOf("private void ConfigureModel", at, StringComparison.Ordinal); + var body = next < 0 ? src[method..] : src[method..next]; + Assert.Contains("HasIndex(x => x.Id);", body); + Assert.Contains("HasComment(\"t\");", body); + } + + [Fact] + public void Text_hook_entries_and_split_points_are_unchanged_while_no_writer_overload_is_overridden() + { + // One entry per chunk: each text-hook line is still its own ConfigureModelNN, so a project + // that overrides no writer overload gets the same split it always had. + var root = Load(); + var stock = new DbContextGenerator { ModelConfigChunkSize = 1 }; + var src = Db(stock, root); + var methods = src.Split("private void ConfigureModel").Length - 1; + var oneChunk = Db(new DbContextGenerator(), root); + var open = oneChunk.IndexOf("protected override void OnModelCreating", StringComparison.Ordinal); + var statements = oneChunk[open..].Split('\n').Count(l => l.StartsWith(" modelBuilder.", StringComparison.Ordinal)); + Assert.True(statements > 1); + // Every entry of the stock model here is a single statement line, so one method per statement. + Assert.Equal(statements, methods); + } + + private sealed class UsingFragmentDb : DbContextGenerator + { + protected override void ContextPreambleLines(CsWriter w, GenContext ctx) + { + w.Using("Fragment.Only.Ns"); + w.Line("var fragmentMarker = 1;"); + } + } + + [Fact] + public void A_writer_overload_that_calls_Using_puts_no_using_line_in_the_method_body() + { + var src = Db(new UsingFragmentDb(), Load()); + Assert.Contains("var fragmentMarker = 1;", src); + Assert.DoesNotContain("Fragment.Only.Ns", src); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs index adb88d422..39d96802f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DerivedNamespaceTests.cs @@ -180,7 +180,7 @@ public void A_multi_package_model_compiles() // asserted by Routes_reach_the_package_namespaces_of_the_types_they_name. var comp = CSharpCompilation.Create( "derived_ns_" + Guid.NewGuid().ToString("N"), - files.Where(f => !f.Path.EndsWith("Routes.g.cs", StringComparison.Ordinal)).Select(f => CSharpSyntaxTree.ParseText(MetaObjects.Codegen.FrameworkQualifier.Qualify(f.Content), new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), + files.Where(f => !f.Path.EndsWith("Routes.g.cs", StringComparison.Ordinal)).Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) diff --git a/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs index 4a4e30ebe..c79e05567 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Fr019SharedEnumCodegenTests.cs @@ -282,6 +282,28 @@ public void Single_namespace_fallback_applies_when_package_is_unmapped() Assert.Contains("public Acme.Fallback.ContactMethod? Preferred { get; set; }", customer.Content); } + [Fact] + public void Provided_enum_namespace_is_public_and_is_what_the_type_reference_uses() + { + var root = LoadMany(ExtEnumSrc, ExtConsumerSrc); + var shared = root.Objects().SelectMany(o => o.Fields()) + .Select(Fr019SharedEnum.SharedEnumForField).OfType().Single(); + var mapped = Ctx(root, providedNs: "Acme.Fallback", + packageNamespaces: new() { ["acme::ext::auth"] = "Acme.External.Auth" }).Config; + var fallback = Ctx(root, providedNs: "Acme.Fallback").Config; + + // The namespace alone, from the same resolver chain the type reference walks. + Assert.Equal("Acme.External.Auth", Fr019SharedEnum.ProvidedEnumNamespace(shared, mapped)); + Assert.Equal("Acme.Fallback", Fr019SharedEnum.ProvidedEnumNamespace(shared, fallback)); + Assert.Equal(Fr019SharedEnum.ProvidedEnumNamespace(shared, mapped) + ".ContactMethod", + Fr019SharedEnum.SharedEnumTypeReference(shared, mapped)); + + // And it refuses with the same error when nothing is configured. + var ex = Assert.Throws(() => Fr019SharedEnum.ProvidedEnumNamespace(shared, Ctx(root).Config)); + Assert.Contains("acme::ext::auth", ex.Message); + Assert.Contains("ProvidedEnumNamespace", ex.Message); + } + [Fact] public void Provided_enum_with_no_package_mapping_and_no_fallback_names_the_package() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/FrameworkQualifierTests.cs b/server/csharp/MetaObjects.Codegen.Tests/FrameworkQualifierTests.cs index 728cc9eb8..0788a122a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/FrameworkQualifierTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/FrameworkQualifierTests.cs @@ -83,3 +83,47 @@ public void A_raw_string_is_left_alone() public void An_empty_string_is_not_a_raw_string() => Assert.Equal("var s = \"\"; global::System.A.B();", Q("var s = \"\"; System.A.B();")); } + +// The check that replaced the runner's rewrite: generators qualify their own framework references, and a +// file that still writes a bare one a generated namespace shadows is named, with the fix. +public sealed class FrameworkShadowCheckTests +{ + private const string Shadow = "namespace Acme.App.System;\npublic class Clock { }\n"; + + [Fact] + public void Bare_references_are_found_in_code_only_with_their_line() + { + var refs = FrameworkQualifier.BareReferences( + "using System.Linq;\n// System.Foo\nvar s = \"System.Bar\";\nvar x = System.Math.Abs(1);\nglobal::Microsoft.A.B();\nMicrosoft.C.D();"); + Assert.Equal([(4, "System"), (6, "Microsoft")], refs); + } + + [Fact] + public void A_bare_reference_a_generated_namespace_shadows_is_named() + { + var w = Assert.Single(FrameworkQualifier.ShadowWarnings([ + ("routes", "acme/app/OrderRoutes.g.cs", "namespace Acme.App;\n\nvar x = 1;\nvar o = System.Math.Abs(x);\n"), + ("entity", "acme/app/system/Clock.g.cs", Shadow), + ])); + Assert.StartsWith("routes: acme/app/OrderRoutes.g.cs:4 writes a bare framework reference (System.…)", w); + Assert.Contains("CSharpNaming.Framework", w); + } + + [Fact] + public void A_qualified_reference_or_a_namespace_outside_the_shadow_is_not_named() + { + Assert.Empty(FrameworkQualifier.ShadowWarnings([ + ("routes", "acme/app/OrderRoutes.g.cs", "namespace Acme.App;\nvar o = global::System.Math.Abs(1);\n"), + ("routes", "other/Routes.g.cs", "namespace Other;\nvar o = System.Math.Abs(1);\n"), + ("entity", "acme/app/system/Clock.g.cs", Shadow), + ])); + } + + [Fact] + public void Nothing_is_named_when_no_generated_namespace_shadows_a_framework_root() + { + Assert.Empty(FrameworkQualifier.ShadowWarnings([ + ("routes", "acme/app/OrderRoutes.g.cs", "namespace Acme.App;\nvar o = System.Math.Abs(1);\n"), + ])); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs index c62f7d703..b03e836ce 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs @@ -43,40 +43,40 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) /// private static class MapJsonb { - private static readonly System.Text.Json.JsonSerializerOptions Options = new() + private static readonly global::System.Text.Json.JsonSerializerOptions Options = new() { - Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } + Converters = { new global::System.Text.Json.Serialization.JsonStringEnumConverter() } }; - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< - System.Collections.Generic.Dictionary, string> RequiredConverter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>(v, Options)!); + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + global::System.Collections.Generic.Dictionary, string> RequiredConverter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>(v, Options)!); /// Same conversion as RequiredConverter, over the NULLABLE dictionary a /// non-required map's property carries — keep the two bodies identical. EF Core's /// nullability-aware HasConversion checks the converter's model type against the /// property's own annotation, so one factory cannot serve both arms. - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< - System.Collections.Generic.Dictionary?, string> Converter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>(v, Options)!); + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + global::System.Collections.Generic.Dictionary?, string> Converter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>(v, Options)!); /// A whole value-object document (or collection of them) as one jsonb value, /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON). - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize(v, Options)!); + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize(v, Options)!); - internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( - (a, b) => System.Text.Json.JsonSerializer.Serialize(a, Options) == System.Text.Json.JsonSerializer.Serialize(b, Options), - v => System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), - v => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); + internal static global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( + (a, b) => global::System.Text.Json.JsonSerializer.Serialize(a, Options) == global::System.Text.Json.JsonSerializer.Serialize(b, Options), + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), + v => global::System.Text.Json.JsonSerializer.Deserialize(global::System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); - internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< - System.Collections.Generic.Dictionary?> Comparer() => new( + internal static global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< + global::System.Collections.Generic.Dictionary?> Comparer() => new( (a, b) => Eq(a, b), v => Hash(v), v => Snap(v)); /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key @@ -85,17 +85,17 @@ internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< /// comparer (no serialization at all); a value-object value falls through to a JSON /// compare, since the generated POCO is a class and compares by reference. private static bool Eq( - System.Collections.Generic.Dictionary? a, - System.Collections.Generic.Dictionary? b) + global::System.Collections.Generic.Dictionary? a, + global::System.Collections.Generic.Dictionary? b) { if (a is null || b is null) return ReferenceEquals(a, b); if (a.Count != b.Count) return false; foreach (var kv in a) { if (!b.TryGetValue(kv.Key, out var other)) return false; - if (System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; - if (System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) - != System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; + if (global::System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) + != global::System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; } return true; } @@ -103,7 +103,7 @@ private static bool Eq( /// Keys and count only — order-independent (XOR), allocation-free, and /// stable for a value-object value whose GetHashCode is reference-based. Equal /// dictionaries always hash equal, which is all EF requires. - private static int Hash(System.Collections.Generic.Dictionary? v) + private static int Hash(global::System.Collections.Generic.Dictionary? v) { if (v is null) return 0; var h = v.Count; @@ -114,14 +114,14 @@ private static int Hash(System.Collections.Generic.DictionaryThe change-tracking snapshot. A value-object value needs a DEEP copy or /// an in-place edit to a nested object mutates the snapshot too and goes undetected; /// an immutable scalar only needs the dictionary copied. - private static System.Collections.Generic.Dictionary? Snap( - System.Collections.Generic.Dictionary? v) => + private static global::System.Collections.Generic.Dictionary? Snap( + global::System.Collections.Generic.Dictionary? v) => v is null ? null : typeof(TValue).IsValueType || typeof(TValue) == typeof(string) - ? new System.Collections.Generic.Dictionary(v) - : System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>( - System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; + ? new global::System.Collections.Generic.Dictionary(v) + : global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>( + global::System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs index 330e2a7d8..667d3c54a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs @@ -15,30 +15,30 @@ namespace Acme.Shop; /// public static class CarFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { "plate", }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { - ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(), }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "kind", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs index 8eaf62ddb..307056bea 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs @@ -15,30 +15,30 @@ namespace Acme.Shop; /// public static class GizmoFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { "title", }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { - ["title"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["title"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { ["title"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { ["title"] = new("desc"), }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "title", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 03133e4e7..b8ad7e099 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -12,7 +12,7 @@ namespace Acme.Shop; public static class GizmoRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Title"] = new SortFieldRule("desc", "Title"), @@ -24,7 +24,7 @@ public static class GizmoRoutes }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. - private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + private static readonly global::System.Collections.Generic.HashSet KnownFields = new(global::System.StringComparer.Ordinal) { "createdAt", "dims", @@ -47,7 +47,7 @@ public static class GizmoRoutes /// public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { - SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -69,19 +69,19 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "PinHash" }); var totalQ = EfCoreFilterDispatch.Apply(db.Gizmos.AsNoTracking(), listQuery, GizmoFilterAllowlist.Rules); var total = await totalQ.CountAsync(); @@ -98,25 +98,25 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap app.MapPost(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - System.Text.Json.JsonDocument __body; - try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; - if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; var __issues = new ValidationIssues(); - var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase); + var __present = new global::System.Collections.Generic.HashSet(global::System.StringComparer.OrdinalIgnoreCase); foreach (var __p in __body.RootElement.EnumerateObject()) - if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name); + if (__p.Value.ValueKind != global::System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name); foreach (var __req in new[] { "title" }) if (!__present.Contains(__req)) __issues.AddRequired(__req); Gizmo? input = null; - try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Gizmo)); } + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(Gizmo)); } if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); // @formExclude / credential: not settable through the generated create; the value is ignored. input.PinHash = default!; @@ -125,11 +125,11 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap ValueObjectValidator.Collect(input.Dims, __issues, jsonOpts, "dims"); ValueObjectValidator.Collect(input.Extras, __issues, jsonOpts, "extras"); if (__issues.Any) return __issues.ToResult(); - input.CreatedAt = System.DateTimeOffset.UtcNow; - input.UpdatedAt = System.DateTimeOffset.UtcNow; + input.CreatedAt = global::System.DateTimeOffset.UtcNow; + input.UpdatedAt = global::System.DateTimeOffset.UtcNow; db.Gizmos.Add(input); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -140,69 +140,69 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap return (IResult)new CredentialOmittingResult(input, new string[] { "PinHash" }, status: 201, location: prefix + "/gizmos"); }); - async System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global::Acme.Generated.AppDbContext db) + async global::System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global::Acme.Generated.AppDbContext db) { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Gizmos.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); - System.Text.Json.JsonDocument body; - try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; - if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; // Deserialize each value with the app's CONFIGURED JSON options, not defaults — // a field.timestamp binds to DateTimeOffset via a custom converter registered on // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); - existing.UpdatedAt = System.DateTimeOffset.UtcNow; + existing.UpdatedAt = global::System.DateTimeOffset.UtcNow; var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); var __issues = new ValidationIssues(); foreach (var prop in body.RootElement.EnumerateObject()) { var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; if (__clr is "PinHash" or "TokenHash") continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "pinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "tokenHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "dims", System.StringComparison.OrdinalIgnoreCase) || __clr == "Dims") + if (string.Equals(prop.Name, "pinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "tokenHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "dims", global::System.StringComparison.OrdinalIgnoreCase) || __clr == "Dims") { - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { existing.Dims = null; continue; } global::Acme.Shop.Dims __vo0; - try { __vo0 = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), jsonOpts); } - catch (System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "dims"); continue; } + try { __vo0 = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), jsonOpts); } + catch (global::System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "dims"); continue; } if (!ValueObjectValidator.Collect(__vo0, __issues, jsonOpts, "dims")) continue; existing.Dims = __vo0; continue; } - if (string.Equals(prop.Name, "extras", System.StringComparison.OrdinalIgnoreCase) || __clr == "Extras") + if (string.Equals(prop.Name, "extras", global::System.StringComparison.OrdinalIgnoreCase) || __clr == "Extras") { - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { existing.Extras = null; continue; } - System.Collections.Generic.Dictionary? __map0; - try { __map0 = System.Text.Json.JsonSerializer.Deserialize>(prop.Value.GetRawText(), jsonOpts); } - catch (System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "extras"); continue; } + global::System.Collections.Generic.Dictionary? __map0; + try { __map0 = global::System.Text.Json.JsonSerializer.Deserialize>(prop.Value.GetRawText(), jsonOpts); } + catch (global::System.Text.Json.JsonException __e) { __issues.AddJson(__e, null, "extras"); continue; } if (!ValueObjectValidator.Collect(__map0, __issues, jsonOpts, "extras")) continue; existing.Extras = __map0; continue; } var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) ?? entry.Metadata.FindProperty(prop.Name) - ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); if (target.IsPrimaryKey()) continue; // PK is route-authoritative - if (string.Equals(target.Name, "CreatedAt", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned - if (string.Equals(target.Name, "UpdatedAt", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned - if (string.Equals(target.Name, "Stamp", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable - if (string.Equals(target.Name, "Serial", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (string.Equals(target.Name, "CreatedAt", global::System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "UpdatedAt", global::System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "Stamp", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (string.Equals(target.Name, "Serial", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { // FR-035 PATCH-2: explicit null clears a nullable column; on a // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). @@ -210,10 +210,10 @@ async System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global: entry.CurrentValues[target] = null; continue; } - var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; object? __val; - try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } // FR-036 A2 — validate the PRESENT, non-null value with the same per-field // DataAnnotations as create. This validates ONLY the present value (never the // whole row) so an ABSENT @required field is untouched, not a 400. @@ -222,7 +222,7 @@ async System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global: } if (__issues.Any) return __issues.ToResult(); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -242,7 +242,7 @@ async System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global: if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Gizmos.Remove(existing); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -273,7 +273,7 @@ private static IOrderedQueryable ApplySortGizmo(IQueryable q, stri /// Escape hatch: insert without @autoSet stamping (created-at/updated-at /// written verbatim from ) for import / restore / replication. - public static async System.Threading.Tasks.Task InsertPreserving(global::Acme.Generated.AppDbContext db, Gizmo input) + public static async global::System.Threading.Tasks.Task InsertPreserving(global::Acme.Generated.AppDbContext db, Gizmo input) { db.Gizmos.Add(input); await db.SaveChangesAsync(); @@ -291,12 +291,12 @@ private sealed class CredentialOmittingResult : IResult private readonly string? _location; public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } - public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + public async global::System.Threading.Tasks.Task ExecuteAsync(HttpContext http) { - var opts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var opts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names. SerializerKeys.StripBody(node, _value, _envelope, opts, _names); http.Response.StatusCode = _status; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs index 09c92829c..b871b0dc4 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs @@ -15,26 +15,26 @@ namespace Acme.Shop; /// public static class LineFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "label", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs index 3f9f7a910..f93e51b77 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -12,14 +12,14 @@ namespace Acme.Shop; public static class LineRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Label"] = new SortFieldRule(property: "Label"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. - private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + private static readonly global::System.Collections.Generic.HashSet KnownFields = new(global::System.StringComparer.Ordinal) { "id", "label", @@ -55,19 +55,19 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); var totalQ = EfCoreFilterDispatch.Apply(db.Lines.AsNoTracking(), listQuery, LineFilterAllowlist.Rules); var total = await totalQ.CountAsync(); @@ -84,26 +84,26 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app app.MapPost(prefix + "/lines", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - System.Text.Json.JsonDocument __body; - try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; - if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; var __issues = new ValidationIssues(); Line? input = null; - try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Line)); } + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(Line)); } if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); __issues.ValidateObject(input, jsonOpts); if (__issues.Any) return __issues.ToResult(); db.Lines.Add(input); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -114,22 +114,22 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app return Results.Created(prefix + "/lines", input); }); - async System.Threading.Tasks.Task UpdateLine(HttpContext http, global::Acme.Generated.AppDbContext db) + async global::System.Threading.Tasks.Task UpdateLine(HttpContext http, global::Acme.Generated.AppDbContext db) { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Lines.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); - System.Text.Json.JsonDocument body; - try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; - if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; // Deserialize each value with the app's CONFIGURED JSON options, not defaults — // a field.timestamp binds to DateTimeOffset via a custom converter registered on // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); @@ -139,11 +139,11 @@ async System.Threading.Tasks.Task UpdateLine(HttpContext http, global:: var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) ?? entry.Metadata.FindProperty(prop.Name) - ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); if (target.IsPrimaryKey()) continue; // PK is route-authoritative - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { // FR-035 PATCH-2: explicit null clears a nullable column; on a // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). @@ -151,10 +151,10 @@ async System.Threading.Tasks.Task UpdateLine(HttpContext http, global:: entry.CurrentValues[target] = null; continue; } - var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; object? __val; - try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } // FR-036 A2 — validate the PRESENT, non-null value with the same per-field // DataAnnotations as create. This validates ONLY the present value (never the // whole row) so an ABSENT @required field is untouched, not a 400. @@ -163,7 +163,7 @@ async System.Threading.Tasks.Task UpdateLine(HttpContext http, global:: } if (__issues.Any) return __issues.ToResult(); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -183,7 +183,7 @@ async System.Threading.Tasks.Task UpdateLine(HttpContext http, global:: if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Lines.Remove(existing); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs index 236a7a132..9cbb17ee0 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs @@ -15,34 +15,34 @@ namespace Acme.Shop; /// public static class LineTotalsFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { "label", "lines", }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { - ["label"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, - ["lines"] = new(System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, + ["label"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["lines"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { ["label"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), ["lines"] = new(FilterValueKind.Number, "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") { Integer = true }, }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { ["label"] = new(), ["lines"] = new(), }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "label", "lines", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs index 58c0d48e9..ba1280701 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -12,7 +12,7 @@ namespace Acme.Shop; public static class LineTotalsRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Label"] = new SortFieldRule(property: "Label"), ["Lines"] = new SortFieldRule(property: "Lines"), @@ -54,7 +54,7 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild if (limit > maxRows) return Results.BadRequest(new { error = "report_too_large", maxRows }); if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); q = q.Take((int)(limit ?? maxRows + 1L)); var rows = await q.ToListAsync(); @@ -62,7 +62,7 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild return Results.BadRequest(new { error = "report_too_large", maxRows }); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); var totalQ = EfCoreFilterDispatch.Apply(db.LineTotals.AsNoTracking(), listQuery, LineTotalsFilterAllowlist.Rules); var total = await totalQ.CountAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs index 9df130471..986b7d8de 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs @@ -48,7 +48,7 @@ public static ReportExportCell Cell(object? value) case Enum e: return new(e.ToString(), true); case Uri u: return new(u.OriginalString, true); case IPAddress ip: return new(ip.ToString(), false); - case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); + case IEnumerable: return new(global::System.Text.Json.JsonSerializer.Serialize(value), false); case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs index 5b2e42d06..32908e502 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs @@ -15,26 +15,26 @@ namespace Acme.Shop; /// public static class TagFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "name", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs index 49db8d4dd..d90d4446b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -12,14 +12,14 @@ namespace Acme.Shop; public static class TagRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Name"] = new SortFieldRule(property: "Name"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. - private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + private static readonly global::System.Collections.Generic.HashSet KnownFields = new(global::System.StringComparer.Ordinal) { "id", "name", @@ -55,19 +55,19 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); var totalQ = EfCoreFilterDispatch.Apply(db.Tags.AsNoTracking(), listQuery, TagFilterAllowlist.Rules); var total = await totalQ.CountAsync(); @@ -84,20 +84,20 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, app.MapPost(prefix + "/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - System.Text.Json.JsonDocument __body; - try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; - if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; var __issues = new ValidationIssues(); Tag? input = null; - try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(Tag)); } + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(Tag)); } if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. input.Id = default!; @@ -105,7 +105,7 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, if (__issues.Any) return __issues.ToResult(); db.Tags.Add(input); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -116,22 +116,22 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, return Results.Created(prefix + "/tags", input); }); - async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::Acme.Generated.AppDbContext db) + async global::System.Threading.Tasks.Task UpdateTag(HttpContext http, global::Acme.Generated.AppDbContext db) { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Tags.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); - System.Text.Json.JsonDocument body; - try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; - if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; // Deserialize each value with the app's CONFIGURED JSON options, not defaults — // a field.timestamp binds to DateTimeOffset via a custom converter registered on // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); @@ -141,11 +141,11 @@ async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::A var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) ?? entry.Metadata.FindProperty(prop.Name) - ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); if (target.IsPrimaryKey()) continue; // PK is route-authoritative - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { // FR-035 PATCH-2: explicit null clears a nullable column; on a // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). @@ -153,10 +153,10 @@ async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::A entry.CurrentValues[target] = null; continue; } - var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; object? __val; - try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } // FR-036 A2 — validate the PRESENT, non-null value with the same per-field // DataAnnotations as create. This validates ONLY the present value (never the // whole row) so an ABSENT @required field is untouched, not a 400. @@ -165,7 +165,7 @@ async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::A } if (__issues.Any) return __issues.ToResult(); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -185,7 +185,7 @@ async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::A if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Tags.Remove(existing); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs index 5f5e0fd18..f4ddcdcac 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs @@ -15,30 +15,30 @@ namespace Acme.Shop; /// public static class VanFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { "plate", }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { - ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(), }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "kind", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs index 3c75c8572..1215969f1 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs @@ -15,30 +15,30 @@ namespace Acme.Shop; /// public static class VehicleFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { "plate", }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { - ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { ["plate"] = new(), }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "id", "kind", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 70779c13a..928be6f96 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -12,14 +12,14 @@ namespace Acme.Shop; public static class VehicleRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Plate"] = new SortFieldRule(property: "Plate"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. - private static readonly System.Collections.Generic.HashSet KnownFields = new(System.StringComparer.Ordinal) + private static readonly global::System.Collections.Generic.HashSet KnownFields = new(global::System.StringComparer.Ordinal) { "id", "kind", @@ -30,7 +30,7 @@ public static class VehicleRoutes "vinHash", }; - private static readonly System.Collections.Generic.Dictionary CarSortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary CarSortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Plate"] = new SortFieldRule(property: "Plate"), @@ -38,7 +38,7 @@ public static class VehicleRoutes ["RegNo"] = new SortFieldRule(property: "RegNo"), }; - private static readonly System.Collections.Generic.Dictionary VanSortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary VanSortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["Id"] = new SortFieldRule(property: "Id"), ["Plate"] = new SortFieldRule(property: "Plate"), @@ -54,7 +54,7 @@ public static class VehicleRoutes /// public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { - SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -74,16 +74,16 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder } // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.Apply(db.Vehicles.AsNoTracking(), listQuery, VehicleFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); @@ -104,7 +104,7 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder .Where(j => EF.Property(j, "VehicleId").Equals(id)) .Select(j => EF.Property(j, "TagId")) .ToListAsync()).ToHashSet(); - if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); var rows = await db.Tags.AsNoTracking() .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) .ToListAsync(); @@ -128,16 +128,16 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder } // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.Apply(db.Vehicles.OfType().AsNoTracking(), listQuery, global::Acme.Shop.CarFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); @@ -153,32 +153,32 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app.MapPost(prefix + "/vehicles/car", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - System.Text.Json.JsonDocument __body; - try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; - if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; var __issues = new ValidationIssues(); global::Acme.Shop.Car? input = null; - try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Car)); } + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Car)); } if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. input.Id = default!; input.Kind = default!; - input.Tags = new System.Collections.Generic.List(); + input.Tags = new global::System.Collections.Generic.List(); // @formExclude / credential: not settable through the generated create; the value is ignored. input.VinHash = default!; __issues.ValidateObject(input, jsonOpts); if (__issues.Any) return __issues.ToResult(); db.Vehicles.Add(input); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -189,21 +189,21 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); }); - async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::Acme.Generated.AppDbContext db) + async global::System.Threading.Tasks.Task UpdateCar(HttpContext http, global::Acme.Generated.AppDbContext db) { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); - System.Text.Json.JsonDocument body; - try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; - if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; // Configured JSON options (not defaults) so a custom converter — e.g. the // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); @@ -212,16 +212,16 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A { var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; if (__clr is "VinHash") continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "vinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) ?? entry.Metadata.FindProperty(prop.Name) - ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); if (target.IsPrimaryKey()) continue; // PK is route-authoritative - if (string.Equals(target.Name, "Kind", System.StringComparison.Ordinal)) continue; // discriminator is immutable - if (string.Equals(target.Name, "RegNo", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (string.Equals(target.Name, "Kind", global::System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (string.Equals(target.Name, "RegNo", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { // FR-035 PATCH-2: explicit null clears a nullable column; on a // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). @@ -229,10 +229,10 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A entry.CurrentValues[target] = null; continue; } - var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; object? __val; - try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } // FR-036 A2 — validate the PRESENT, non-null value with the same per-field // DataAnnotations as create. This validates ONLY the present value (never the // whole row) so an ABSENT @required field is untouched, not a 400. @@ -241,7 +241,7 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A } if (__issues.Any) return __issues.ToResult(); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -261,7 +261,7 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Vehicles.Remove(existing); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -276,12 +276,12 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) - return Results.Ok(new System.Collections.Generic.List()); + return Results.Ok(new global::System.Collections.Generic.List()); var relatedIds = (await db.VehicleTags.AsNoTracking() .Where(j => EF.Property(j, "VehicleId").Equals(id)) .Select(j => EF.Property(j, "TagId")) .ToListAsync()).ToHashSet(); - if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); var rows = await db.Tags.AsNoTracking() .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) .ToListAsync(); @@ -305,16 +305,16 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A } // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.Apply(db.Vehicles.OfType().AsNoTracking(), listQuery, global::Acme.Shop.VanFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); @@ -330,32 +330,32 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A app.MapPost(prefix + "/vehicles/van", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - System.Text.Json.JsonDocument __body; - try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; - if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown; var __issues = new ValidationIssues(); global::Acme.Shop.Van? input = null; - try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Van)); } + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(global::Acme.Shop.Van)); } if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable(); // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. input.Id = default!; input.Kind = default!; - input.Tags = new System.Collections.Generic.List(); + input.Tags = new global::System.Collections.Generic.List(); // @formExclude / credential: not settable through the generated create; the value is ignored. input.VinHash = default!; __issues.ValidateObject(input, jsonOpts); if (__issues.Any) return __issues.ToResult(); db.Vehicles.Add(input); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -366,21 +366,21 @@ async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::A return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); }); - async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::Acme.Generated.AppDbContext db) + async global::System.Threading.Tasks.Task UpdateVan(HttpContext http, global::Acme.Generated.AppDbContext db) { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); - System.Text.Json.JsonDocument body; - try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; - if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); + if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; // Configured JSON options (not defaults) so a custom converter — e.g. the // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. - var jsonOpts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); @@ -389,15 +389,15 @@ async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::A { var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; if (__clr is "VinHash") continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "vinHash", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) ?? entry.Metadata.FindProperty(prop.Name) - ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase)); + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts); if (target.IsPrimaryKey()) continue; // PK is route-authoritative - if (string.Equals(target.Name, "Kind", System.StringComparison.Ordinal)) continue; // discriminator is immutable - if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null) + if (string.Equals(target.Name, "Kind", global::System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { // FR-035 PATCH-2: explicit null clears a nullable column; on a // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). @@ -405,10 +405,10 @@ async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::A entry.CurrentValues[target] = null; continue; } - var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; object? __val; - try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } - catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } + try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); } + catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; } // FR-036 A2 — validate the PRESENT, non-null value with the same per-field // DataAnnotations as create. This validates ONLY the present value (never the // whole row) so an ABSENT @required field is untouched, not a 400. @@ -417,7 +417,7 @@ async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::A } if (__issues.Any) return __issues.ToResult(); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -437,7 +437,7 @@ async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::A if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Vehicles.Remove(existing); try { await db.SaveChangesAsync(); } - catch (System.Exception __saveError) + catch (global::System.Exception __saveError) { if (ConstraintErrors.Classify(__saveError) is { } __constraint) return Results.Json( @@ -452,12 +452,12 @@ async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::A { if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) - return Results.Ok(new System.Collections.Generic.List()); + return Results.Ok(new global::System.Collections.Generic.List()); var relatedIds = (await db.VehicleTags.AsNoTracking() .Where(j => EF.Property(j, "VehicleId").Equals(id)) .Select(j => EF.Property(j, "TagId")) .ToListAsync()).ToHashSet(); - if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List()); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); var rows = await db.Tags.AsNoTracking() .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) .ToListAsync(); @@ -488,12 +488,12 @@ private sealed class CredentialOmittingResult : IResult private readonly string? _location; public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } - public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + public async global::System.Threading.Tasks.Task ExecuteAsync(HttpContext http) { - var opts = ((Microsoft.Extensions.Options.IOptions) - http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) + var opts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; - var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names. SerializerKeys.StripBody(node, _value, _envelope, opts, _names); http.Response.StatusCode = _status; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs index 389504e98..5e31ff37f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs @@ -15,26 +15,26 @@ namespace Acme.Shop; /// public static class VehicleTagFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "vehicleId", "tagId", diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs index 45008205b..e9ff4bcc9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -12,7 +12,7 @@ namespace Acme.Shop; public static class VehicleTagRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["VehicleId"] = new SortFieldRule(property: "VehicleId"), ["TagId"] = new SortFieldRule(property: "TagId"), @@ -48,19 +48,19 @@ public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuild // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); var totalQ = EfCoreFilterDispatch.Apply(db.VehicleTags.AsNoTracking(), listQuery, VehicleTagFilterAllowlist.Rules); var total = await totalQ.CountAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs index b64b1c4e6..b27e1088c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs @@ -15,26 +15,26 @@ namespace Acme.Shop; /// public static class WidgetSummaryFilterAllowlist { - public static readonly HashSet Fields = new(System.StringComparer.Ordinal) + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) { }; - public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) { }; /// Each filterable field's rule: its operators, how its values are typed and checked. - public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Rules = new Dictionary(global::System.StringComparer.Ordinal) { }; /// The sortable fields, each with its declared @sortableDefaultOrder. - public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + public static readonly IReadOnlyDictionary Sort = new Dictionary(global::System.StringComparer.Ordinal) { }; /// Every field of the entity, filterable or not, except a credential. - public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + public static readonly IReadOnlySet FieldNames = new HashSet(global::System.StringComparer.Ordinal) { "widgetId", }; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs index 62236b461..a001b6e79 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -12,7 +12,7 @@ namespace Acme.Shop; public static class WidgetSummaryRoutes { - private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly global::System.Collections.Generic.Dictionary SortRules = new(global::System.StringComparer.OrdinalIgnoreCase) { ["WidgetId"] = new SortFieldRule(property: "WidgetId"), }; @@ -47,19 +47,19 @@ public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBu // Pagination: ?offset=N first (skip), then ?limit=N (take). if (listQuery.Offset is { } __offset && __offset > 0) - q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); + q = q.Skip((int)global::System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(__limit, int.MaxValue); + __take = (int)global::System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); // withCount=1 → { rows, total } envelope; otherwise bare row array. - var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); var totalQ = EfCoreFilterDispatch.Apply(db.WidgetSummaries.AsNoTracking(), listQuery, WidgetSummaryFilterAllowlist.Rules); var total = await totalQ.CountAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs index 804c73d1e..528521cce 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs @@ -137,7 +137,7 @@ public void Two_entities_with_one_name_in_two_packages_build_together_with_route Assert.Contains("crm/billing/InvoiceQueries.g.cs", files.Select(f => f.Path)); // The runner's post-pass is part of the output the adopter builds. - var sources = files.Select(f => (f.Path, Content: FrameworkQualifier.Apply(Ctx(root, true).Config, f).Content)).ToList(); + var sources = files.Select(f => (f.Path, f.Content)).ToList(); var errors = CompileErrors(sources); Assert.True(errors.Count == 0, string.Join("\n", errors.Take(15))); } @@ -208,7 +208,7 @@ public void A_TPH_subtype_in_another_package_than_its_base_compiles_with_routes_ { "field.int": { "name": "quantity", "@required": true, "@default": 3 } } ] } } ] } } """); var ctx = Ctx(root, package: true); - var files = Run(ctx).Select(f => FrameworkQualifier.Apply(ctx.Config, f)).ToList(); + var files = Run(ctx).ToList(); Assert.Contains("crm/sub/BridgeAuth.g.cs", files.Select(f => f.Path)); var errors = CompileErrors(files.Select(f => (f.Path, f.Content))); Assert.True(errors.Count == 0, string.Join("\n", errors.Take(15))); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs index 26b174bb7..9a43f7cf8 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs @@ -188,7 +188,7 @@ internal static List CompileErrors(IEnumerable files) paths.Add(typeof(MetaObjects.Render.Extract.ExtractSchema).Assembly.Location); paths.Add(typeof(MetaObject).Assembly.Location); var comp = CSharpCompilation.Create("pkgns_" + Guid.NewGuid().ToString("N"), - sources.Select(f => CSharpSyntaxTree.ParseText(MetaObjects.Codegen.FrameworkQualifier.Qualify(f.Content), new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), + sources.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)), paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); return comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index a264feb41..bb7dea308 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -282,7 +282,7 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ Assert.Contains("if (__clr is \"XPinHash\" or \"XTokenHash\") continue;", gizmo); Assert.Contains("SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts)", gizmo); foreach (var k in new[] { "pinHash", "XPinHash", "tokenHash", "XTokenHash" }) - Assert.Contains($"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential", gizmo); + Assert.Contains($"string.Equals(prop.Name, \"{k}\", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential", gizmo); // Create resets the resolved property, so the two writes agree. Assert.Contains("input.XPinHash = default!;", gizmo); Assert.Contains("input.XTokenHash = default!;", gizmo); @@ -295,8 +295,8 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ public void A_renamed_value_object_and_map_patch_arm_matches_both_spellings() { var gizmo = One(AllSites(AllSitesCtx()), "GizmoRoutes.g.cs"); - Assert.Contains("string.Equals(prop.Name, \"dims\", System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XDims\", System.StringComparison.OrdinalIgnoreCase)", gizmo); - Assert.Contains("string.Equals(prop.Name, \"extras\", System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XExtras\", System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("string.Equals(prop.Name, \"dims\", global::System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XDims\", global::System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("string.Equals(prop.Name, \"extras\", global::System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XExtras\", global::System.StringComparison.OrdinalIgnoreCase)", gizmo); Assert.Contains("existing.XDims =", gizmo); Assert.Contains("existing.XExtras =", gizmo); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/UnemittedObjectFieldsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/UnemittedObjectFieldsTests.cs new file mode 100644 index 000000000..761bd0113 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/UnemittedObjectFieldsTests.cs @@ -0,0 +1,107 @@ +// The object-typed fields the entity generator leaves off a view-mapped class are reported ONCE, by +// `dotnet meta verify`, with the fix; `gen` says nothing about them, so a clean regen prints nothing. + +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class UnemittedObjectFieldsTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street", "@maxLength": 120 } } + ]}}, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "jsonb" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } } + ]}}, + { "object.projection": { "name": "OrderSummary", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_order_summary" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.object": { "name": "shipTo", "extends": "Order.shipTo" } }, + { "identity.primary": { "name": "pk", "extends": "Order.pk" } } + ]}}, + { "object.entity": { "name": "Invoice", "children": [ + { "source.rdb": { "@role": "primary", "@kind": "table", "@table": "invoices" } }, + { "source.rdb": { "@role": "replica", "@kind": "view", "@view": "v_invoice" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "billTo", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { "name": "payTo", "@objectRef": "Address", "@storage": "jsonb" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } } + ]}} + ]}} + """; + + private static MetaRoot Load() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "unemitted.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + [Fact] + public void Gen_prints_nothing_for_an_object_field_on_a_projection() + { + var root = Load(); + var warnings = new List(); + var files = new EntityGenerator().Generate(new GenContext + { + Entities = root.Objects(), Root = root, Warn = warnings.Add, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, + }).ToList(); + Assert.Empty(warnings); + // The field is still left off the view class, as before. + var summary = Assert.Single(files, f => Path.GetFileName(f.Path) == "OrderSummary.g.cs"); + Assert.DoesNotContain("ShipTo", summary.Content); + } + + [Fact] + public void Verify_reports_each_unemitted_field_once_with_its_fix() + { + var lines = EntityGenerator.UnemittedObjectFields(Load(), [new EntityGenerator()]); + Assert.Equal(2, lines.Count); + Assert.Contains("\"Invoice.billTo\"", lines[0]); + Assert.Contains("InvoiceView", lines[0]); + Assert.Contains("@storage: jsonb", lines[0]); + Assert.Contains("\"OrderSummary.shipTo\"", lines[1]); + Assert.Contains("Remove the field from the projection", lines[1]); + // A jsonb value object on a write-through read model IS emitted: not reported. + Assert.DoesNotContain(lines, l => l.Contains("payTo")); + } + + [Fact] + public void Verify_says_nothing_when_no_entity_generator_runs() + { + Assert.Empty(EntityGenerator.UnemittedObjectFields(Load(), [new DbContextGenerator()])); + } + + [Fact] + public void Verify_reports_through_an_entity_generator_wrapped_by_WithHandEdits() + { + var lines = EntityGenerator.UnemittedObjectFields(Load(), [new EntityGenerator().WithHandEdits(HandEdits.Overwrite).Unwrap()]); + Assert.Equal(2, lines.Count); + } + + [Fact] + public void Verify_skips_an_object_the_entity_generators_include_excludes() + { + var lines = EntityGenerator.UnemittedObjectFields(Load(), + [new EntityGenerator { Include = o => o.Name != "OrderSummary" }.WithHandEdits(HandEdits.Overwrite).Unwrap()]); + var line = Assert.Single(lines); + Assert.Contains("\"Invoice.billTo\"", line); + } + + [Fact] + public void Verify_reports_an_object_when_any_entity_generator_accepts_it() + { + var lines = EntityGenerator.UnemittedObjectFields(Load(), + [new EntityGenerator { Include = o => o.Name == "Invoice" }, new EntityGenerator { Include = o => o.Name == "OrderSummary" }]); + Assert.Equal(2, lines.Count); + } +} diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 2c5d465ff..3adef6c8f 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -289,6 +289,21 @@ public static bool IsLenientNet(MetaField field) => public static string? DbColumnTypeClrOverride(MetaField field) => field.DbColumnType == DbConstants.DB_COLUMN_TYPE_JSONB ? JsonbClrType : null; + /// + /// A framework name (System.…, Microsoft.…) as generated code spells it: global::-qualified + /// when package namespaces are on, as written otherwise. With package namespaces a generated file sits in a + /// namespace derived from a metadata package, so a package segment can shadow a framework namespace + /// (acme::app::system derives Acme.App.System, and a bare System.Text.Json inside it + /// resolves there: CS0234). Every generator, and every owned copy of one, spells a framework reference + /// through this (or ), so the output is right as emitted; nothing rewrites it. + /// A using directive needs neither: it resolves from the global namespace. + /// + public static string Framework(GenConfig config, string name) => FrameworkPrefix(config) + name; + + /// What puts before a framework name: "global::" when package + /// namespaces are on, else "". For a site that spells several framework names in one string. + public static string FrameworkPrefix(GenConfig config) => config.PackageNamespacesFromMetadata ? "global::" : ""; + /// True when any of 's own fields is a jsonb open-bag /// (so the generated file needs using System.Text.Json; for the JsonDocument type). public static bool RequiresSystemTextJson(MetaObject obj) => diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 34d146a70..ca89d5f88 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -354,7 +354,7 @@ public static string LegacyTemplateSpec(string command, string what) => return File.Exists(Path.Combine(projectRoot, TemplateSpecFileName)) ? TemplateSpecFileName : null; } - private static IGenerator Unwrapped(IGenerator g) => g is HandEditsGenerator h ? h.Inner : g; + private static IGenerator Unwrapped(IGenerator g) => g.Unwrap(); /// Read every declared template spec once, so a missing or malformed file is a clean /// error before anything is written. null when they all read. @@ -1097,6 +1097,10 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar // its project may not reference (1.3.0 moved it out of MetaObjects.Codegen). foreach (var w in HelperRuntimeReference.ForRun(config, suite, projectRoot)) Console.Error.WriteLine($" warning: {w}"); + // Advisory: object-typed fields the entity generator leaves off a view-mapped class. Said here, + // once per verify, rather than on every gen. + foreach (var w in Generators.EntityGenerator.UnemittedObjectFields(load.Root, suite.Select(Unwrapped))) + Console.Error.WriteLine($" warning: {w}"); // ADR-0064: locally, an unchanged key and output that still hashes to what gen recorded answer // "no drift" without rendering. CI and --full always render. if (a.Entities is null && suite.All(g => g.Cacheable) && GenFingerprint.MayAnswerNoDrift( diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index 7d7cd44c1..af1d29428 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -135,6 +135,8 @@ captureKeys is { } ck // Written files that import the packaged helper runtime: their projects must reference it. var helperImports = new List<(string Path, string Shown)>(); var formerImports = new List(); + // With package namespaces on: every emitted file, for the framework-shadowing check after the run. + var csFiles = new List<(string Generator, string Path, string Content)>(); var refused = new List(); var adopted = new List(); var overwritePaths = new HashSet(StringComparer.Ordinal); @@ -170,7 +172,8 @@ captureKeys is { } ck var shown = generator.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : ""; foreach (var generated in Emit(generator, ctx, selection)) { - var file = FrameworkQualifier.Apply(config, generated); + var file = generated; + if (config.PackageNamespacesFromMetadata) csFiles.Add((generator.Name, file.Path, file.Content)); var full = Path.GetFullPath(Path.Combine(genRoot, file.Path)); if (!emitted.TryAdd(full, generator.Name)) throw new InvalidOperationException( @@ -250,6 +253,9 @@ captureKeys is { } ck // 1.3.0 moved the helper runtime into its own package; say so when the app would not compile. warnings.AddRange(HelperRuntimeReference.WarningsForImporting(helperImports)); + // Generators qualify framework references as they write them; a file that still writes a bare one + // a generated namespace shadows (an owned generator from before the prefix) is named, never rewritten. + warnings.AddRange(FrameworkQualifier.ShadowWarnings(csFiles)); if (HelperRuntimeReference.FormerImportWarning(formerImports) is { } former) warnings.Add(former); if (sweeps && config.GenStateDir is { } genState && config.ProjectRoot is { } project) diff --git a/server/csharp/MetaObjects.Codegen/FrameworkQualifier.cs b/server/csharp/MetaObjects.Codegen/FrameworkQualifier.cs index b333a4114..714a9261d 100644 --- a/server/csharp/MetaObjects.Codegen/FrameworkQualifier.cs +++ b/server/csharp/MetaObjects.Codegen/FrameworkQualifier.cs @@ -1,29 +1,85 @@ // With package namespaces on, a generated file sits in a namespace derived from a metadata package, // so a package segment can shadow a framework namespace (`acme::app::system` derives `Acme.App.System`, -// and a bare `System.Text.Json` inside it resolves into that namespace: CS0234). The runner therefore -// spells every framework reference in a generated C# file `global::`-qualified. +// and a bare `System.Text.Json` inside `Acme.App` resolves into that namespace: CS0234). Every generator +// therefore spells a framework reference through CSharpNaming.Framework / FrameworkPrefix, so its output +// is right as written (ADR-0063: the writer owns the text; nothing rewrites it afterwards). // -// Only code is touched. The file is read with a small C# lexer, so line and block comments, regular, -// verbatim, interpolated and raw string literals and char literals are copied through unchanged; the -// holes of a regular or verbatim interpolated string are code and are qualified. A using, global using, -// namespace or preprocessor line is left alone. +// This is the check that stays behind: the runner names a file that still writes a BARE framework +// reference where a generated namespace actually shadows it, which is an owned generator written before +// the prefix, or a reference spelled by hand. It finds the references with a small C# lexer, so line and +// block comments, regular, verbatim, interpolated and raw string literals and char literals are not +// code; the holes of a regular or verbatim interpolated string are. A using, global using, namespace +// or preprocessor line is not a reference: it resolves from the global namespace. using System.Text; +using System.Text.RegularExpressions; namespace MetaObjects.Codegen; -/// Qualifies System. / Microsoft. references in generated C# with global::. +/// Finds bare System. / Microsoft. references in generated C#, and the ones a +/// generated namespace shadows. public static class FrameworkQualifier { - /// with its framework references qualified, when - /// has package namespaces on and the file is C# source; else unchanged. - public static EmittedFile Apply(GenConfig config, EmittedFile file) + private static readonly Regex NamespaceDecl = new(@"^[ \t]*namespace[ \t]+([A-Za-z_][\w.]*)", RegexOptions.Multiline | RegexOptions.CultureInvariant); + + /// + /// One warning per generated C# file that writes a bare framework reference a generated namespace + /// shadows: a namespace of the run with a System or Microsoft segment whose parent + /// encloses the file's namespace. Nothing when no namespace of the run has such a segment, so a + /// bare reference that still compiles is never reported. + /// + public static IReadOnlyList ShadowWarnings(IEnumerable<(string Generator, string Path, string Content)> files) + { + var cs = files.Where(f => f.Path.EndsWith(".cs", StringComparison.Ordinal)).ToList(); + // Each shadowing namespace's parent, by the framework root it shadows. + var shadows = new List<(string Parent, string Root)>(); + foreach (var ns in cs.SelectMany(f => NamespaceDecl.Matches(f.Content).Select(m => m.Groups[1].Value)).Distinct(StringComparer.Ordinal)) + { + var segs = ns.Split('.'); + for (var k = 1; k < segs.Length; k++) + if (segs[k] is "System" or "Microsoft") + shadows.Add((string.Join('.', segs[..k]), segs[k])); + } + if (shadows.Count == 0) return []; + var warnings = new List(); + foreach (var f in cs) + { + var spaces = NamespaceDecl.Matches(f.Content).Select(m => m.Groups[1].Value).ToList(); + var roots = shadows + .Where(sh => spaces.Any(ns => ns == sh.Parent || ns.StartsWith(sh.Parent + ".", StringComparison.Ordinal))) + .Select(sh => sh.Root).ToHashSet(StringComparer.Ordinal); + if (roots.Count == 0) continue; + var bare = BareReferences(f.Content).Where(r => roots.Contains(r.Root)).ToList(); + if (bare.Count == 0) continue; + var first = bare[0]; + warnings.Add( + $"{f.Generator}: {f.Path}:{first.Line} writes a bare framework reference ({first.Root}.…) " + + $"that a generated namespace shadows{(bare.Count > 1 ? $" ({bare.Count} in the file)" : "")}; " + + "it will not compile (CS0234). Spell it through CSharpNaming.Framework(config, name) or the " + + "generator's Fx prefix, or write global::."); + } + return warnings; + } + + /// Each bare framework reference in code in : its 1-based line and + /// its root (System or Microsoft). + public static IReadOnlyList<(int Line, string Root)> BareReferences(string src) { - if (!config.PackageNamespacesFromMetadata || !file.Path.EndsWith(".cs", StringComparison.Ordinal)) return file; - return file with { Content = Qualify(file.Content) }; + var q = Qualify(src); + var hits = new List<(int, string)>(); + int i = 0, k = 0, line = 1; + while (i < src.Length) + { + if (k < q.Length && q[k] == src[i]) { if (src[i] == '\n') line++; i++; k++; continue; } + // Qualify only ever inserts "global::" before a reference. + hits.Add((line, src[i] == 'S' ? "System" : "Microsoft")); + k += "global::".Length; + } + return hits; } - /// The lexer behind , over a whole C# source text. + /// with every bare framework reference in code global::-qualified: + /// the lexer reads with. public static string Qualify(string src) { var sb = new StringBuilder(src.Length + 256); diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 7c7892139..8b5aed22b 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -696,7 +696,11 @@ public static class GeneratorExtensions /// The same entry with its setting replaced: /// new EntityGenerator().WithHandEdits(HandEdits.Overwrite). public static IGenerator WithHandEdits(this IGenerator generator, HandEdits handEdits) => - new HandEditsGenerator(generator is HandEditsGenerator h ? h.Inner : generator, handEdits); + new HandEditsGenerator(generator.Unwrap(), handEdits); + + /// The entry without its WithHandEdits wrapper; the entry itself when it has none. + public static IGenerator Unwrap(this IGenerator generator) => + generator is HandEditsGenerator h ? h.Inner : generator; } /// An entry with its handEdits setting; everything else is the wrapped entry's. diff --git a/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs b/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs index 805a24b17..4b3f38b2f 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs @@ -77,7 +77,8 @@ public static bool IsDecimalWireField(MetaField field) => // closed type the property has (decimal, decimal?, IList). Under the default // `wire.decimals: native` (ADR-0019 Amendment 2) it writes what System.Text.Json writes, a // JSON number, and keeps only the input rules; `string` writes the canonical string. - public static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, bool nullable, WireFormat wire) + // `fx` is the run's framework prefix (CSharpNaming.FrameworkPrefix). + public static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, bool nullable, WireFormat wire, string fx = "") { if (!IsDecimalWireField(field)) return; if (wire.Decimals == DecimalWireForm.Native) @@ -95,7 +96,7 @@ public static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, b } var converter = field.ResolvedIsArray() ? "DecimalListJsonConverter" : nullable ? "NullableDecimalJsonConverter" : "DecimalJsonConverter"; - w.Line($"[System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); + w.Line($"[{fx}System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); } // String length + pattern DataAnnotations for a string scalar, combining the field diff --git a/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs index 94d216c66..7a9c68d81 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs @@ -220,7 +220,7 @@ protected virtual void WriteMember(CsWriter w, MetaObject entity, MetaField fiel ContractMembers.WriteNumericValidatorAttributes(w, field); if (mustSend && !CSharpNaming.IsValueType(ElementType(field))) w.Line("[Required]"); } - ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !mustSend, wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !mustSend, wire, CSharpNaming.FrameworkPrefix(ctx.Config)); ContractMembers.WriteDurationConverterAttribute(w, field, wire); ContractMembers.WriteNetConverterAttribute(w, field); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index c92cf943d..e46c0f145 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -95,10 +95,70 @@ public static bool AppliesTo(MetaObject obj, MetaRoot root) => /// (a different using order, say); every method of the writer is public or protected. protected virtual CsWriter NewWriter() => new(); + // ── Writer seams (CsWriter overloads of the text hooks) ───────────────────────────────── + // + // Every text hook below has an overload that takes a CsWriter as its first parameter. Its + // default writes what the text hook returns, so an override of either one is honoured, and + // calling base from a writer overload writes the default lines first. What a writer overload + // writes is placed through the writer's own Text: its margin is removed and it is indented to + // its place, so an override writes at the margin and uses Braced/Open for a nested block. + // + // A writer overload's output is ONE entry. In OnModelCreating that means one unit that is never + // split across ConfigureModelNN methods, so a guard and what it guards, or an OwnsOne block and + // its lambda, stay together. While a writer overload is NOT overridden, the generator asks the + // text hook directly, so the entries (and where a large model splits) are exactly what they were. + // Only the fragment's body is used: a using or header a fragment writer collects is not carried + // over (it would land inside a method). A using belongs in ContextUsings. + + private readonly Dictionary _writerOverrides = new(StringComparer.Ordinal); + + // Whether this generator's runtime type overrides the CsWriter overload of hook `name`. + private bool OverridesWriterHook(string name) + { + if (_writerOverrides.TryGetValue(name, out var known)) return known; + const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance + | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; + static bool WriterOverload(System.Reflection.MethodInfo m, string name) => + m.Name == name && m.GetParameters() is [{ ParameterType: var first }, ..] && first == typeof(CsWriter); + var declared = typeof(DbContextGenerator).GetMethods(flags).Single(m => m.DeclaringType == typeof(DbContextGenerator) && WriterOverload(m, name)); + // The most derived override of that slot; the slot's own declaration when nothing overrides it. + var effective = GetType().GetMethods(flags).First(m => WriterOverload(m, name) && m.GetBaseDefinition() == declared); + return _writerOverrides[name] = effective.DeclaringType != typeof(DbContextGenerator); + } + + // The entries one hook contributes: the text hook's, unless the writer overload is overridden, + // in which case whatever it writes on a fresh writer is one entry (none when it writes nothing). + private IEnumerable HookEntries(string name, Action writerHook, Func> textHook) + { + if (!OverridesWriterHook(name)) return textHook(); + var fragment = NewWriter(); + writerHook(fragment); + var text = fragment.BodyOnly().TrimEnd('\n'); + return text.Length == 0 ? [] : [text]; + } + + // Writes each entry of a text hook through the writer, as the generator always has. + private static void WriteEntries(CsWriter w, IEnumerable entries) + { + foreach (var entry in entries) w.Text(entry); + } + + // A nullable single-entry text hook as a list. + private static IEnumerable One(string? entry) => entry is null ? [] : [entry]; + + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + public virtual IEnumerable Generate(GenContext ctx) { ctx = ctx.Narrow(Include); _config = ctx.Config; + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); // FR-017 TPH: a concrete subtype shares the base's single table — it gets NO // DbSet and no per-subtype model config; the hierarchy is reached via the base // DbSet (`.OfType()`). Filter subtypes out of the emitted set entirely. @@ -231,7 +291,10 @@ public virtual IEnumerable Generate(GenContext ctx) if (IdentityStartOn(ctx)) EmitIdentityStartConfig(owner, e, modelLines); EmitCommentConfig(owner, e, configFields, modelLines, ctx); EmitIndexConfig(owner, e, ctx, modelLines); - EmitCheckConfig(owner, e, ctx, modelLines); + if (OverridesWriterHook(nameof(EmitCheckConfig))) + modelLines.AddRange(HookEntries(nameof(EmitCheckConfig), fw => EmitCheckConfig(fw, owner, e, ctx), () => [])); + else + EmitCheckConfig(owner, e, ctx, modelLines); // identity.primary @generation: assigned — the caller supplies the key. EF's // convention makes a single integer or Guid key generated on add, which leaves a key @@ -295,7 +358,7 @@ public virtual IEnumerable Generate(GenContext ctx) // The adopter's own per-entity lines (indexes, CHECKs, query filters, computed // columns), last so they see everything the entity was configured with. - modelLines.AddRange(EntityConfigTrailer(e, ctx)); + modelLines.AddRange(HookEntries(nameof(EntityConfigTrailer), fw => EntityConfigTrailer(fw, e, ctx), () => EntityConfigTrailer(e, ctx))); } // #214 (FR-024 §7) — register the write-through read model against its replica view. @@ -434,7 +497,7 @@ protected virtual void EmitUsings(CsWriter w, bool needsMetadataUsing, GenContex w.Line($"public {name}(DbContextOptions<{name}> options) : base(options) {{ }}"); w.Blank(); } - var members = ContextMemberLines(ctx).ToList(); + var members = HookEntries(nameof(ContextMemberLines), fw => ContextMemberLines(fw, ctx), () => ContextMemberLines(ctx)).ToList(); foreach (var line in members) { w.Text(line); @@ -531,6 +594,10 @@ protected virtual IEnumerable ContextUsings(GenContext ctx) /// protected virtual IEnumerable ContextMemberLines(GenContext ctx) => []; + /// Writer seam for : write the extra class + /// members at the margin. Default: the text hook's lines. + protected virtual void ContextMemberLines(CsWriter w, GenContext ctx) => WriteEntries(w, ContextMemberLines(ctx)); + /// /// Extension hook — emits one public DbSet<Entity> Plural { get; set; } /// (with its XML doc) per persisted object/projection, in the order computed by @@ -543,7 +610,7 @@ protected virtual void EmitDbSetDeclarations(CsWriter w, IReadOnlyList DbSetLine(fw, o, ctx), () => [DbSetLine(o, ctx)])); // #214 — a write-through entity additionally exposes a read-model DbSet mapped to // its replica view (reads route here; the derived fields live on the view row). if (o.IsWriteThrough()) @@ -572,8 +639,8 @@ protected virtual void EmitDbSetDeclarations(CsWriter w, IReadOnlyList modelLines, GenContext ctx) { // Materialized once: a hook may enumerate lazily, and each is asked exactly once per context. - var preamble = ContextPreambleLines(ctx).ToList(); - var trailer = ContextTrailerLines(ctx).ToList(); + var preamble = HookEntries(nameof(ContextPreambleLines), fw => ContextPreambleLines(fw, ctx), () => ContextPreambleLines(ctx)).ToList(); + var trailer = HookEntries(nameof(ContextTrailerLines), fw => ContextTrailerLines(fw, ctx), () => ContextTrailerLines(ctx)).ToList(); if (modelLines.Count == 0 && preamble.Count == 0 && trailer.Count == 0 && !AlwaysEmitOnModelCreating(ctx)) { return; @@ -630,6 +697,10 @@ protected virtual void EmitOnModelCreatingBody(CsWriter w, IReadOnlyList /// protected virtual IEnumerable ContextPreambleLines(GenContext ctx) => []; + /// Writer seam for : write the statements + /// placed first in OnModelCreating. Default: the text hook's lines. + protected virtual void ContextPreambleLines(CsWriter w, GenContext ctx) => WriteEntries(w, ContextPreambleLines(ctx)); + /// /// Hook — complete lines placed LAST in OnModelCreating, after the model configuration /// (or after the ConfigureModelNN calls when the model is split). Default none. An @@ -638,6 +709,10 @@ protected virtual void EmitOnModelCreatingBody(CsWriter w, IReadOnlyList /// protected virtual IEnumerable ContextTrailerLines(GenContext ctx) => []; + /// Writer seam for : write the statements + /// placed last in OnModelCreating. Default: the text hook's lines. + protected virtual void ContextTrailerLines(CsWriter w, GenContext ctx) => WriteEntries(w, ContextTrailerLines(ctx)); + /// /// Hook — whether OnModelCreating is emitted even when there is nothing to put in it /// (no model lines, no preamble, no trailer). Default false: an empty method is omitted. @@ -662,6 +737,10 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) /// protected virtual string DbSetPropertyName(MetaObject entity, GenContext ctx) => CSharpNaming.DbSetName(entity); + /// Writer seam for : write the whole + /// DbSet declaration (an attribute above it, say). Default: the text hook's line. + protected virtual void DbSetLine(CsWriter w, MetaObject entity, GenContext ctx) => w.Text(DbSetLine(entity, ctx)); + /// /// Hook — extra configuration lines appended after everything else an entity is configured /// with (field types, defaults, M:N, TPH discriminator, references). Default none. For the @@ -670,6 +749,10 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) /// protected virtual IEnumerable EntityConfigTrailer(MetaObject entity, GenContext ctx) => []; + /// Writer seam for : write the + /// entity's extra configuration statements; what it writes is one model entry. Default: the text hook's lines. + protected virtual void EntityConfigTrailer(CsWriter w, MetaObject entity, GenContext ctx) => WriteEntries(w, EntityConfigTrailer(entity, ctx)); + // R6 Plan 2b — EF mapping for a @dbColumnType physical-override field. The CLR // property type is unchanged (the logical field's native binding); only the DB // column type — and, for uuid, a string↔Guid value converter — is configured so @@ -684,6 +767,12 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) // raw JSON text ↔ string directly. // (ADR-0036 Wave 2: the retired timestamp_with_tz override is gone — timezone-awareness // is the field.timestamp default, opted out of via @localTime; handled above.) + /// Writer seam for : write the + /// @dbColumnType configuration of one field, as one model entry; writing nothing leaves + /// it with no column-type line. Default: the text hook's entry. + protected virtual void DbColumnTypeConfig(CsWriter w, string owner, MetaField f) => + WriteEntries(w, One(DbColumnTypeConfig(owner, f))); + protected virtual string? DbColumnTypeConfig(string owner, MetaField f) { var prop = PropertyName(f); @@ -697,7 +786,7 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) // (see the field.uri note above); an unqualified `Guid.Parse` in OnModelCreating // would only compile under a host's ImplicitUsings. DbConstants.DB_COLUMN_TYPE_UUID => - lhs + ".HasColumnType(\"uuid\").HasConversion(v => System.Guid.Parse(v!), g => g.ToString(\"D\"));", + lhs + $".HasColumnType(\"uuid\").HasConversion(v => {Fx}System.Guid.Parse(v!), g => g.ToString(\"D\"));", DbConstants.DB_COLUMN_TYPE_JSONB => lhs + ".HasColumnType(\"jsonb\");", // rc.21 part B (U2): a text spelling is the column type, as `meta migrate` creates it. @@ -790,7 +879,7 @@ private void EmitReferenceConfig( foreach (var reference in entity.ReferenceIdentities().Where(r => r.Enforce)) { if (!emitted.Add(FkKey(reference))) continue; - modelLines.AddRange(ReferenceConfig(entity, reference, ctx)); + modelLines.AddRange(ReferenceEntries(entity, reference, ctx)); } if (tph is null) return; @@ -804,7 +893,7 @@ private void EmitReferenceConfig( .OfType().Where(r => r.Enforce)) { if (!emitted.Add(FkKey(reference))) continue; - modelLines.AddRange(ReferenceConfig(st.Entity, reference, ctx)); + modelLines.AddRange(ReferenceEntries(st.Entity, reference, ctx)); } } @@ -839,7 +928,7 @@ private void EmitReferenceConfig( { if (!emitted.Add(FkKey(reference))) continue; foreach (var leaf in leaves) - modelLines.AddRange(ReferenceConfig(leaf, reference, ctx)); + modelLines.AddRange(ReferenceEntries(leaf, reference, ctx)); } } } @@ -886,7 +975,7 @@ private void EmitDefaultValueConfig( { foreach (var f in fields) { - modelLines.AddRange(DefaultValueConfig(entity, f, ctx)); + modelLines.AddRange(HookEntries(nameof(DefaultValueConfig), fw => DefaultValueConfig(fw, entity, f, ctx), () => DefaultValueConfig(entity, f, ctx))); } } @@ -897,6 +986,10 @@ private void EmitDefaultValueConfig( /// the base returns nothing for a primary-key field, an array, a field with no @default /// and a @dbColumnType override. The emitted class is the entity's own name. /// + protected virtual void DefaultValueConfig(CsWriter w, MetaObject entity, MetaField f, GenContext ctx) => + WriteEntries(w, DefaultValueConfig(entity, f, ctx)); + + /// Text hook behind ; see the summary above. protected virtual IEnumerable DefaultValueConfig(MetaObject entity, MetaField f, GenContext ctx) { var className = ValueObjectNames.Ref(entity, ctx.Config); @@ -988,6 +1081,14 @@ private void EmitIdentityStartConfig(string owner, MetaObject entity, Listpostgres, sqlite, d1): /// the text is dialect-specific and EF hands it to the provider verbatim. One statement per entry. /// + protected virtual void EmitCheckConfig(CsWriter w, string owner, MetaObject entity, GenContext ctx) + { + var lines = new List(); + EmitCheckConfig(owner, entity, ctx, lines); + WriteEntries(w, lines); + } + + /// List hook behind ; see the summary above. protected virtual void EmitCheckConfig(string owner, MetaObject entity, GenContext ctx, List modelLines) { if (entity.DbTable is null) return; @@ -1495,7 +1596,7 @@ private void EmitForeignKeyIndexConfig(MetaObject entity, TphPlan? tph, GenConte private void EmitTphSubtypeFieldConfig(MetaObject root, TphPlan tph, GenContext ctx, List modelLines) { foreach (var st in tph.Subtypes) - modelLines.AddRange(TphSubtypeFieldConfig(root, st.Entity, ctx)); + modelLines.AddRange(HookEntries(nameof(TphSubtypeFieldConfig), fw => TphSubtypeFieldConfig(fw, root, st.Entity, ctx), () => TphSubtypeFieldConfig(root, st.Entity, ctx))); } /// @@ -1505,6 +1606,10 @@ private void EmitTphSubtypeFieldConfig(MetaObject root, TphPlan tph, GenContext /// index.lookup) for what it declares beyond its TPH ancestors, on the subtype's own builder. Called once per /// subtype of each discriminator ; empty for a subtype that adds no field. /// + protected virtual void TphSubtypeFieldConfig(CsWriter w, MetaObject root, MetaObject subtype, GenContext ctx) => + WriteEntries(w, TphSubtypeFieldConfig(root, subtype, ctx)); + + /// Text hook behind ; see the summary above. protected virtual IEnumerable TphSubtypeFieldConfig(MetaObject root, MetaObject subtype, GenContext ctx) { var tph = TphPlanBuilder.For(root, ctx.Root); @@ -1622,6 +1727,13 @@ private static string FkKey(MetaReferenceIdentity reference) => /// deliberately does not map. is the declaring entity (a TPH /// subtype for a reference it declares itself); the emitted class is its own name. /// + protected virtual void ReferenceConfig(CsWriter w, MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) => + WriteEntries(w, ReferenceConfig(entity, reference, ctx)); + + private IEnumerable ReferenceEntries(MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) => + HookEntries(nameof(ReferenceConfig), fw => ReferenceConfig(fw, entity, reference, ctx), () => ReferenceConfig(entity, reference, ctx)); + + /// Text hook behind ; see the summary above. protected virtual IEnumerable ReferenceConfig( MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) { @@ -1703,11 +1815,11 @@ private IEnumerable FlattenedMemberReferenceConfig( // `HomeCountry` over `CountryId` matches too); several, the one whose convention FK is these // properties — and with no such one the model build THROWS, naming the owner, rather than // configure a second relationship beside them (rc.21 fix round, M6). - var linq = "System.Linq.Enumerable"; + var linq = $"{Fx}System.Linq.Enumerable"; var fkNames = string.Join(", ", props.Select(p => $"\"{p}\"")); var toTarget = $"{linq}.Where(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}))"; var byFk = $"{linq}.FirstOrDefault({toTarget}, n => {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))"; - var ambiguous = $"new System.InvalidOperationException(\"{CSharpNaming.CSharpStringLiteral($"{entity.Name}.{nav} has several navigations to {target.Name} and none over {string.Join(", ", props)}: name the one this reference uses with that foreign key, or remove the others.")}\")"; + var ambiguous = $"new {Fx}System.InvalidOperationException(\"{CSharpNaming.CSharpStringLiteral($"{entity.Name}.{nav} has several navigations to {target.Name} and none over {string.Join(", ", props)}: name the one this reference uses with that foreign key, or remove the others.")}\")"; // rc.21 part B (N3): what codegen can know, it decides here. When this entity declares // another reference from the same owned member to the same target, a sole navigation may be // THAT reference's, so only the navigation over these exact properties is this one's; with @@ -1923,7 +2035,7 @@ private string UsingEntityConfig(M2MNavigation nav, GenContext ctx) /// rc.21 — the fail-fast helpers a @stringValueMap enum's converters end in, emitted only /// when a converter references them (so a model with none is byte-identical). /// - private static void EmitUnmappedStoredEnumHelper(CsWriter w) + private void EmitUnmappedStoredEnumHelper(CsWriter w) { w.Blank(); w.Text($$""" @@ -1932,7 +2044,7 @@ private static void EmitUnmappedStoredEnumHelper(CsWriter w) /// database holds data the model says is impossible. /// private static T {{UnmappedEnumStoredValueHelperName}}(string stored, string field) => - throw new System.InvalidOperationException( + throw new {{Fx}}System.InvalidOperationException( $"field.enum '{field}' read stored value '{stored}' with no member in " + "@stringValueMap — the database holds a value the model does not describe."); @@ -1941,7 +2053,7 @@ private static void EmitUnmappedStoredEnumHelper(CsWriter w) /// declared stored string, and writing another member's would corrupt the row silently. /// private static string {{UnmappedEnumStoredMemberHelperName}}(object? value, string field) => - throw new System.InvalidOperationException( + throw new {{Fx}}System.InvalidOperationException( $"field.enum '{field}' cannot write {value}: it has no stored string in " + "@stringValueMap — the value is not one of the members the model declares."); """); @@ -1952,7 +2064,7 @@ private static void EmitUnmappedStoredEnumHelper(CsWriter w) /// in. Emitted only when at least one such converter was generated, so a model with /// no @intValueMap produces byte-identical output. /// - private static void EmitUnmappedEnumHelper(CsWriter w) + private void EmitUnmappedEnumHelper(CsWriter w) { w.Blank(); // Fully qualified: the generated file's usings are a fixed set (EmitUsings), and @@ -1965,7 +2077,7 @@ private static void EmitUnmappedEnumHelper(CsWriter w) /// would hand the caller a wrong-but-valid value, silently. /// private static T {{UnmappedEnumHelperName}}(int stored, string field) => - throw new System.InvalidOperationException( + throw new {{Fx}}System.InvalidOperationException( $"field.enum '{field}' read stored value {stored} with no member in " + "@intValueMap — the database holds a value the model does not describe."); @@ -1975,7 +2087,7 @@ private static void EmitUnmappedEnumHelper(CsWriter w) /// integer, and writing some other member's instead would corrupt the row silently. /// private static int {{UnmappedEnumMemberHelperName}}(object? value, string field) => - throw new System.InvalidOperationException( + throw new {{Fx}}System.InvalidOperationException( $"field.enum '{field}' cannot write {value}: it has no integer in " + "@intValueMap — the value is not one of the members the model declares."); """); @@ -2076,7 +2188,7 @@ private static string MapValueTypeRef(MetaField f, GenContext ctx) /// untranslated and never invokes the expressions on it, so the lambdas' bodies are /// unchanged. /// - private static void EmitMapJsonbHelper(CsWriter w) + private void EmitMapJsonbHelper(CsWriter w) { w.Blank(); // A value object that holds a map is stored as ONE document converted whole: EF Core 8 cannot @@ -2090,40 +2202,40 @@ private static void EmitMapJsonbHelper(CsWriter w) /// private static class {{MapJsonbHelperName}} { - private static readonly System.Text.Json.JsonSerializerOptions Options = new() + private static readonly {{Fx}}System.Text.Json.JsonSerializerOptions Options = new() { - Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } + Converters = { new {{Fx}}System.Text.Json.Serialization.JsonStringEnumConverter() } }; - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< - System.Collections.Generic.Dictionary, string> RequiredConverter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>(v, Options)!); + internal static {{Fx}}Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + {{Fx}}System.Collections.Generic.Dictionary, string> RequiredConverter() => new( + v => {{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options), + v => {{Fx}}System.Text.Json.JsonSerializer.Deserialize< + {{Fx}}System.Collections.Generic.Dictionary>(v, Options)!); /// Same conversion as RequiredConverter, over the NULLABLE dictionary a /// non-required map's property carries — keep the two bodies identical. EF Core's /// nullability-aware HasConversion checks the converter's model type against the /// property's own annotation, so one factory cannot serve both arms. - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< - System.Collections.Generic.Dictionary?, string> Converter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>(v, Options)!); + internal static {{Fx}}Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + {{Fx}}System.Collections.Generic.Dictionary?, string> Converter() => new( + v => {{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options), + v => {{Fx}}System.Text.Json.JsonSerializer.Deserialize< + {{Fx}}System.Collections.Generic.Dictionary>(v, Options)!); /// A whole value-object document (or collection of them) as one jsonb value, /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON). - internal static Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( - v => System.Text.Json.JsonSerializer.Serialize(v, Options), - v => System.Text.Json.JsonSerializer.Deserialize(v, Options)!); + internal static {{Fx}}Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( + v => {{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options), + v => {{Fx}}System.Text.Json.JsonSerializer.Deserialize(v, Options)!); - internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( - (a, b) => System.Text.Json.JsonSerializer.Serialize(a, Options) == System.Text.Json.JsonSerializer.Serialize(b, Options), - v => System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), - v => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); + internal static {{Fx}}Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( + (a, b) => {{Fx}}System.Text.Json.JsonSerializer.Serialize(a, Options) == {{Fx}}System.Text.Json.JsonSerializer.Serialize(b, Options), + v => {{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), + v => {{Fx}}System.Text.Json.JsonSerializer.Deserialize({{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); - internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< - System.Collections.Generic.Dictionary?> Comparer() => new( + internal static {{Fx}}Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< + {{Fx}}System.Collections.Generic.Dictionary?> Comparer() => new( (a, b) => Eq(a, b), v => Hash(v), v => Snap(v)); /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key @@ -2132,17 +2244,17 @@ internal static Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< /// comparer (no serialization at all); a value-object value falls through to a JSON /// compare, since the generated POCO is a class and compares by reference. private static bool Eq( - System.Collections.Generic.Dictionary? a, - System.Collections.Generic.Dictionary? b) + {{Fx}}System.Collections.Generic.Dictionary? a, + {{Fx}}System.Collections.Generic.Dictionary? b) { if (a is null || b is null) return ReferenceEquals(a, b); if (a.Count != b.Count) return false; foreach (var kv in a) { if (!b.TryGetValue(kv.Key, out var other)) return false; - if (System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; - if (System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) - != System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; + if ({{Fx}}System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; + if ({{Fx}}System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) + != {{Fx}}System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; } return true; } @@ -2150,7 +2262,7 @@ private static bool Eq( /// Keys and count only — order-independent (XOR), allocation-free, and /// stable for a value-object value whose GetHashCode is reference-based. Equal /// dictionaries always hash equal, which is all EF requires. - private static int Hash(System.Collections.Generic.Dictionary? v) + private static int Hash({{Fx}}System.Collections.Generic.Dictionary? v) { if (v is null) return 0; var h = v.Count; @@ -2161,15 +2273,15 @@ private static int Hash(System.Collections.Generic.DictionaryThe change-tracking snapshot. A value-object value needs a DEEP copy or /// an in-place edit to a nested object mutates the snapshot too and goes undetected; /// an immutable scalar only needs the dictionary copied. - private static System.Collections.Generic.Dictionary? Snap( - System.Collections.Generic.Dictionary? v) => + private static {{Fx}}System.Collections.Generic.Dictionary? Snap( + {{Fx}}System.Collections.Generic.Dictionary? v) => v is null ? null : typeof(TValue).IsValueType || typeof(TValue) == typeof(string) - ? new System.Collections.Generic.Dictionary(v) - : System.Text.Json.JsonSerializer.Deserialize< - System.Collections.Generic.Dictionary>( - System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; + ? new {{Fx}}System.Collections.Generic.Dictionary(v) + : {{Fx}}System.Text.Json.JsonSerializer.Deserialize< + {{Fx}}System.Collections.Generic.Dictionary>( + {{Fx}}System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; } """); } @@ -2343,10 +2455,8 @@ private void EmitFieldTypeConfig( foreach (var f in fieldList.Where(f => f.SubType == FIELD_SUBTYPE_OBJECT && (!jsonbObjectsOnly || f.Storage != STORAGE_FLATTENED))) { - if (OwnedTypeConfig(className, entity, f, ctx) is { } cfg) - { - modelLines.Add(cfg); - } + modelLines.AddRange(HookEntries(nameof(OwnedTypeConfig), + fw => OwnedTypeConfig(fw, className, entity, f, ctx), () => One(OwnedTypeConfig(className, entity, f, ctx)))); } // Every other kind of field, in FieldTypeRank order: all maps, then all enums, then primitive @@ -2403,7 +2513,8 @@ private void EmitFieldTypeConfig( } } } - modelLines.AddRange(FieldTypeConfig(className, entity, f, ctx)); + modelLines.AddRange(HookEntries(nameof(FieldTypeConfig), + fw => FieldTypeConfig(fw, className, entity, f, ctx), () => FieldTypeConfig(className, entity, f, ctx))); } } finally @@ -2414,10 +2525,8 @@ private void EmitFieldTypeConfig( foreach (var f in fieldList.Where(f => !f.ResolvedIsArray() && f.DbColumnType is not null)) { // An override that returns null leaves the field with no column-type line. - if (DbColumnTypeConfig(className, f) is { } cfg) - { - modelLines.Add(cfg); - } + modelLines.AddRange(HookEntries(nameof(DbColumnTypeConfig), + fw => DbColumnTypeConfig(fw, className, f), () => One(DbColumnTypeConfig(className, f)))); } } @@ -2484,6 +2593,10 @@ private static int FieldTypeRank(MetaField f) /// apply to. Enum conversions come from , owned value objects /// from and @dbColumnType from . /// + protected virtual void FieldTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField f, GenContext ctx) => + WriteEntries(w, FieldTypeConfig(owner, entity, f, ctx)); + + /// Text hook behind ; see the summary above. protected virtual IEnumerable FieldTypeConfig(string owner, MetaObject entity, MetaField f, GenContext ctx) { var lines = new List(); @@ -2538,7 +2651,7 @@ protected virtual IEnumerable FieldTypeConfig(string owner, MetaObject e // to compile except under a host's ImplicitUsings — the generated context must be // self-contained (this is also on the #214 write-through read-model path now). lines.Add( - $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"text\").HasConversion(v => v!.ToString(), v => new System.Uri(v));"); + $"modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"text\").HasConversion(v => v!.ToString(), v => new {Fx}System.Uri(v));"); } if (!array && f.SubType == FIELD_SUBTYPE_INET && !CSharpNaming.IsLenientNet(f)) @@ -2626,16 +2739,18 @@ private static string DurationWireRef(MetaObject owner, GenContext ctx) => // A TimeSpan <-> canonical ISO-8601 string converter: a duration inside a JSON document. private static string DurationConverter(MetaObject owner, GenContext ctx) { + var Fx = CSharpNaming.FrameworkPrefix(ctx.Config); var dw = DurationWireRef(owner, ctx); - return "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + return $"new {Fx}Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<{Fx}System.TimeSpan, string>(" + $"v => {dw}.Format(v), v => {dw}.Parse(v))"; } // A TimeSpan <-> microsecond-count converter: a duration column on a database without an interval type. private static string DurationMicrosConverter(MetaObject owner, GenContext ctx) { + var Fx = CSharpNaming.FrameworkPrefix(ctx.Config); var dw = DurationWireRef(owner, ctx); - return "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + return $"new {Fx}Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<{Fx}System.TimeSpan, long>(" + $"v => {dw}.ToMicros(v), v => {dw}.FromMicros(v))"; } @@ -2810,6 +2925,16 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s // required, so EF models it nullable — a gen↔schema nullability mismatch. Deferred // until the exact EF Core required-owned-JSON mapping can be validated against a // live provider. + /// + /// Writer seam for : write the + /// owned-type configuration of one object-typed field, as one model entry, so a nested + /// OwnsOne(x => x.Nav, b => { … }) block is written with Braced rather than built on + /// a local writer and returned as text. Writing nothing leaves the field unconfigured. + /// Default: the text hook's entry. + /// + protected virtual void OwnedTypeConfig(CsWriter w, string owner, MetaObject entity, MetaField field, GenContext ctx) => + WriteEntries(w, One(OwnedTypeConfig(owner, entity, field, ctx))); + protected virtual string? OwnedTypeConfig(string owner, MetaObject entity, MetaField field, GenContext ctx) { if (ValueObjectNames.ResolveFieldRef(field, ctx.Root) is not { } vo) @@ -2848,7 +2973,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var modelType = CSharpNaming.IsRequired(entity, field) ? "" : "?"; var voType = MapValueTypeRef(field, ctx); var clr = field.ResolvedIsArray() - ? $"System.Collections.Generic.ICollection<{voType}>{modelType}" + ? $"{Fx}System.Collections.Generic.ICollection<{voType}>{modelType}" : voType + modelType; return $"modelBuilder.Entity<{owner}>().Property(x => x.{nav}).HasColumnName({parentColRef})" + $".HasColumnType(\"jsonb\").HasConversion({MapJsonbHelperName}.ObjectConverter<{clr}>(), {MapJsonbHelperName}.ObjectComparer<{clr}>());"; @@ -2938,7 +3063,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var nullable = CSharpNaming.IsRequired(vo, nf) ? "" : "?"; var nestedType = MapValueTypeRef(nf, ctx); var clr = nf.ResolvedIsArray() - ? $"System.Collections.Generic.ICollection<{nestedType}>{nullable}" + ? $"{Fx}System.Collections.Generic.ICollection<{nestedType}>{nullable}" : nestedType + nullable; s.Line($"b.Property(p => p.{PropertyName(nf)}).HasColumnName(\"{nestedColAny}\")" + $".HasColumnType(\"jsonb\").HasConversion({MapJsonbHelperName}.ObjectConverter<{clr}>(), {MapJsonbHelperName}.ObjectComparer<{clr}>());"); @@ -3028,8 +3153,8 @@ private List JsonEnumConversions(MetaObject vo, GenContext ctx, string b && CSharpNaming.DbColumnTypeClrOverride(nf) is null) { lines.Add(CSharpNaming.IsRequired(vo, nf) - ? $"{builder}.Property(p => p.{prop}).HasConversion(v => v.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));" - : $"{builder}.Property(p => p.{prop}).HasConversion(v => v == null ? null : v.Value.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => s == null ? (decimal?)null : decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));"); + ? $"{builder}.Property(p => p.{prop}).HasConversion(v => v.ToString(\"0.############################\", {Fx}System.Globalization.CultureInfo.InvariantCulture), s => decimal.Parse(s, {Fx}System.Globalization.CultureInfo.InvariantCulture));" + : $"{builder}.Property(p => p.{prop}).HasConversion(v => v == null ? null : v.Value.ToString(\"0.############################\", {Fx}System.Globalization.CultureInfo.InvariantCulture), s => s == null ? (decimal?)null : decimal.Parse(s, {Fx}System.Globalization.CultureInfo.InvariantCulture));"); continue; } // A duration member of a JSON document is stored as its canonical ISO-8601 string (the diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 6cd1b6d56..44bf64f7c 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -113,10 +113,19 @@ private static void Claimed(List files, EmittedFile file, MetaObjec files.Add(file); } + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + public virtual IEnumerable Generate(GenContext ctx) { ctx = ctx.Narrow(Include); _wire = ctx.Root.WireFormat; + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); _config = ctx.Config; _ctx = ctx; CSharpNaming.RefuseDivergingPropertyHook(Name, ReportRows.WithReportRows(ctx), ctx.Config, PropertyName); @@ -288,6 +297,51 @@ private static List HelperNamespaces(IEnumerable shapes, Gen private static string HelperFileName(string stem, string ns, IReadOnlyCollection namespaces) => namespaces.Count > 1 ? $"{stem}.{ns}.g.cs" : $"{stem}.g.cs"; + // Whether a view-mapped class leaves out an object-typed field: a plain read-only projection + // leaves out every one (EF maps no owned type on a view-mapped, usually keyless, class here); + // a write-through read model leaves out only a flattened one. + private static bool SkipsViewObjectField(MetaField field, bool includeJsonbObjects) => + field.SubType == FIELD_SUBTYPE_OBJECT && (!includeJsonbObjects || field.Storage == STORAGE_FLATTENED); + + /// + /// The object-typed fields this generator leaves off a view-mapped class, one advisory line each + /// with its fix: every object-typed field of a read-only projection, and every flattened value + /// object of a write-through entity's <Entity>View read model. Empty when no entity + /// generator in accepts the object (its ). Callers pass + /// the entries unwrapped (). dotnet meta verify prints these once; + /// gen does not, so a clean regen prints nothing. Advisory only: the output is correct + /// without the field, which simply is not readable through the view class. + /// + public static IReadOnlyList UnemittedObjectFields(MetaRoot root, IEnumerable generators) + { + var entityGenerators = generators.OfType().ToList(); + if (entityGenerators.Count == 0) return []; + var lines = new List(); + foreach (var o in root.Objects() + .Where(o => root.InScope(o) && !InstanceArtifacts.IsAbstract(o) && InstanceArtifacts.HasAnyRdbSource(o) + && !TphPlanBuilder.IsTphSubtype(o, root) + && entityGenerators.Any(g => g.Include is null || g.Include(o))) + .OrderBy(o => o.ResolutionKey(), StringComparer.Ordinal)) + { + if (o.IsReadOnlyProjection()) + { + foreach (var f in o.Fields().Where(f => SkipsViewObjectField(f, includeJsonbObjects: false))) + lines.Add($"entity-generator: object-typed field \"{o.Name}.{f.Name}\" is not emitted on projection " + + $"{o.Name}: a view-mapped class carries no value object here. Remove the field from the projection, " + + "or read the value through its entity: a write-through entity's View read model carries " + + "a value object stored as jsonb."); + } + else if (o.IsEntity() && o.IsWriteThrough()) + { + foreach (var f in o.Fields().Where(f => SkipsViewObjectField(f, includeJsonbObjects: true))) + lines.Add($"entity-generator: flattened value object \"{o.Name}.{f.Name}\" is not emitted on the read model " + + $"{CSharpNaming.ViewModelClassName(o)}: the replica view does not project a flattened value object. " + + "Store it with @storage: jsonb to read it through the view, or read it from the table entity."); + } + } + return lines; + } + // EF Core entity (table) or projection (view) class. For a write-through entity // (#214) this emits the WRITE half: the table-mapped, derived-FREE entity (the // derived origin.* fields live only on the view read model — EmitWriteThroughReadModel). @@ -408,22 +462,16 @@ private EmittedFile EmitMappedClassImpl( } else if (field.SubType == FIELD_SUBTYPE_OBJECT) { - // Owned-type navigation only on entities; projection collection - // origins are materialized elsewhere. - if (isProjection) - { - // #214 [1] — a write-through entity's read model (includeJsonbObjects) - // DOES carry its non-derived single-jsonb-column value-object columns: - // reads route to the view, so the column must be present to be readable. - // The DbContext registers the matching owned-VO config (OwnsOne/OwnsMany - // .ToJson). A FLATTENED VO (multi-column spread) is out of scope on the - // view. A plain projection keeps the original warn-and-skip. - if (!includeJsonbObjects || field.Storage == STORAGE_FLATTENED) - { - ctx.Warn($"{Name}: skipping object-typed field \"{entity.Name}.{field.Name}\" on projection (collection materialization not emitted here)."); - continue; - } - } + // Owned-type navigation only on entities. + // #214 [1] — a write-through entity's read model (includeJsonbObjects) + // DOES carry its non-derived single-jsonb-column value-object columns: + // reads route to the view, so the column must be present to be readable. + // The DbContext registers the matching owned-VO config (OwnsOne/OwnsMany + // .ToJson). A FLATTENED VO (multi-column spread) is out of scope on the + // view, and a plain projection carries none. The skip is reported once, by + // `dotnet meta verify` (UnemittedObjectFields), never on every regen. + if (isProjection && SkipsViewObjectField(field, includeJsonbObjects)) + continue; WriteObjectNavProperty(w, entity, field, ctx); } else if (field.SubType == FIELD_SUBTYPE_MAP) @@ -530,7 +578,7 @@ protected virtual void EmitClassHeader( protected virtual IEnumerable TphDerivedTypeAttributes(MetaObject root, GenContext ctx) => TphPlanBuilder.For(root, ctx.Root) is { } plan ? plan.Subtypes.Select(sub => - $"[System.Text.Json.Serialization.JsonDerivedType(typeof({ValueObjectNames.Ref(sub.Entity, ctx.Config)}))]") + $"[{Fx}System.Text.Json.Serialization.JsonDerivedType(typeof({ValueObjectNames.Ref(sub.Entity, ctx.Config)}))]") : []; // Extension hook — class-level attributes of an adopter's own, emitted after the framework's @@ -746,7 +794,7 @@ protected virtual void WriteTphSubtypeScalarProperty( w.Line(arrColumn); } WriteArrayValidatorAttributes(w, field); - ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire, Fx); ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection. @@ -763,7 +811,7 @@ protected virtual void WriteTphSubtypeScalarProperty( else WriteNumericValidatorAttributes(w, field); var required = CSharpNaming.IsRequired(entity, field); - ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !required, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !required, _wire, Fx); ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // Mirrors WriteScalarProperty's own initializer handling (its non-TPH sibling): a // literal-safe @default (bool/int/long/double/float/decimal/string) wins over the @@ -1439,12 +1487,12 @@ static string InvariantNumber(object v) return ParseIsoDurationMicros(d) is { } us ? ($"TimeSpan.FromTicks({us * 10}L)", false) : null; case CrossKind.Temporal when lit is string t && temporalClr is not null: { - var inv = "System.Globalization.CultureInfo.InvariantCulture"; + var inv = $"{Fx}System.Globalization.CultureInfo.InvariantCulture"; return temporalClr switch { "DateOnly" => ($"DateOnly.Parse({CsLiteral(t)}, {inv})", false), "TimeOnly" => ($"TimeOnly.Parse({CsLiteral(t)}, {inv})", false), - "DateTimeOffset" => ($"DateTimeOffset.Parse({CsLiteral(t)}, {inv}, System.Globalization.DateTimeStyles.AssumeUniversal)", false), + "DateTimeOffset" => ($"DateTimeOffset.Parse({CsLiteral(t)}, {inv}, {Fx}System.Globalization.DateTimeStyles.AssumeUniversal)", false), "DateTime" => ($"DateTime.Parse({CsLiteral(t)}, {inv})", false), _ => null, }; @@ -2699,7 +2747,7 @@ protected virtual void WriteScalarProperty( WriteArrayValidatorAttributes(w, field); // EF Core 8 on SQLite materializes a primitive collection only through IList (an // ICollection property throws at query compile time), so a scalar array is an IList. - ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire, Fx); ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection; a @@ -2760,7 +2808,7 @@ protected virtual void WriteScalarProperty( ContractMembers.WriteNetConverterAttribute(w, field); // ADR-0019 Amendment 1: a decimal crosses JSON as a canonical string. Attached per // property (not through host JsonSerializerOptions) so no host configuration drops it. - ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !ScalarIsNonNull(owner, field), _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !ScalarIsNonNull(owner, field), _wire, Fx); // field.duration: a TimeSpan crosses JSON as its canonical ISO-8601 string, never as // System.Text.Json's own "01:30:00". ContractMembers.WriteDurationConverterAttribute(w, field, _wire); diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index b3b5cc14b..779716da5 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -188,6 +188,7 @@ protected virtual void WriteMapper(CsWriter w, MetaData vo, GenContext ctx) /// The initializer expression mapping one mirror member onto the POCO member. private static string StrictArg(MetaObject owner, MetaField field, GenContext ctx) { + var Fx = CSharpNaming.FrameworkPrefix(ctx.Config); string m = $"m.{field.Name}"; bool required = CSharpNaming.IsRequired(owner, field); @@ -212,8 +213,8 @@ private static string StrictArg(MetaObject owner, MetaField field, GenContext ct string et = EnumTypeRef(owner, field, ctx); if (Fr010FieldMapping.IsArray(field)) return $"({m} ?? global::System.Linq.Enumerable.Empty()).Where(x => x is not null)" + - $".Select(x => System.Enum.Parse<{et}>(x!)).ToList()"; - return required ? $"System.Enum.Parse<{et}>({m}!)" : $"{m} is null ? ({et}?)null : System.Enum.Parse<{et}>({m})"; + $".Select(x => {Fx}System.Enum.Parse<{et}>(x!)).ToList()"; + return required ? $"{Fx}System.Enum.Parse<{et}>({m}!)" : $"{m} is null ? ({et}?)null : {Fx}System.Enum.Parse<{et}>({m})"; } string baseType = CSharpNaming.DbColumnTypeClrOverride(field) ?? CSharpNaming.ScalarForField(field) ?? "string"; diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 48521000d..78f4ee4ea 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -66,10 +66,21 @@ public static bool AppliesTo(MetaObject entity) => && InstanceArtifacts.EmitsInstanceArtifacts(entity)) || InstanceArtifacts.IsSourcelessEntity(entity); + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + // FR-044 — a served report joins the set as its ROW MODEL (ReportRows), whose derived // fields are what the allowlist lists; a raw report node in the entity set is dropped. - public override IEnumerable Generate(GenContext ctx) => - ReportRows.WithReportRows(ctx.Narrow(Include)).Where(Filter).Select(e => GenerateOne(e, ctx)); + public override IEnumerable Generate(GenContext ctx) + { + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); + return ReportRows.WithReportRows(ctx.Narrow(Include)).Where(Filter).Select(e => GenerateOne(e, ctx)); + } protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) { @@ -141,7 +152,7 @@ protected virtual void WriteTypeDoc(CsWriter w, string cls) => w.DocSummary( /// The Fields set: the filterable field names. Ordinal comparison, because the URL grammar is case-exact. protected virtual void WriteFields(CsWriter w, IReadOnlyDictionary> opsByField) { - using (w.Braced("public static readonly HashSet Fields = new(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly HashSet Fields = new({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var f in opsByField.Keys) w.Line($"\"{f}\","); } @@ -150,10 +161,10 @@ protected virtual void WriteFields(CsWriter w, IReadOnlyDictionaryThe OpsByField dictionary: each field's operator set. protected virtual void WriteOpsByField(CsWriter w, IReadOnlyDictionary> opsByField) { - using (w.Braced("public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly Dictionary> OpsByField = new({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var (field, ops) in opsByField) - w.Line($"[\"{field}\"] = new(System.StringComparer.Ordinal) {{ {string.Join(", ", ops.Select(op => $"\"{op}\""))} }},"); + w.Line($"[\"{field}\"] = new({Fx}System.StringComparer.Ordinal) {{ {string.Join(", ", ops.Select(op => $"\"{op}\""))} }},"); } } @@ -164,7 +175,7 @@ protected virtual void WriteOpsByField(CsWriter w, IReadOnlyDictionary rules) { w.Line("/// Each filterable field's rule: its operators, how its values are typed and checked."); - using (w.Braced("public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly IReadOnlyDictionary Rules = new Dictionary({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var (field, rule) in rules) { @@ -184,7 +195,7 @@ protected virtual void WriteRules(CsWriter w, IReadOnlyList<(string Field, Filte protected virtual void WriteSortRules(CsWriter w, IReadOnlyList<(string Field, string? DefaultOrder)> rules) { w.Line("/// The sortable fields, each with its declared @sortableDefaultOrder."); - using (w.Braced("public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly IReadOnlyDictionary Sort = new Dictionary({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var (field, order) in rules) w.Line(order is null ? $"[\"{field}\"] = new()," : $"[\"{field}\"] = new(\"{order}\"),"); @@ -198,7 +209,7 @@ protected virtual void WriteSortRules(CsWriter w, IReadOnlyList<(string Field, s protected virtual void WriteFieldNames(CsWriter w, IReadOnlyList names) { w.Line("/// Every field of the entity, filterable or not, except a credential."); - using (w.Braced("public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly IReadOnlySet FieldNames = new HashSet({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var name in names) w.Line($"\"{name}\","); } @@ -221,7 +232,7 @@ public static IReadOnlyList FieldNames(MetaObject entity, MetaRoot root) protected virtual void WritePropertyByField(CsWriter w, IReadOnlyDictionary renamed) { w.Line("/// The CLR property of each field whose property name is not the field name in another case."); - using (w.Braced("public static readonly IReadOnlyDictionary PropertyByField = new Dictionary(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static readonly IReadOnlyDictionary PropertyByField = new Dictionary({Fx}System.StringComparer.Ordinal)", "};")) { foreach (var (field, property) in renamed) w.Line($"[\"{field}\"] = \"{property}\","); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs b/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs index e46036d86..6d205f080 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/Fr019SharedEnum.cs @@ -150,9 +150,21 @@ public static string SharedEnumTypeReference(SharedEnum shared, GenConfig config return config.PackageNamespacesFromMetadata ? ValueObjectNames.Global(MaterializedNamespace(shared, config), shared.Name) : shared.Name; - // Bind the namespace to the enum's declaring metadata package (ADR-0001): - // TypeOverrides → PackageNamespaces → Convention with ProvidedEnumPrepend → - // ProvidedEnumNamespace (FR-019 legacy single-string fallback) → Error. + return $"{ProvidedEnumNamespace(shared, config)}.{shared.Name}"; + } + + /// + /// The namespace a @provided shared enum is referenced from — the counterpart of + /// for an enum the project supplies itself. + /// builds its reference from this, so an owned generator + /// that needs the namespace alone (a using, an alias) agrees with it by construction. + /// Bound to the enum's declaring metadata package (ADR-0001): TypeOverrides → + /// PackageNamespaces → Convention with ProvidedEnumPrepend → + /// (the FR-019 single-string fallback) → error. + /// + /// No namespace is configured for the enum. + public static string ProvidedEnumNamespace(SharedEnum shared, GenConfig config) + { var ns = PackageBindingResolver.TryResolve(config, shared.Package, shared.Name, useProvidedEnumPrepend: true) ?? config.ProvidedEnumNamespace; if (string.IsNullOrEmpty(ns)) @@ -161,6 +173,6 @@ public static string SharedEnumTypeReference(SharedEnum shared, GenConfig config $"@provided but no C# namespace is configured to reference it from. Set " + $"Convention.ProvidedEnumPrepend, map its package in PackageNamespaces, " + $"or set the legacy ProvidedEnumNamespace fallback."); - return $"{PackageBindingResolver.ValidNamespace(ns, shared.Package)}.{shared.Name}"; + return PackageBindingResolver.ValidNamespace(ns, shared.Package); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index 7c9f95412..f45570d58 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -33,6 +33,14 @@ public class NamesGenerator : PerEntityGenerator { public override string Name => "names"; + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + /// /// Pass 1 — every matched object that participates in the database (#248). Pass 2 — the /// abstract bases those participants EXTEND, each carrying the columns it declares so a @@ -44,6 +52,7 @@ public class NamesGenerator : PerEntityGenerator /// public override IEnumerable Generate(GenContext ctx) { + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); var emitted = new HashSet(StringComparer.Ordinal); var files = new List(); @@ -434,7 +443,7 @@ protected virtual void WriteMembers(CsWriter w, IEnumerable> groups protected virtual void WriteColumnsByField(CsWriter w, ObjectNames names, bool hasBase) { var hides = hasBase ? "new " : ""; - using (w.Braced($"public static {hides}readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal)", "};")) + using (w.Braced($"public static {hides}readonly Dictionary ColumnsByField = new({Fx}System.StringComparer.Ordinal)", "};")) { var skippedMembers = CollidingFlattenedMembers(names); foreach (var f in names.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index 5abe04431..81366a79c 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -214,8 +214,8 @@ namespace {{ctx.Config.Namespace}}; case IPAddress ip: return new(ip.ToString(), false); """); if (durations) w.Line(DurationCase); - w.Text(""" - case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); + w.Text($$""" + case IEnumerable: return new({{CSharpNaming.FrameworkPrefix(ctx.Config)}}System.Text.Json.JsonSerializer.Serialize(value), false); case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); """); diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs index 91b1496c9..b4c36e0f2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs @@ -129,7 +129,7 @@ private static string FkValueType(MetaObject entity, ReverseFk fk, MetaRoot root var ns = ValueObjectNames.CompanionNamespace(entity, ctx.Config); var rowName = rowTypeOverride ?? cls; // #214 write-through → View var rowType = ctx.Config.PackageNamespacesFromMetadata ? ValueObjectNames.Global(entityNs, rowName) : rowName; - var sys = ctx.Config.PackageNamespacesFromMetadata ? "global::" : ""; + var sys = CSharpNaming.FrameworkPrefix(ctx.Config); var queriesCls = CSharpNaming.QueriesClassName(entity); var dbSet = readDbSetOverride ?? CSharpNaming.DbSetName(entity); // #214 write-through → Views diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index ce53bd335..91405e59e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -89,11 +89,20 @@ public static bool AppliesTo(MetaObject entity, MetaRoot root) => // emits NO standalone routes file (the base mounts polymorphic + per-subtype CRUD). // The subtype skip needs the root, which Filter doesn't receive, so it is applied // here where the GenContext is in scope. + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + // FR-044 — a served report joins the set as its ROW MODEL (ReportRows): a keyless, // projection-shaped object, so GenerateStandardRoutes emits the list GET and the POST // refusal and nothing else. A raw report node in the entity set is dropped. public override IEnumerable Generate(GenContext ctx) { + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); var served = ReportRows.WithReportRows(ctx.Narrow(Include)) .Where(e => AppliesTo(e, ctx.Root)) .ToList(); @@ -366,7 +375,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte w.Open("{"); // Refuse to start when the host's serializer contract cannot be read to strip a credential. if (p.Credentials.Count > 0) - w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ typeof({p.ReadCls}) }}, {NamesLiteral(p.Credentials)});"); + w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new {Fx}System.Type[] {{ typeof({p.ReadCls}) }}, {NamesLiteral(p.Credentials)});"); WriteDecimalRangeGroup(w); WriteListRoute(w, p); @@ -449,7 +458,7 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) var fm = FilterMapArg($"{cls}FilterAllowlist", p.Entity, p.Ctx.Config); WriteListQuery(w, readCls, $"{cls}FilterAllowlist", fm, "SortRules", p.SqliteSort - ? $"ApplySort{cls}(q, __sortProp, desc, db.Database.ProviderName?.Contains(\"Sqlite\", System.StringComparison.OrdinalIgnoreCase) == true)" + ? $"ApplySort{cls}(q, __sortProp, desc, db.Database.ProviderName?.Contains(\"Sqlite\", {Fx}System.StringComparison.OrdinalIgnoreCase) == true)" : $"ApplySort{cls}(q, __sortProp, desc)"); w.Blank(); if (p.IsReport) @@ -465,7 +474,7 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) } w.Blank(); w.Line("// withCount=1 → { rows, total } envelope; otherwise bare row array."); - w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Line($"var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", {Fx}System.StringComparison.OrdinalIgnoreCase));"); if (export is null) w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); else @@ -536,22 +545,22 @@ protected virtual void WriteUpdateRoute(CsWriter w, StandardRoutesPlan p) // is a 400. The per-key merge (shared with the TPH per-subtype handler) is // emitted by WritePartialMergeLoop. w.Blank(); - w.Line("async System.Threading.Tasks.Task Update" + cls + "(HttpContext http, " + p.ContextType + " db)"); + w.Line($"async {Fx}System.Threading.Tasks.Task Update" + cls + "(HttpContext http, " + p.ContextType + " db)"); w.Open("{"); WriteReadId(w, p.PkType!); w.Line("var existing = await db." + dbSet + ".FindAsync(id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - w.Line("System.Text.Json.JsonDocument body;"); - w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); + w.Line($"{Fx}System.Text.Json.JsonDocument body;"); + w.Line($"try {{ body = await {Fx}System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }}"); + w.Line($"catch ({Fx}System.Text.Json.JsonException) {{ return RouteErrors.InvalidJson(); }}"); w.Line("using var bodyScope = body;"); - w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); + w.Line($"if (body.RootElement.ValueKind != {Fx}System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); WriteUnknownFieldsCheck(w, ctx.Root, "body"); w.Line("// Deserialize each value with the app's CONFIGURED JSON options, not defaults —"); w.Line("// a field.timestamp binds to DateTimeOffset via a custom converter registered on"); w.Line("// ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500."); - w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + w.Line($"var jsonOpts = (({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>)"); + using (w.Hanging()) w.Line($"http.RequestServices.GetService(typeof({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>))!)"); using (w.Hanging()) w.Line(".Value.SerializerOptions;"); w.Line("var entry = db.Entry(existing);"); WriteUpdateAutoSet(w, p.AutoSetFields); @@ -758,7 +767,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t if (p.BaseCredentials.Count > 0) { var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); - w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(p.BaseCredentials)});"); + w.Line($"SerializerKeys.EnsureContract(app.ServiceProvider, new {Fx}System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(p.BaseCredentials)});"); } WriteDecimalRangeGroup(w); @@ -814,7 +823,7 @@ protected virtual void WriteTphListRoute(CsWriter w, TphRoutesPlan p) WriteListQuery(w, baseCls, $"{baseCls}FilterAllowlist", fmB, "SortRules", "ApplySort(q, __sortProp, desc)"); WriteListPage(w, ctx.Root.Api.Pagination); w.Line("var rows = await q.ToListAsync();"); - w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Line($"var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", {Fx}System.StringComparison.OrdinalIgnoreCase));"); w.Line($"if (!withCount) return {OkResult("rows", p.BaseCredentials)};"); w.Line($"var total = await EfCoreFilterDispatch.Apply(db.{dbSet}.AsNoTracking(), listQuery, {baseCls}FilterAllowlist.Rules{fmB}).CountAsync();"); w.Line($"return {OkResult("new { rows, total }", p.BaseCredentials, envelope: true)};"); @@ -968,8 +977,9 @@ protected static IEnumerable CredentialSpellings(MetaField f, GenConfig new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. - protected static string KeyMatch(IEnumerable keys) => - string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)")); + // `fx` is the run's framework prefix (CSharpNaming.FrameworkPrefix). + protected static string KeyMatch(IEnumerable keys, string fx = "") => + string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", {fx}System.StringComparison.OrdinalIgnoreCase)")); // The sort rules (case-insensitive) a list route hands ListQueryParser: each key gives the CLR property to // sort on and the field's DECLARED @sortableDefaultOrder. The keys are the property names (the field name @@ -979,7 +989,7 @@ protected static string KeyMatch(IEnumerable keys) => protected virtual void WriteSortRules(CsWriter w, string name, IReadOnlyList fields, GenConfig config) { var pairs = fields.Select(f => (Field: f.Name, Prop: CSharpNaming.PropertyName(f, config), Order: f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) as string)).ToList(); - w.Line($"private static readonly System.Collections.Generic.Dictionary {name} = new(System.StringComparer.OrdinalIgnoreCase)"); + w.Line($"private static readonly {Fx}System.Collections.Generic.Dictionary {name} = new({Fx}System.StringComparer.OrdinalIgnoreCase)"); w.Open("{"); // Property names first, so a field name that spells another field's property never shadows it. var keys = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -1036,12 +1046,12 @@ protected virtual void WriteOmitResultClass(CsWriter w, bool used) w.Line("private readonly string? _location;"); w.Line("public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null)"); w.Line("{ _value = value; _names = names; _envelope = envelope; _status = status; _location = location; }"); - w.Line("public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http)"); + w.Line($"public async {Fx}System.Threading.Tasks.Task ExecuteAsync(HttpContext http)"); w.Open("{"); - w.Line("var opts = ((Microsoft.Extensions.Options.IOptions)"); - using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + w.Line($"var opts = (({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>)"); + using (w.Hanging()) w.Line($"http.RequestServices.GetService(typeof({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>))!)"); using (w.Hanging()) w.Line(".Value.SerializerOptions;"); - w.Line("var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); + w.Line($"var node = {Fx}System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); w.Line("// The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names."); w.Line("SerializerKeys.StripBody(node, _value, _envelope, opts, _names);"); w.Line("http.Response.StatusCode = _status;"); @@ -1057,7 +1067,7 @@ protected static List AutoSetFields(MetaObject entity, GenConfig c foreach (var f in entity.Fields()) { if (f.AutoSet is not (AUTO_SET_ON_CREATE or AUTO_SET_ON_UPDATE)) continue; - if (NowExprFor(f) is not { } now) continue; // non-temporal @autoSet — skip + if (NowExprFor(f, CSharpNaming.FrameworkPrefix(config)) is not { } now) continue; // non-temporal @autoSet — skip list.Add(new AutoSetField( Nav: CSharpNaming.PropertyName(f, config), NowExpr: now, @@ -1070,13 +1080,14 @@ protected static List AutoSetFields(MetaObject entity, GenConfig c // (ADR-0036 Wave 2: field.timestamp is DateTimeOffset, or DateTime under @localTime; // field.date → DateOnly; field.time → TimeOnly). Fully qualified so no extra using is // needed. Returns null for a non-temporal field. - protected static string? NowExprFor(MetaField field) => + // `fx` is the run's framework prefix (CSharpNaming.FrameworkPrefix). + protected static string? NowExprFor(MetaField field, string fx = "") => CSharpNaming.ScalarForField(field) switch { - "DateTimeOffset" => "System.DateTimeOffset.UtcNow", - "DateTime" => "System.DateTime.Now", // @localTime: naive wall-clock - "DateOnly" => "System.DateOnly.FromDateTime(System.DateTime.UtcNow)", - "TimeOnly" => "System.TimeOnly.FromDateTime(System.DateTime.UtcNow)", + "DateTimeOffset" => $"{fx}System.DateTimeOffset.UtcNow", + "DateTime" => $"{fx}System.DateTime.Now", // @localTime: naive wall-clock + "DateOnly" => $"{fx}System.DateOnly.FromDateTime({fx}System.DateTime.UtcNow)", + "TimeOnly" => $"{fx}System.TimeOnly.FromDateTime({fx}System.DateTime.UtcNow)", _ => null, }; @@ -1107,6 +1118,7 @@ protected static string VoTypeRef(MetaData target, MetaRoot root, GenConfig conf protected static List MapValueObjectFields(MetaObject entity, MetaRoot root, GenConfig config) { + var Fx = CSharpNaming.FrameworkPrefix(config); var list = new List(); foreach (var f in entity.Fields()) { @@ -1117,13 +1129,14 @@ protected static List MapValueObjectFields(MetaObject entity, MetaRo list.Add(new MapVoField( WireKeys: WireKeys(f, config), WireName: f.Name, Nav: CSharpNaming.PropertyName(f, config), - DeserType: $"System.Collections.Generic.Dictionary")); + DeserType: $"{Fx}System.Collections.Generic.Dictionary")); } return list; } protected static List ValueObjectFields(MetaObject entity, MetaRoot root, ColumnNamingStrategy strategy, bool includeNames, GenConfig config) { + var Fx = CSharpNaming.FrameworkPrefix(config); var list = new List(); foreach (var f in entity.Fields()) { @@ -1136,7 +1149,7 @@ protected static List ValueObjectFields(MetaObject entity, MetaRoot roo list.Add(new VoField( WireKeys: WireKeys(f, config), WireName: f.Name, Nav: CSharpNaming.PropertyName(f, config), - DeserType: isArray ? $"System.Collections.Generic.List<{voType}>" : voType, + DeserType: isArray ? $"{Fx}System.Collections.Generic.List<{voType}>" : voType, JsonColumnRef: CSharpNaming.ColumnRef(entity, f, strategy, includeNames, config), IsArray: isArray, Required: f.IsRequired)); @@ -1162,7 +1175,7 @@ protected virtual void WriteKnownFields(CsWriter w, IEnumerable obje var names = objects.SelectMany(o => o.Fields()).Select(f => f.Name) .Distinct(StringComparer.Ordinal).OrderBy(n => n, StringComparer.Ordinal).ToList(); w.Line("// api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400."); - w.Line("private static readonly System.Collections.Generic.HashSet " + KnownFieldsConst + " = new(System.StringComparer.Ordinal)"); + w.Line($"private static readonly {Fx}System.Collections.Generic.HashSet " + KnownFieldsConst + $" = new({Fx}System.StringComparer.Ordinal)"); w.Open("{"); foreach (var n in names) w.Line($"\"{n}\","); w.Close("};"); @@ -1197,10 +1210,10 @@ protected virtual void WriteReadId(CsWriter w, string pkType) => // sets no block; with the block, a limit above maxLimit is 400 limit_too_large, and without it there is no // maximum. `limit=0` is a page of zero rows, as every other port serves it, not "no limit". // The parsed ?offset, skipped (an offset is at most 2^53 - 1; EF's Skip takes an int). - private static void WriteSkip(CsWriter w) + private void WriteSkip(CsWriter w) { w.Line("if (listQuery.Offset is { } __offset && __offset > 0)"); - using (w.Hanging()) w.Line("q = q.Skip((int)System.Math.Min(__offset, int.MaxValue));"); + using (w.Hanging()) w.Line($"q = q.Skip((int){Fx}System.Math.Min(__offset, int.MaxValue));"); } protected virtual void WriteListPage(CsWriter w, ApiPagination? page) @@ -1216,7 +1229,7 @@ protected virtual void WriteListPage(CsWriter w, ApiPagination? page) w.Open("{"); if (page is not null) w.Line($"if (__limit > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); - w.Line("__take = (int)System.Math.Min(__limit, int.MaxValue);"); + w.Line($"__take = (int){Fx}System.Math.Min(__limit, int.MaxValue);"); w.Close("}"); w.Line("q = q.Take(__take);"); } @@ -1259,11 +1272,11 @@ protected virtual void WriteCreateHandler( w.Line($"app.MapPost(prefix + \"{mapPath}\", async (HttpContext http, {ctxType} db) =>"); w.Open("{"); WriteJsonOptsLocal(w); - w.Line("System.Text.Json.JsonDocument __body;"); - w.Line("try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); + w.Line($"{Fx}System.Text.Json.JsonDocument __body;"); + w.Line($"try {{ __body = await {Fx}System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }}"); + w.Line($"catch ({Fx}System.Text.Json.JsonException) {{ return RouteErrors.InvalidJson(); }}"); w.Line("using var __bodyScope = __body;"); - w.Line("if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)"); + w.Line($"if (__body.RootElement.ValueKind != {Fx}System.Text.Json.JsonValueKind.Object)"); using (w.Hanging()) w.Line("return ValidationIssues.Unreadable();"); if (root is not null) WriteUnknownFieldsCheck(w, root, "__body"); w.Line("var __issues = new ValidationIssues();"); @@ -1272,17 +1285,17 @@ protected virtual void WriteCreateHandler( // so a camelCase wire key ("createdAt") matches its PascalCase property ("CreatedAt"). if (requiredKeys.Count > 0) { - w.Line("var __present = new System.Collections.Generic.HashSet(System.StringComparer.OrdinalIgnoreCase);"); + w.Line($"var __present = new {Fx}System.Collections.Generic.HashSet({Fx}System.StringComparer.OrdinalIgnoreCase);"); w.Line("foreach (var __p in __body.RootElement.EnumerateObject())"); - using (w.Hanging()) w.Line("if (__p.Value.ValueKind != System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);"); + using (w.Hanging()) w.Line($"if (__p.Value.ValueKind != {Fx}System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);"); w.Line("foreach (var __req in new[] { " + string.Join(", ", requiredKeys.Select(k => "\"" + k + "\"")) + " })"); using (w.Hanging()) w.Line("if (!__present.Contains(__req)) __issues.AddRequired(__req);"); } // A value that cannot be read (a wrong-shaped VO, a decimal out of range, a malformed date) throws // JsonException: it is listed at its path, and the body cannot be checked further. w.Line($"{cls}? input = null;"); - w.Line("try { input = System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }"); - w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, typeof(" + cls + ")); }"); + w.Line($"try {{ input = {Fx}System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }"); + w.Line($"catch ({Fx}System.Exception __e) {{ __issues.AddReadFailure(__e, typeof(" + cls + ")); }"); w.Line("if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable();"); WriteCreateServerOwned(w, serverOwned); WriteCreateIgnoreDenied(w, deniedNavs); @@ -1349,6 +1362,7 @@ protected virtual void WriteCreateServerOwned(CsWriter w, IReadOnlyList? protected static List ServerOwnedCreateResets( MetaObject entity, MetaRoot root, GenConfig config, MetaField? discField = null, MetaObject? navOwner = null) { + var Fx = CSharpNaming.FrameworkPrefix(config); var list = new List(); if (entity.PrimaryIdentity() is MetaPrimaryIdentity pk && pk.Generation is MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT @@ -1362,7 +1376,7 @@ or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, _ => { })) { var target = ValueObjectNames.Ref(nav.Target, config); - list.Add($"input.{CSharpNaming.Pascal(nav.Name)} = new System.Collections.Generic.List<{target}>();"); + list.Add($"input.{CSharpNaming.Pascal(nav.Name)} = new {Fx}System.Collections.Generic.List<{target}>();"); } return list; } @@ -1409,7 +1423,7 @@ protected virtual void WriteInsertPreserving(CsWriter w, string cls, string dbSe w.Blank(); w.Line("/// Escape hatch: insert without @autoSet stamping (created-at/updated-at"); w.Line("/// written verbatim from ) for import / restore / replication."); - w.Line($"public static async System.Threading.Tasks.Task<{cls}> InsertPreserving({ctxType} db, {cls} input)"); + w.Line($"public static async {Fx}System.Threading.Tasks.Task<{cls}> InsertPreserving({ctxType} db, {cls} input)"); w.Open("{"); w.Line($"db.{dbSet}.Add(input);"); w.Line("await db.SaveChangesAsync();"); @@ -1509,8 +1523,8 @@ protected virtual void WriteDecimalRangeGroup(CsWriter w) protected virtual void WriteJsonOptsLocal(CsWriter w) { - w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + w.Line($"var jsonOpts = (({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>)"); + using (w.Hanging()) w.Line($"http.RequestServices.GetService(typeof({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>))!)"); using (w.Hanging()) w.Line(".Value.SerializerOptions;"); } @@ -1568,7 +1582,7 @@ protected virtual void WritePartialMergeLoop( if (deniedClr.Count > 0) w.Line($"if (__clr is {string.Join(" or ", deniedClr.Select(n => "\"" + n + "\""))}) continue; // @formExclude / credential: not writable"); foreach (var key in deniedKeys) - w.Line($"if (string.Equals(prop.Name, \"{key}\", System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); + w.Line($"if (string.Equals(prop.Name, \"{key}\", {Fx}System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); // Program D — typed value-object arms FIRST (owned-nav columns are invisible to // EF's FindProperty below, so the generic scalar path would silently drop them). // Present value → deserialize + recursive VO validation + assign the CLR nav @@ -1579,9 +1593,9 @@ protected virtual void WritePartialMergeLoop( { var vf = voFields[i]; var v = "__vo" + i; - w.Line($"if ({KeyMatch(vf.WireKeys)} || __clr == \"{vf.Nav}\")"); + w.Line($"if ({KeyMatch(vf.WireKeys, Fx)} || __clr == \"{vf.Nav}\")"); w.Open("{"); - w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Line($"if (prop.Value.ValueKind == {Fx}System.Text.Json.JsonValueKind.Null)"); w.Open("{"); if (vf.Required) { @@ -1600,8 +1614,8 @@ protected virtual void WritePartialMergeLoop( // array column) throws JsonException — return the cross-port 400 rather than an // unhandled 500 (matches every other port + this port's own reference lane). w.Line($"{vf.DeserType} {v};"); - w.Line($"try {{ {v} = System.Text.Json.JsonSerializer.Deserialize<{vf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); - w.Line($"catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{vf.WireName}\"); continue; }}"); + w.Line($"try {{ {v} = {Fx}System.Text.Json.JsonSerializer.Deserialize<{vf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); + w.Line($"catch ({Fx}System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{vf.WireName}\"); continue; }}"); w.Line($"if (!ValueObjectValidator.Collect({v}, __issues, jsonOpts, \"{vf.WireName}\")) continue;"); w.Line($"existing.{vf.Nav} = {v}{(vf.Required ? "!" : "")};"); w.Line("continue;"); @@ -1616,13 +1630,13 @@ protected virtual void WritePartialMergeLoop( { var mf = mapVoFields[i]; var mv = "__map" + i; - w.Line($"if ({KeyMatch(mf.WireKeys)} || __clr == \"{mf.Nav}\")"); + w.Line($"if ({KeyMatch(mf.WireKeys, Fx)} || __clr == \"{mf.Nav}\")"); w.Open("{"); - w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Line($"if (prop.Value.ValueKind == {Fx}System.Text.Json.JsonValueKind.Null)"); w.Line($"{{ existing.{mf.Nav} = null; continue; }}"); w.Line($"{mf.DeserType}? {mv};"); - w.Line($"try {{ {mv} = System.Text.Json.JsonSerializer.Deserialize<{mf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); - w.Line($"catch (System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{mf.WireName}\"); continue; }}"); + w.Line($"try {{ {mv} = {Fx}System.Text.Json.JsonSerializer.Deserialize<{mf.DeserType}>(prop.Value.GetRawText(), jsonOpts); }}"); + w.Line($"catch ({Fx}System.Text.Json.JsonException __e) {{ __issues.AddJson(__e, null, \"{mf.WireName}\"); continue; }}"); w.Line($"if (!ValueObjectValidator.Collect({mv}, __issues, jsonOpts, \"{mf.WireName}\")) continue;"); w.Line($"existing.{mf.Nav} = {mv};"); w.Line("continue;"); @@ -1630,26 +1644,26 @@ protected virtual void WritePartialMergeLoop( } w.Line("var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))"); using (w.Hanging()) w.Line("?? entry.Metadata.FindProperty(prop.Name)"); - using (w.Hanging()) w.Line("?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, System.StringComparison.OrdinalIgnoreCase));"); + using (w.Hanging()) w.Line($"?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, {Fx}System.StringComparison.OrdinalIgnoreCase));"); w.Line("if (target is null) continue;"); w.Line("var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);"); w.Line("if (target.IsPrimaryKey()) continue; // PK is route-authoritative"); if (discProp is not null) { - w.Line($"if (string.Equals(target.Name, \"{discProp}\", System.StringComparison.Ordinal)) continue; // discriminator is immutable"); + w.Line($"if (string.Equals(target.Name, \"{discProp}\", {Fx}System.StringComparison.Ordinal)) continue; // discriminator is immutable"); } // Issue #203 — @autoSet columns are server-owned: an onUpdate column is stamped to // now() (below), an onCreate column is never rewritten. Either way the caller can // never set them via the PATCH/PUT body, so skip any present key. foreach (var nav in autoSetNavs) - w.Line($"if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @autoSet: server-owned"); + w.Line($"if (string.Equals(target.Name, \"{nav}\", {Fx}System.StringComparison.Ordinal)) continue; // @autoSet: server-owned"); // FR-037 R1 — @mutability readOnly / writeOnce are not PATCH-settable. STRIPPED, // never 400'd: the uniform behaviour of every excluded key on this path. Skipping // BEFORE the null branch also covers the FR-035 present-null arm, since clearing a // column is itself a write. foreach (var nav in frozenNavs) - w.Line($"if (string.Equals(target.Name, \"{nav}\", System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable"); - w.Line("if (prop.Value.ValueKind == System.Text.Json.JsonValueKind.Null)"); + w.Line($"if (string.Equals(target.Name, \"{nav}\", {Fx}System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable"); + w.Line($"if (prop.Value.ValueKind == {Fx}System.Text.Json.JsonValueKind.Null)"); w.Open("{"); w.Line("// FR-035 PATCH-2: explicit null clears a nullable column; on a"); w.Line("// NOT-NULL (@required) column it is a 400 (matching the cross-port contract)."); @@ -1657,7 +1671,7 @@ protected virtual void WritePartialMergeLoop( w.Line("entry.CurrentValues[target] = null;"); w.Line("continue;"); w.Close("}"); - w.Line("var clr = System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;"); + w.Line($"var clr = {Fx}System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;"); // ADR-0019 Amendment 1 (W2): a decimal is read from a JSON-number string or a JSON number, // exactly; anything else, or a value decimal cannot hold, is the 400 validation envelope. // `DecimalWire` resolves to the copy the entity generator emits into this namespace (the @@ -1675,10 +1689,10 @@ protected virtual void WritePartialMergeLoop( w.Line("if (!DecimalWire.FitsDeclared(existing.GetType(), target.Name, __dec)) { __issues.Add(\"too_big\", __wire + \" exceeds its declared precision and scale\", __wire); continue; }"); w.Line("__val = __dec;"); w.Close("}"); - w.Line("else if (clr == typeof(System.Collections.Generic.IList))"); + w.Line($"else if (clr == typeof({Fx}System.Collections.Generic.IList))"); w.Open("{"); - w.Line("if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); - w.Line("var __decs = new System.Collections.Generic.List();"); + w.Line($"if (prop.Value.ValueKind != {Fx}System.Text.Json.JsonValueKind.Array) {{ __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }}"); + w.Line($"var __decs = new {Fx}System.Collections.Generic.List();"); w.Line("var __decBad = false;"); w.Line("foreach (var __el in prop.Value.EnumerateArray())"); w.Open("{"); @@ -1697,15 +1711,15 @@ protected virtual void WritePartialMergeLoop( // namespace) and refuse anything else with the validation envelope. if (hasDuration) { - w.Line($"{arm} (clr == typeof(System.TimeSpan))"); + w.Line($"{arm} (clr == typeof({Fx}System.TimeSpan))"); w.Open("{"); w.Line("if (!DurationWire.TryParseElement(prop.Value, out var __dur)) { __issues.Add(\"invalid_type\", __wire + \" is not an ISO-8601 duration\", __wire); continue; }"); w.Line("__val = __dur;"); w.Close("}"); - w.Line("else if (clr == typeof(System.Collections.Generic.IList))"); + w.Line($"else if (clr == typeof({Fx}System.Collections.Generic.IList<{Fx}System.TimeSpan>))"); w.Open("{"); - w.Line("if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) { __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }"); - w.Line("var __durs = new System.Collections.Generic.List();"); + w.Line($"if (prop.Value.ValueKind != {Fx}System.Text.Json.JsonValueKind.Array) {{ __issues.Add(\"invalid_type\", __wire + \" is not an array\", __wire); continue; }}"); + w.Line($"var __durs = new {Fx}System.Collections.Generic.List<{Fx}System.TimeSpan>();"); w.Line("var __durBad = false;"); w.Line("foreach (var __el in prop.Value.EnumerateArray())"); w.Open("{"); @@ -1718,15 +1732,15 @@ protected virtual void WritePartialMergeLoop( } w.Line("else"); w.Open("{"); - w.Line("try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); - w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); + w.Line($"try {{ __val = {Fx}System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }}"); + w.Line($"catch ({Fx}System.Exception __e) {{ __issues.AddReadFailure(__e, clr, __wire); continue; }}"); w.Close("}"); } else { w.Line("object? __val;"); - w.Line("try { __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }"); - w.Line("catch (System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }"); + w.Line($"try {{ __val = {Fx}System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }}"); + w.Line($"catch ({Fx}System.Exception __e) {{ __issues.AddReadFailure(__e, clr, __wire); continue; }}"); } w.Line("// FR-036 A2 — validate the PRESENT, non-null value with the same per-field"); w.Line("// DataAnnotations as create. This validates ONLY the present value (never the"); @@ -1778,7 +1792,7 @@ protected virtual void WriteTphSubtypeRoutes( WriteListQuery(w, subType, subAllowlist, fmS, $"{subCls}SortRules", NullsLargestSort("q", "EF.Property(x!, __sortProp)")); WriteListPage(w, root.Api.Pagination); w.Line("var rows = await q.ToListAsync();"); - w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); + w.Line($"var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", {Fx}System.StringComparison.OrdinalIgnoreCase));"); w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); w.Line($"var total = await EfCoreFilterDispatch.Apply(db.{dbSet}.OfType<{subType}>().AsNoTracking(), listQuery, {subAllowlist}.Rules{fmS}).CountAsync();"); w.Line($"return {OkResult("new { rows, total }", credentials, envelope: true)};"); @@ -1815,21 +1829,21 @@ protected virtual void WriteTphSubtypeRoutes( // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. w.Blank(); - w.Line("async System.Threading.Tasks.Task Update" + subCls + "(HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); + w.Line($"async {Fx}System.Threading.Tasks.Task Update" + subCls + "(HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); w.Open("{"); WriteReadId(w, pkType!); w.Line($"var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); - w.Line("System.Text.Json.JsonDocument body;"); - w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); + w.Line($"{Fx}System.Text.Json.JsonDocument body;"); + w.Line($"try {{ body = await {Fx}System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }}"); + w.Line($"catch ({Fx}System.Text.Json.JsonException) {{ return RouteErrors.InvalidJson(); }}"); w.Line("using var bodyScope = body;"); - w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); + w.Line($"if (body.RootElement.ValueKind != {Fx}System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); WriteUnknownFieldsCheck(w, root, "body"); w.Line("// Configured JSON options (not defaults) so a custom converter — e.g. the"); w.Line("// field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it."); - w.Line("var jsonOpts = ((Microsoft.Extensions.Options.IOptions)"); - using (w.Hanging()) w.Line("http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); + w.Line($"var jsonOpts = (({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>)"); + using (w.Hanging()) w.Line($"http.RequestServices.GetService(typeof({Fx}Microsoft.Extensions.Options.IOptions<{Fx}Microsoft.AspNetCore.Http.Json.JsonOptions>))!)"); using (w.Hanging()) w.Line(".Value.SerializerOptions;"); w.Line("var entry = db.Entry(existing);"); WriteUpdateAutoSet(w, autoSetFields); @@ -1889,7 +1903,7 @@ protected virtual void WriteTphSubtypeRoutes( protected virtual void WriteSaveChanges(CsWriter w) { w.Line("try { await db.SaveChangesAsync(); }"); - w.Line("catch (System.Exception __saveError)"); + w.Line($"catch ({Fx}System.Exception __saveError)"); w.Open("{"); w.Line("if (ConstraintErrors.Classify(__saveError) is { } __constraint)"); using (w.Hanging()) w.Line("return Results.Json("); @@ -1957,7 +1971,7 @@ protected virtual void WriteM2mRoute( // (it just has no relations under this segment): 200 with an empty list, // never 404 and never the sibling's rows. w.Line($"if (!await db.{sourceScope.DbSet}.OfType<{sourceScope.SubtypeClass}>().AnyAsync(x => x.{sourceScope.PkProp} == id))"); - using (w.Hanging()) w.Line($"return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); + using (w.Hanging()) w.Line($"return Results.Ok(new {Fx}System.Collections.Generic.List<{targetCls}>());"); } if (nav.Symmetric) { @@ -1966,7 +1980,7 @@ protected virtual void WriteM2mRoute( using (w.Hanging()) w.Line($".Where(j => EF.Property<{fkType}>(j, \"{srcFkProp}\").Equals(id) || EF.Property<{fkType}>(j, \"{tgtFkProp}\").Equals(id))"); using (w.Hanging()) w.Line($".Select(j => new {{ S = EF.Property<{fkType}>(j, \"{srcFkProp}\"), T = EF.Property<{fkType}>(j, \"{tgtFkProp}\") }})"); using (w.Hanging()) w.Line(".ToListAsync();"); - w.Line($"var relatedIds = new System.Collections.Generic.HashSet<{fkType}>();"); + w.Line($"var relatedIds = new {Fx}System.Collections.Generic.HashSet<{fkType}>();"); w.Line("foreach (var p in pairs)"); using (w.Hanging()) w.Line("relatedIds.Add(p.S.Equals(id) ? p.T : p.S);"); } @@ -1977,7 +1991,7 @@ protected virtual void WriteM2mRoute( using (w.Hanging()) w.Line($".Select(j => EF.Property<{fkType}>(j, \"{tgtFkProp}\"))"); using (w.Hanging()) w.Line(".ToListAsync()).ToHashSet();"); } - w.Line($"if (relatedIds.Count == 0) return Results.Ok(new System.Collections.Generic.List<{targetCls}>());"); + w.Line($"if (relatedIds.Count == 0) return Results.Ok(new {Fx}System.Collections.Generic.List<{targetCls}>());"); w.Line($"var rows = await {targetFrom}.AsNoTracking()"); using (w.Hanging()) w.Line($".Where(t => relatedIds.Contains(EF.Property<{fkType}>(t, \"{targetPk}\")))"); using (w.Hanging()) w.Line(".ToListAsync();"); diff --git a/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs index 17ea41a47..a31717546 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs @@ -45,8 +45,17 @@ public class RulesNamesGenerator : IGenerator /// public Func? Include { get; init; } + /// + /// What this run writes before a framework name (System.…, Microsoft.…): + /// "global::" when package namespaces are on, else "" + /// (). Set when a run starts; a hook or an owned copy that + /// writes a framework name spells it $"{Fx}System.…", so the output is right as written. + /// + protected string Fx { get; set; } = ""; + public virtual IEnumerable Generate(GenContext ctx) { + Fx = CSharpNaming.FrameworkPrefix(ctx.Config); var narrowed = ctx.Narrow(Include); var settings = ctx.Root.Rules; var files = new List(); @@ -126,7 +135,7 @@ protected virtual void WriteLifecycle(CsWriter w, MetaObject entity, Lifecycle l Const(w, "Initial", initial); } w.DocSummary("The states no transition leaves."); - w.Line("public static readonly System.Collections.Generic.IReadOnlyList TerminalStates = " + + w.Line($"public static readonly {Fx}System.Collections.Generic.IReadOnlyList TerminalStates = " + $"[{string.Join(", ", Lifecycles.TerminalStates(l).Select(Literal))}];"); w.Blank(); diff --git a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs index 4124fc9b6..2072aa7ad 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs @@ -154,6 +154,9 @@ private static bool IsSystem(string target) => /// The using block, as printed. protected virtual IEnumerable WriteUsings() => OrderUsings(_usings); + /// The body lines alone, with no header and no using block: what a fragment spliced into another file carries. + public string BodyOnly() => base.Body(); + protected override string Body() { var body = base.Body();