Path: redb-route/redb.Route.Xml/XmlCodeGenerator.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Xml/XmlCodeGenerator.cs ---- using System.Text; using System.Xml.Linq; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; namespace redb.Route.Xml; /// /// The code generator: a .route.xml document printed as the fluent C# it parses into — the /// same traversal as the loader with a different receiver, each element printed by its own /// contribution (the print face), so the parser and the generator cannot drift apart. /// Readable style is for a human migrating off XML (descriptions become comments); machine style /// adds #line directives so diagnostics point back at the XML. The honesty check is /// mechanical: load the XML, run the generated Configure, and compare the two trees with /// RouteDescriber — the tests do exactly that for every shipped example. /// public static class XmlCodeGenerator { /// Generates one RouteBuilder class from a route document. /// The parsed document (with line info for machine style). /// The class name (derive from the file name: orders → OrdersRoutes). /// The namespace of the generated class. /// Readable for migration, machine for a build step. /// The XML path — printed in the header and #line directives. /// Loader options carrying package contributions, if any. public static string Generate( XDocument document, string className, string ns, CodeGenStyle style = CodeGenStyle.Readable, string sourceName = "", XmlRouteLoaderOptions? options = null) { ArgumentNullException.ThrowIfNull(document); ArgumentException.ThrowIfNullOrWhiteSpace(className); ArgumentException.ThrowIfNullOrWhiteSpace(ns); var root = document.Root; if (root is null || root.Name.LocalName != "routes" || root.Name.NamespaceName != XmlRouteLoader.Namespace) throw new InvalidOperationException( $"the generator reads documents."); var registry = ElementRegistry.CreateDefault(options?.Extensions); var resources = sourceName != "" ? new Packaging.RouteProjectResourceResolver(sourceName) : null; var writer = new XmlCodeWriter(registry, style, sourceName, resources); writer.Line($"// "); writer.Line("#nullable enable"); writer.Line("using System;"); writer.Line("using System.Collections.Generic;"); writer.Line("using Microsoft.Extensions.Logging;"); writer.Line("using redb.Route.Abstractions;"); writer.Line("using redb.Route.Aggregation;"); writer.Line("using redb.Route.ControlBus;"); writer.Line("using redb.Route.Core;"); writer.Line("using redb.Route.Transactions;"); writer.Line("using redb.Route.Xml;"); writer.Line("using redb.Route.Xslt;"); // Namespaces the registered package printers ask for (GeneratedUsings face). foreach (var extra in (options?.Extensions ?? []) .SelectMany(c => c.GeneratedUsings).Distinct().Order(StringComparer.Ordinal)) writer.Line($"using {extra};"); writer.BlankLine(); writer.Line($"namespace {ns};"); writer.BlankLine(); writer.Line("/// A generated route builder — see the header for the source file."); writer.Line($"public sealed class {className} : RouteBuilder"); writer.Line("{"); writer.Indent(); writer.Line("protected override void Configure()"); writer.Line("{"); writer.Indent(); // Section order mirrors the loader: beans, container handlers, routes. foreach (var bean in root.Elements().Where(e => e.Name.LocalName == "bean")) PrintBean(bean, writer); foreach (var handler in root.Elements().Where(e => e.Name.LocalName is "onException" or "intercept" or "interceptFrom" or "interceptSendToEndpoint" or "onCompletion")) PrintContainerHandler(handler, writer); foreach (var configuration in root.Elements().Where(e => e.Name.LocalName == XmlRouteLoader.RouteConfigurationElement)) PrintRouteConfiguration(configuration, writer); foreach (var element in root.Elements()) { if (registry.Find(element.Name.LocalName) is { Kind: XmlElementKind.TopLevel } topLevel) topLevel.Print(element, writer); } foreach (var route in root.Elements().Where(e => e.Name.LocalName == "route")) PrintRoute(route, writer); writer.Outdent(); writer.Line("}"); writer.Outdent(); writer.Line("}"); if (style == CodeGenStyle.Machine) writer.Line("#line default"); return writer.Text; } private static void PrintBean(XElement bean, XmlCodeWriter writer) { var name = bean.Attribute("name")?.Value ?? ""; var problems = new List(); var declaration = BeanModel.Parse(bean, (at, message) => problems.Add(at is System.Xml.IXmlLineInfo line && line.HasLineInfo() ? $"({line.LineNumber},{line.LinePosition}): {message}" : message)); if (declaration is null) throw new InvalidOperationException($"bean '{name}': {string.Join("; ", problems)}"); writer.MapTo(bean); writer.Line($"Context!.AddToRegistry({XmlCodeWriter.Str(name)}, {BeanExpression(declaration)});"); } /// /// A bean as a XmlBeans.Create(...) expression. Registrations print in document order, /// so an XmlBeans.Ref finds what the XML section would have found at the same point. /// private static string BeanExpression(BeanDeclaration bean) { var args = new StringBuilder(); args.Append("XmlBeans.Create(Context!, ").Append(XmlCodeWriter.Str(bean.TypeName)); args.Append(", [").Append(string.Join(", ", bean.ConstructorArgs.Select(a => ValueExpression(a.Value)))).Append(']'); var properties = bean.Properties.Select(p => $"({XmlCodeWriter.Str(p.Key)}, {ValueExpression(p.Value)})"); args.Append(", [").Append(string.Join(", ", properties)).Append(']'); if (bean.FactoryMethod is not null) args.Append(", ").Append(XmlCodeWriter.Str(bean.FactoryMethod)); if (bean.TypedArguments) args.Append(", argumentTypes: [").Append(string.Join(", ", bean.ConstructorArgs.Select(a => XmlCodeWriter.Str(a.TypeName!)))).Append(']'); return args.Append(')').ToString(); } private static string ValueExpression(BeanValue value) => value switch { ScalarBeanValue scalar => XmlCodeWriter.Str(scalar.Text), RefBeanValue reference => $"XmlBeans.Ref(Context!, {XmlCodeWriter.Str(reference.Bean)})", NestedBeanValue nested => BeanExpression(nested.Bean), ListBeanValue list => $"XmlBeans.List(Context!, {(list.ElementTypeName is null ? "null" : XmlCodeWriter.Str(list.ElementTypeName))}, " + $"[{string.Join(", ", list.Items.Select(ValueExpression))}])", _ => throw new InvalidOperationException($"unhandled bean value {value.GetType().Name}."), }; private static void PrintContainerHandler(XElement handler, XmlCodeWriter writer) { // Builder-level: the same shapes as the route level, statements on a fresh variable, // no End call (a builder-level definition has no parent to return to). switch (handler.Name.LocalName) { case "onException": { var types = (handler.Attribute("exceptions")?.Value ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); writer.PushRoot($"OnException({string.Join(", ", types.Select(XmlCodeWriter.TypeRef))})", handler, "handler"); if (handler.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); CoreElements.CoreContributions.PrintOnException(handler, writer); writer.PopReceiver(); break; } case "intercept": case "interceptFrom": case "interceptSendToEndpoint": { var verb = char.ToUpperInvariant(handler.Name.LocalName[0]) + handler.Name.LocalName[1..]; var arg = handler.Attribute("uri")?.Value is { } uri ? XmlCodeWriter.Str(uri) : ""; writer.PushRoot($"{verb}({arg})", handler, "handler"); if (handler.Attribute("skipSendToOriginalEndpoint")?.Value == "true") writer.Config("SkipSendToOriginalEndpoint()"); CoreElements.CoreContributions.PrintWhenConditionThenSteps(handler, writer); writer.PopReceiver(); break; } default: { writer.PushRoot("OnCompletion()", handler, "handler"); if (handler.Attribute("onCompleteOnly")?.Value == "true") writer.Config("OnCompleteOnly()"); if (handler.Attribute("onFailureOnly")?.Value == "true") writer.Config("OnFailureOnly()"); if (handler.Attribute("modeBeforeConsumer")?.Value == "true") writer.Config("ModeBeforeConsumer()"); if (handler.Attribute("parallelProcessing")?.Value == "true") writer.Config("ParallelProcessing()"); if (handler.Attribute("executorService")?.Value is { } pool) writer.Config($"ExecutorService({XmlCodeWriter.Str(pool)})"); CoreElements.CoreContributions.PrintWhenConditionThenSteps(handler, writer); writer.PopReceiver(); break; } } } /// /// A route configuration: one variable for the configuration, then each <onException> as statements /// on a variable of its own, the shapes of a builder-level handler. /// private static void PrintRouteConfiguration(XElement configuration, XmlCodeWriter writer) { var id = configuration.Attribute("id")?.Value is { Length: > 0 } value ? XmlCodeWriter.Str(value) : ""; var name = writer.PushRoot($"RouteConfiguration({id})", configuration, "configuration"); writer.PopReceiver(); foreach (var handler in configuration.Elements().Where(e => e.Name.LocalName == "onException")) { var types = (handler.Attribute("exceptions")?.Value ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); writer.PushRoot($"{name}.OnException({string.Join(", ", types.Select(XmlCodeWriter.TypeRef))})", handler, "handler"); if (handler.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); CoreElements.CoreContributions.PrintOnException(handler, writer); writer.PopReceiver(); } } private static void PrintRoute(XElement route, XmlCodeWriter writer) { // enabled= is a load-time decision from live configuration; generated code has no // configuration at generation time, so the attribute is refused rather than mistranslated. if (route.Attribute("enabled") is { } enabled) { if (bool.TryParse(enabled.Value, out var isEnabled)) { if (!isEnabled) return; } else { throw new NotSupportedException( $"route '{route.Attribute("id")?.Value}': enabled=\"{enabled.Value}\" resolves from configuration " + "at load time — decide it before generating, or keep this route in XML."); } } writer.BlankLine(); if (writer.Style == CodeGenStyle.Readable && route.Attribute("description")?.Value is { Length: > 0 } comment) writer.Line($"// {comment}"); var from = route.Elements().First(e => e.Name.LocalName == "from"); var fromUri = from.Attribute("uri")?.Value is { } uri ? XmlCodeWriter.Str(uri) : XmlCodeWriter.Str(StructuredEndpoint.NormalizeForPrint(from.Elements().First())); writer.PushRoot($"From({fromUri})", route, "route"); if (route.Attribute("id")?.Value is { Length: > 0 } id) writer.Config($"RouteId({XmlCodeWriter.Str(id)})"); if (route.Attribute("description")?.Value is { Length: > 0 } description) writer.Config($"Description({XmlCodeWriter.Str(description)})"); if (route.Attribute("autoStart")?.Value is { } autoStart) writer.Config($"AutoStart({XmlCodeWriter.Bool(bool.Parse(autoStart))})"); if (route.Attribute("cluster")?.Value is { } cluster) writer.Config($"Cluster({XmlCodeWriter.Bool(bool.Parse(cluster))})"); if (route.Attribute("messageHistory")?.Value is { } history) writer.Config($"MessageHistory({XmlCodeWriter.Bool(bool.Parse(history))})"); if (route.Attribute("tracing")?.Value is { } tracing) writer.Config($"Tracing({XmlCodeWriter.Bool(bool.Parse(tracing))})"); if (route.Attribute("processingTimeout")?.Value is { } timeout) writer.Config($"ProcessingTimeout({XmlCodeWriter.Ts(TimeSpan.Parse(timeout, System.Globalization.CultureInfo.InvariantCulture))})"); if (route.Attribute("routePolicy")?.Value is { Length: > 0 } policy) writer.Config($"RoutePolicy({XmlCodeWriter.Str(policy)})"); if (route.Attribute("routeConfigurationId")?.Value is { Length: > 0 } configurations) writer.Config($"RouteConfigurationId({XmlCodeWriter.Str(configurations)})"); foreach (var step in route.Elements().Where(e => e.Name.LocalName != "from")) writer.PrintStep(step); writer.PopReceiver(); } } /// /// The runtime half of generated bean registrations: builds an instance the same way the /// <bean> section does — the registered IBeanTypeResolver decides what the /// type name means, and every value binds through the same factory as the XML section. /// public static class XmlBeans { /// /// Creates a bean instance for a generated registration. A value is a string (placeholders /// resolved, then converted to the target type the way a URI option is), an object built by a /// nested bean or taken by (assigned as it is), or a /// (built into the target's collection shape). names a public /// static creator to call instead of a constructor, with the constructor arguments as its parameters. /// — <constructorArg type=…> — names the parameter types: /// the constructor or factory method is then the one with exactly that signature. /// public static object Create( IRouteContext context, string typeName, object?[] constructorArgs, (string Key, object? Value)[] properties, string? factoryMethod = null, string[]? argumentTypes = null) { ArgumentNullException.ThrowIfNull(context); var resolver = context.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName) ?? throw new InvalidOperationException($"bean type '{typeName}' was not found in the loaded assemblies."); var parameterTypes = argumentTypes?.Select(name => resolver.Resolve(name) ?? throw new InvalidOperationException($"constructor argument type '{name}' was not found in the loaded assemblies.")).ToList(); Func resolve = context is RouteContext live ? live.ResolvePlaceholders : text => text; var instance = BeanFactory.Instantiate( type, constructorArgs, parameterTypes, factoryMethod, context.GetServiceProvider() ?? EmptyProvider.Instance, resolve); foreach (var (key, value) in properties) BeanFactory.Assign(instance, key, value, resolve); return instance; } /// /// A registered bean for a ref: it must already be in the registry — generated /// registrations run in document order, exactly as the XML section builds them. /// public static object Ref(IRouteContext context, string name) { ArgumentNullException.ThrowIfNull(context); return context.GetFromRegistry(name) ?? throw new InvalidOperationException( $"bean reference '{name}' names nothing registered so far — declare it before the bean that refers to it."); } /// /// A <list> for : the items as raw values, the element type /// named by of= (null when the target property or parameter supplies it). /// public static object List(IRouteContext context, string? elementType, object?[] items) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(items); Type? type = null; if (elementType is not null) { var resolver = context.GetService() ?? DefaultBeanTypeResolver.Instance; type = resolver.Resolve(elementType) ?? throw new InvalidOperationException($"list element type '{elementType}' was not found in the loaded assemblies."); } return new BeanListValue(type, items); } private sealed class EmptyProvider : IServiceProvider { public static readonly EmptyProvider Instance = new(); public object? GetService(Type serviceType) => null; } }