| | | 1 | | // Copyright (c) NexusLabs. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text; |
| | | 6 | | |
| | | 7 | | using NexusLabs.Needlr.Generators.Models; |
| | | 8 | | |
| | | 9 | | namespace NexusLabs.Needlr.Generators.CodeGen; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Generates IValidateOptions implementations for options classes with validation. |
| | | 13 | | /// </summary> |
| | | 14 | | internal static class OptionsCodeGenerator |
| | | 15 | | { |
| | | 16 | | internal static string GenerateOptionsValidatorsSource(IReadOnlyList<DiscoveredOptions> optionsWithValidators, strin |
| | | 17 | | { |
| | 18 | 18 | | var builder = new StringBuilder(); |
| | 18 | 19 | | var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblyName); |
| | | 20 | | |
| | 18 | 21 | | breadcrumbs.WriteFileHeader(builder, assemblyName, "Needlr Generated Options Validators"); |
| | 18 | 22 | | builder.AppendLine("#nullable enable"); |
| | 18 | 23 | | builder.AppendLine(); |
| | 18 | 24 | | builder.AppendLine("using System.Collections.Generic;"); |
| | 18 | 25 | | builder.AppendLine("using System.Linq;"); |
| | 18 | 26 | | builder.AppendLine(); |
| | 18 | 27 | | builder.AppendLine("using Microsoft.Extensions.Options;"); |
| | 18 | 28 | | builder.AppendLine(); |
| | 18 | 29 | | builder.AppendLine("using NexusLabs.Needlr.Generators;"); |
| | 18 | 30 | | builder.AppendLine(); |
| | 18 | 31 | | builder.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 18 | 32 | | builder.AppendLine(); |
| | | 33 | | |
| | | 34 | | // Generate validator class for each options type with a validator method |
| | 72 | 35 | | foreach (var opt in optionsWithValidators) |
| | | 36 | | { |
| | 18 | 37 | | if (!opt.HasValidatorMethod || opt.ValidatorMethod == null) |
| | | 38 | | continue; |
| | | 39 | | |
| | 18 | 40 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(opt.TypeName); |
| | 18 | 41 | | var validatorClassName = shortTypeName + "Validator"; |
| | | 42 | | |
| | | 43 | | // Determine which type has the validator method |
| | 18 | 44 | | var validatorTargetType = opt.HasExternalValidator ? opt.ValidatorTypeName! : opt.TypeName; |
| | | 45 | | |
| | 18 | 46 | | builder.AppendLine("/// <summary>"); |
| | 18 | 47 | | builder.AppendLine($"/// Generated validator for <see cref=\"{opt.TypeName}\"/>."); |
| | 18 | 48 | | if (opt.HasExternalValidator) |
| | | 49 | | { |
| | 6 | 50 | | builder.AppendLine($"/// Uses external validator <see cref=\"{validatorTargetType}\"/>."); |
| | | 51 | | } |
| | | 52 | | else |
| | | 53 | | { |
| | 12 | 54 | | builder.AppendLine("/// Calls the validation method on the options instance."); |
| | | 55 | | } |
| | 18 | 56 | | builder.AppendLine("/// </summary>"); |
| | 18 | 57 | | builder.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.Generators\", |
| | 18 | 58 | | builder.AppendLine($"public sealed class {validatorClassName} : IValidateOptions<{opt.TypeName}>"); |
| | 18 | 59 | | builder.AppendLine("{"); |
| | | 60 | | |
| | 18 | 61 | | if (opt.HasExternalValidator && !opt.ValidatorMethod.Value.IsStatic) |
| | | 62 | | { |
| | | 63 | | // External validator needs to be injected for instance methods |
| | 4 | 64 | | builder.AppendLine($" private readonly {validatorTargetType} _validator;"); |
| | 4 | 65 | | builder.AppendLine(); |
| | 4 | 66 | | builder.AppendLine($" public {validatorClassName}({validatorTargetType} validator)"); |
| | 4 | 67 | | builder.AppendLine(" {"); |
| | 4 | 68 | | builder.AppendLine(" _validator = validator;"); |
| | 4 | 69 | | builder.AppendLine(" }"); |
| | 4 | 70 | | builder.AppendLine(); |
| | | 71 | | } |
| | | 72 | | |
| | 18 | 73 | | builder.AppendLine($" public ValidateOptionsResult Validate(string? name, {opt.TypeName} options)"); |
| | 18 | 74 | | builder.AppendLine(" {"); |
| | 18 | 75 | | builder.AppendLine(" var errors = new List<string>();"); |
| | | 76 | | |
| | | 77 | | // Generate the foreach to iterate errors |
| | | 78 | | string validationCall; |
| | 18 | 79 | | if (opt.HasExternalValidator) |
| | | 80 | | { |
| | 6 | 81 | | if (opt.ValidatorMethod.Value.IsStatic) |
| | | 82 | | { |
| | | 83 | | // Static method on external type: ExternalValidator.ValidateMethod(options) |
| | 2 | 84 | | validationCall = $"{validatorTargetType}.{opt.ValidatorMethod.Value.MethodName}(options)"; |
| | | 85 | | } |
| | | 86 | | else |
| | | 87 | | { |
| | | 88 | | // Instance method on external type: _validator.ValidateMethod(options) |
| | 4 | 89 | | validationCall = $"_validator.{opt.ValidatorMethod.Value.MethodName}(options)"; |
| | | 90 | | } |
| | | 91 | | } |
| | 12 | 92 | | else if (opt.ValidatorMethod.Value.IsStatic) |
| | | 93 | | { |
| | | 94 | | // Static method on options type: OptionsType.ValidateMethod(options) |
| | 1 | 95 | | validationCall = $"{opt.TypeName}.{opt.ValidatorMethod.Value.MethodName}(options)"; |
| | | 96 | | } |
| | | 97 | | else |
| | | 98 | | { |
| | | 99 | | // Instance method on options type: options.ValidateMethod() |
| | 11 | 100 | | validationCall = $"options.{opt.ValidatorMethod.Value.MethodName}()"; |
| | | 101 | | } |
| | | 102 | | |
| | 18 | 103 | | builder.AppendLine($" foreach (var error in {validationCall})"); |
| | 18 | 104 | | builder.AppendLine(" {"); |
| | 18 | 105 | | builder.AppendLine(" // Support both string and ValidationError (ValidationError.ToString() retur |
| | 18 | 106 | | builder.AppendLine(" var errorMessage = error?.ToString() ?? string.Empty;"); |
| | 18 | 107 | | builder.AppendLine(" if (!string.IsNullOrEmpty(errorMessage))"); |
| | 18 | 108 | | builder.AppendLine(" {"); |
| | 18 | 109 | | builder.AppendLine(" errors.Add(errorMessage);"); |
| | 18 | 110 | | builder.AppendLine(" }"); |
| | 18 | 111 | | builder.AppendLine(" }"); |
| | 18 | 112 | | builder.AppendLine(); |
| | 18 | 113 | | builder.AppendLine(" if (errors.Count > 0)"); |
| | 18 | 114 | | builder.AppendLine(" {"); |
| | 18 | 115 | | builder.AppendLine($" return ValidateOptionsResult.Fail(errors);"); |
| | 18 | 116 | | builder.AppendLine(" }"); |
| | 18 | 117 | | builder.AppendLine(); |
| | 18 | 118 | | builder.AppendLine(" return ValidateOptionsResult.Success;"); |
| | 18 | 119 | | builder.AppendLine(" }"); |
| | 18 | 120 | | builder.AppendLine("}"); |
| | 18 | 121 | | builder.AppendLine(); |
| | | 122 | | } |
| | | 123 | | |
| | 18 | 124 | | return builder.ToString(); |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Generates IValidateOptions implementations for options classes with DataAnnotation attributes. |
| | | 129 | | /// This enables AOT-compatible validation without reflection. |
| | | 130 | | /// </summary> |
| | | 131 | | internal static string GenerateDataAnnotationsValidatorsSource( |
| | | 132 | | IReadOnlyList<DiscoveredOptions> optionsWithDataAnnotations, |
| | | 133 | | string assemblyName, |
| | | 134 | | BreadcrumbWriter breadcrumbs, |
| | | 135 | | string? projectDirectory) |
| | | 136 | | { |
| | 18 | 137 | | var builder = new StringBuilder(); |
| | 18 | 138 | | var safeAssemblyName = GeneratorHelpers.SanitizeIdentifier(assemblyName); |
| | | 139 | | |
| | 18 | 140 | | breadcrumbs.WriteFileHeader(builder, assemblyName, "Needlr Generated DataAnnotations Validators"); |
| | 18 | 141 | | builder.AppendLine("#nullable enable"); |
| | 18 | 142 | | builder.AppendLine(); |
| | 18 | 143 | | builder.AppendLine("using System.Collections.Generic;"); |
| | 18 | 144 | | builder.AppendLine("using System.Text.RegularExpressions;"); |
| | 18 | 145 | | builder.AppendLine(); |
| | 18 | 146 | | builder.AppendLine("using Microsoft.Extensions.Options;"); |
| | 18 | 147 | | builder.AppendLine(); |
| | 18 | 148 | | builder.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 18 | 149 | | builder.AppendLine(); |
| | | 150 | | |
| | 74 | 151 | | foreach (var opt in optionsWithDataAnnotations) |
| | | 152 | | { |
| | 19 | 153 | | if (!opt.HasDataAnnotations) |
| | | 154 | | continue; |
| | | 155 | | |
| | 19 | 156 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(opt.TypeName); |
| | 19 | 157 | | var validatorClassName = shortTypeName + "DataAnnotationsValidator"; |
| | | 158 | | |
| | 19 | 159 | | builder.AppendLine("/// <summary>"); |
| | 19 | 160 | | builder.AppendLine($"/// Generated DataAnnotations validator for <see cref=\"{opt.TypeName}\"/>."); |
| | 19 | 161 | | builder.AppendLine("/// Validates DataAnnotation attributes without reflection (AOT-compatible)."); |
| | 19 | 162 | | builder.AppendLine("/// </summary>"); |
| | 19 | 163 | | builder.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.Generators\", |
| | 19 | 164 | | builder.AppendLine($"public sealed class {validatorClassName} : IValidateOptions<{opt.TypeName}>"); |
| | 19 | 165 | | builder.AppendLine("{"); |
| | 19 | 166 | | builder.AppendLine($" public ValidateOptionsResult Validate(string? name, {opt.TypeName} options)"); |
| | 19 | 167 | | builder.AppendLine(" {"); |
| | 19 | 168 | | builder.AppendLine(" var errors = new List<string>();"); |
| | 19 | 169 | | builder.AppendLine(); |
| | | 170 | | |
| | | 171 | | // Generate validation for each property with DataAnnotations |
| | 82 | 172 | | foreach (var prop in opt.Properties) |
| | | 173 | | { |
| | 22 | 174 | | if (!prop.HasDataAnnotations) |
| | | 175 | | continue; |
| | | 176 | | |
| | 90 | 177 | | foreach (var annotation in prop.DataAnnotations) |
| | | 178 | | { |
| | 23 | 179 | | GenerateDataAnnotationValidation(builder, prop, annotation); |
| | | 180 | | } |
| | | 181 | | } |
| | | 182 | | |
| | 19 | 183 | | builder.AppendLine(" if (errors.Count > 0)"); |
| | 19 | 184 | | builder.AppendLine(" {"); |
| | 19 | 185 | | builder.AppendLine(" return ValidateOptionsResult.Fail(errors);"); |
| | 19 | 186 | | builder.AppendLine(" }"); |
| | 19 | 187 | | builder.AppendLine(); |
| | 19 | 188 | | builder.AppendLine(" return ValidateOptionsResult.Success;"); |
| | 19 | 189 | | builder.AppendLine(" }"); |
| | 19 | 190 | | builder.AppendLine("}"); |
| | 19 | 191 | | builder.AppendLine(); |
| | | 192 | | } |
| | | 193 | | |
| | 18 | 194 | | return builder.ToString(); |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | private static void GenerateDataAnnotationValidation(StringBuilder builder, OptionsPropertyInfo prop, DataAnnotation |
| | | 198 | | { |
| | 23 | 199 | | var propName = prop.Name; |
| | 23 | 200 | | var errorMsg = annotation.ErrorMessage; |
| | | 201 | | |
| | 23 | 202 | | switch (annotation.Kind) |
| | | 203 | | { |
| | | 204 | | case DataAnnotationKind.Required: |
| | 12 | 205 | | var requiredError = errorMsg ?? $"The {propName} field is required."; |
| | 12 | 206 | | if (prop.TypeName.Contains("string")) |
| | | 207 | | { |
| | 12 | 208 | | builder.AppendLine($" if (string.IsNullOrEmpty(options.{propName}))"); |
| | | 209 | | } |
| | | 210 | | else |
| | | 211 | | { |
| | 0 | 212 | | builder.AppendLine($" if (options.{propName} == null)"); |
| | | 213 | | } |
| | 12 | 214 | | builder.AppendLine(" {"); |
| | 12 | 215 | | builder.AppendLine($" errors.Add(\"{EscapeString(requiredError)}\");"); |
| | 12 | 216 | | builder.AppendLine(" }"); |
| | 12 | 217 | | builder.AppendLine(); |
| | 12 | 218 | | break; |
| | | 219 | | |
| | | 220 | | case DataAnnotationKind.Range: |
| | 6 | 221 | | var min = annotation.Minimum; |
| | 6 | 222 | | var max = annotation.Maximum; |
| | 6 | 223 | | var rangeError = errorMsg ?? $"The field {propName} must be between {min} and {max}."; |
| | 6 | 224 | | builder.AppendLine($" if (options.{propName} < {min} || options.{propName} > {max})"); |
| | 6 | 225 | | builder.AppendLine(" {"); |
| | 6 | 226 | | builder.AppendLine($" errors.Add(\"{EscapeString(rangeError)}\");"); |
| | 6 | 227 | | builder.AppendLine(" }"); |
| | 6 | 228 | | builder.AppendLine(); |
| | 6 | 229 | | break; |
| | | 230 | | |
| | | 231 | | case DataAnnotationKind.StringLength: |
| | 2 | 232 | | var maxLen = annotation.Maximum; |
| | 2 | 233 | | var minLen = annotation.MinimumLength ?? 0; |
| | 2 | 234 | | var strLenError = errorMsg ?? $"The field {propName} must be a string with a maximum length of {maxLen}. |
| | 2 | 235 | | if (minLen > 0) |
| | | 236 | | { |
| | 2 | 237 | | builder.AppendLine($" if (options.{propName}?.Length < {minLen} || options.{propName}?.Length |
| | | 238 | | } |
| | | 239 | | else |
| | | 240 | | { |
| | 0 | 241 | | builder.AppendLine($" if (options.{propName}?.Length > {maxLen})"); |
| | | 242 | | } |
| | 2 | 243 | | builder.AppendLine(" {"); |
| | 2 | 244 | | builder.AppendLine($" errors.Add(\"{EscapeString(strLenError)}\");"); |
| | 2 | 245 | | builder.AppendLine(" }"); |
| | 2 | 246 | | builder.AppendLine(); |
| | 2 | 247 | | break; |
| | | 248 | | |
| | | 249 | | case DataAnnotationKind.MinLength: |
| | 1 | 250 | | var minLenVal = annotation.MinimumLength ?? 0; |
| | 1 | 251 | | var minLenError = errorMsg ?? $"The field {propName} must have a minimum length of {minLenVal}."; |
| | 1 | 252 | | builder.AppendLine($" if (options.{propName}?.Length < {minLenVal})"); |
| | 1 | 253 | | builder.AppendLine(" {"); |
| | 1 | 254 | | builder.AppendLine($" errors.Add(\"{EscapeString(minLenError)}\");"); |
| | 1 | 255 | | builder.AppendLine(" }"); |
| | 1 | 256 | | builder.AppendLine(); |
| | 1 | 257 | | break; |
| | | 258 | | |
| | | 259 | | case DataAnnotationKind.MaxLength: |
| | 1 | 260 | | var maxLenVal = annotation.Maximum; |
| | 1 | 261 | | var maxLenError = errorMsg ?? $"The field {propName} must have a maximum length of {maxLenVal}."; |
| | 1 | 262 | | builder.AppendLine($" if (options.{propName}?.Length > {maxLenVal})"); |
| | 1 | 263 | | builder.AppendLine(" {"); |
| | 1 | 264 | | builder.AppendLine($" errors.Add(\"{EscapeString(maxLenError)}\");"); |
| | 1 | 265 | | builder.AppendLine(" }"); |
| | 1 | 266 | | builder.AppendLine(); |
| | 1 | 267 | | break; |
| | | 268 | | |
| | | 269 | | case DataAnnotationKind.RegularExpression: |
| | 1 | 270 | | var pattern = annotation.Pattern ?? ""; |
| | 1 | 271 | | var regexError = errorMsg ?? $"The field {propName} must match the regular expression '{pattern}'."; |
| | | 272 | | // Use verbatim string for pattern |
| | 1 | 273 | | builder.AppendLine($" if (options.{propName} != null && !Regex.IsMatch(options.{propName}, @\"{Es |
| | 1 | 274 | | builder.AppendLine(" {"); |
| | 1 | 275 | | builder.AppendLine($" errors.Add(\"{EscapeString(regexError)}\");"); |
| | 1 | 276 | | builder.AppendLine(" }"); |
| | 1 | 277 | | builder.AppendLine(); |
| | 1 | 278 | | break; |
| | | 279 | | |
| | | 280 | | case DataAnnotationKind.EmailAddress: |
| | 0 | 281 | | var emailError = errorMsg ?? $"The {propName} field is not a valid e-mail address."; |
| | 0 | 282 | | builder.AppendLine($" if (!string.IsNullOrEmpty(options.{propName}) && !Regex.IsMatch(options.{pr |
| | 0 | 283 | | builder.AppendLine(" {"); |
| | 0 | 284 | | builder.AppendLine($" errors.Add(\"{EscapeString(emailError)}\");"); |
| | 0 | 285 | | builder.AppendLine(" }"); |
| | 0 | 286 | | builder.AppendLine(); |
| | 0 | 287 | | break; |
| | | 288 | | |
| | | 289 | | case DataAnnotationKind.Url: |
| | 0 | 290 | | var urlError = errorMsg ?? $"The {propName} field is not a valid fully-qualified http, https, or ftp URL |
| | 0 | 291 | | builder.AppendLine($" if (!string.IsNullOrEmpty(options.{propName}) && !global::System.Uri.TryCre |
| | 0 | 292 | | builder.AppendLine(" {"); |
| | 0 | 293 | | builder.AppendLine($" errors.Add(\"{EscapeString(urlError)}\");"); |
| | 0 | 294 | | builder.AppendLine(" }"); |
| | 0 | 295 | | builder.AppendLine(); |
| | 0 | 296 | | break; |
| | | 297 | | |
| | | 298 | | case DataAnnotationKind.Phone: |
| | 0 | 299 | | var phoneError = errorMsg ?? $"The {propName} field is not a valid phone number."; |
| | 0 | 300 | | builder.AppendLine($" if (!string.IsNullOrEmpty(options.{propName}) && !Regex.IsMatch(options.{pr |
| | 0 | 301 | | builder.AppendLine(" {"); |
| | 0 | 302 | | builder.AppendLine($" errors.Add(\"{EscapeString(phoneError)}\");"); |
| | 0 | 303 | | builder.AppendLine(" }"); |
| | 0 | 304 | | builder.AppendLine(); |
| | | 305 | | break; |
| | | 306 | | |
| | | 307 | | case DataAnnotationKind.Unsupported: |
| | | 308 | | // Skip unsupported - will be handled by analyzer |
| | | 309 | | break; |
| | | 310 | | } |
| | 0 | 311 | | } |
| | | 312 | | |
| | | 313 | | private static string EscapeString(string s) |
| | | 314 | | { |
| | 23 | 315 | | return s.Replace("\\", "\\\\").Replace("\"", "\\\""); |
| | | 316 | | } |
| | | 317 | | |
| | | 318 | | private static string EscapeVerbatimString(string s) |
| | | 319 | | { |
| | 1 | 320 | | return s.Replace("\"", "\"\""); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | /// <summary> |
| | | 324 | | /// Generates parameterless constructors for partial positional records with [Options]. |
| | | 325 | | /// This enables configuration binding which requires a parameterless constructor. |
| | | 326 | | /// </summary> |
| | | 327 | | internal static string GeneratePositionalRecordConstructorsSource( |
| | | 328 | | IReadOnlyList<DiscoveredOptions> optionsNeedingConstructors, |
| | | 329 | | string assemblyName, |
| | | 330 | | BreadcrumbWriter breadcrumbs, |
| | | 331 | | string? projectDirectory) |
| | | 332 | | { |
| | 7 | 333 | | var builder = new StringBuilder(); |
| | | 334 | | |
| | 7 | 335 | | breadcrumbs.WriteFileHeader(builder, assemblyName, "Needlr Generated Options Constructors"); |
| | 7 | 336 | | builder.AppendLine("#nullable enable"); |
| | 7 | 337 | | builder.AppendLine(); |
| | | 338 | | |
| | | 339 | | // Group by namespace for cleaner output |
| | 7 | 340 | | var byNamespace = optionsNeedingConstructors |
| | 7 | 341 | | .Where(o => o.PositionalRecordInfo != null) |
| | 7 | 342 | | .GroupBy(o => o.PositionalRecordInfo!.Value.ContainingNamespace) |
| | 14 | 343 | | .OrderBy(g => g.Key); |
| | | 344 | | |
| | 28 | 345 | | foreach (var namespaceGroup in byNamespace) |
| | | 346 | | { |
| | 7 | 347 | | var namespaceName = namespaceGroup.Key; |
| | | 348 | | |
| | 7 | 349 | | if (!string.IsNullOrEmpty(namespaceName)) |
| | | 350 | | { |
| | 7 | 351 | | builder.AppendLine($"namespace {namespaceName};"); |
| | 7 | 352 | | builder.AppendLine(); |
| | | 353 | | } |
| | | 354 | | |
| | 28 | 355 | | foreach (var opt in namespaceGroup) |
| | | 356 | | { |
| | 7 | 357 | | var info = opt.PositionalRecordInfo!.Value; |
| | | 358 | | |
| | 7 | 359 | | builder.AppendLine("/// <summary>"); |
| | 7 | 360 | | builder.AppendLine($"/// Generated parameterless constructor for configuration binding."); |
| | 7 | 361 | | builder.AppendLine($"/// Chains to primary constructor with default values."); |
| | 7 | 362 | | builder.AppendLine("/// </summary>"); |
| | 7 | 363 | | builder.AppendLine($"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.Generato |
| | 7 | 364 | | builder.AppendLine($"public partial record {info.ShortTypeName}"); |
| | 7 | 365 | | builder.AppendLine("{"); |
| | | 366 | | |
| | | 367 | | // Build the constructor call with default values for each parameter |
| | 7 | 368 | | var defaultArgs = new List<string>(); |
| | 52 | 369 | | foreach (var param in info.Parameters) |
| | | 370 | | { |
| | 19 | 371 | | var defaultValue = GetDefaultValueForType(param.TypeName); |
| | 19 | 372 | | defaultArgs.Add(defaultValue); |
| | | 373 | | } |
| | | 374 | | |
| | 7 | 375 | | var argsString = string.Join(", ", defaultArgs); |
| | 7 | 376 | | builder.AppendLine($" public {info.ShortTypeName}() : this({argsString}) {{ }}"); |
| | 7 | 377 | | builder.AppendLine("}"); |
| | 7 | 378 | | builder.AppendLine(); |
| | | 379 | | } |
| | | 380 | | } |
| | | 381 | | |
| | 7 | 382 | | return builder.ToString(); |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | /// <summary> |
| | | 386 | | /// Gets the default value expression for a given type. |
| | | 387 | | /// </summary> |
| | | 388 | | private static string GetDefaultValueForType(string fullyQualifiedTypeName) |
| | | 389 | | { |
| | | 390 | | // Handle common types with user-friendly defaults |
| | 19 | 391 | | return fullyQualifiedTypeName switch |
| | 19 | 392 | | { |
| | 7 | 393 | | "global::System.String" or "string" => "string.Empty", |
| | 4 | 394 | | "global::System.Boolean" or "bool" => "default", |
| | 6 | 395 | | "global::System.Int32" or "int" => "default", |
| | 0 | 396 | | "global::System.Int64" or "long" => "default", |
| | 0 | 397 | | "global::System.Int16" or "short" => "default", |
| | 0 | 398 | | "global::System.Byte" or "byte" => "default", |
| | 0 | 399 | | "global::System.SByte" or "sbyte" => "default", |
| | 0 | 400 | | "global::System.UInt32" or "uint" => "default", |
| | 0 | 401 | | "global::System.UInt64" or "ulong" => "default", |
| | 0 | 402 | | "global::System.UInt16" or "ushort" => "default", |
| | 0 | 403 | | "global::System.Single" or "float" => "default", |
| | 1 | 404 | | "global::System.Double" or "double" => "default", |
| | 0 | 405 | | "global::System.Decimal" or "decimal" => "default", |
| | 0 | 406 | | "global::System.Char" or "char" => "default", |
| | 0 | 407 | | "global::System.DateTime" => "default", |
| | 0 | 408 | | "global::System.DateTimeOffset" => "default", |
| | 0 | 409 | | "global::System.TimeSpan" => "default", |
| | 0 | 410 | | "global::System.Guid" => "default", |
| | 19 | 411 | | // For nullable types and reference types, use default (which gives null for reference types) |
| | 19 | 412 | | // For other value types, use default |
| | 1 | 413 | | _ when fullyQualifiedTypeName.EndsWith("?") => "default", |
| | 1 | 414 | | _ => "default!" // Reference types need null-forgiving operator |
| | 19 | 415 | | }; |
| | | 416 | | } |
| | | 417 | | |
| | | 418 | | // ----------------------------------------------------------------------- |
| | | 419 | | // Options registration code generation (moved from TypeRegistryGenerator) |
| | | 420 | | // ----------------------------------------------------------------------- |
| | | 421 | | |
| | | 422 | | internal static void GenerateReflectionOptionsRegistration(StringBuilder builder, IReadOnlyList<DiscoveredOptions> o |
| | | 423 | | { |
| | | 424 | | // Track external validators to register (avoid duplicates) |
| | 68 | 425 | | var externalValidatorsToRegister = new HashSet<string>(); |
| | | 426 | | |
| | 292 | 427 | | foreach (var opt in options) |
| | | 428 | | { |
| | 78 | 429 | | var typeName = opt.TypeName; |
| | | 430 | | |
| | 78 | 431 | | if (opt.ValidateOnStart) |
| | | 432 | | { |
| | | 433 | | // Use AddOptions pattern for validation support |
| | | 434 | | // services.AddOptions<T>().BindConfiguration("Section").ValidateDataAnnotations().ValidateOnStart(); |
| | 23 | 435 | | builder.Append($" services.AddOptions<{typeName}>"); |
| | | 436 | | |
| | 23 | 437 | | if (opt.IsNamed) |
| | | 438 | | { |
| | 1 | 439 | | builder.Append($"(\"{opt.Name}\")"); |
| | | 440 | | } |
| | | 441 | | else |
| | | 442 | | { |
| | 22 | 443 | | builder.Append("()"); |
| | | 444 | | } |
| | | 445 | | |
| | 23 | 446 | | builder.Append($".BindConfiguration(\"{opt.SectionName}\")"); |
| | 23 | 447 | | builder.Append(".ValidateDataAnnotations()"); |
| | 23 | 448 | | builder.AppendLine(".ValidateOnStart();"); |
| | | 449 | | |
| | | 450 | | // Register source-generated DataAnnotations validator if present |
| | | 451 | | // This runs alongside .ValidateDataAnnotations() - source-gen handles supported attributes, |
| | | 452 | | // reflection fallback handles unsupported attributes (like [CustomValidation]) |
| | 23 | 453 | | if (opt.HasDataAnnotations) |
| | | 454 | | { |
| | 2 | 455 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(typeName); |
| | 2 | 456 | | var dataAnnotationsValidatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}DataAn |
| | 2 | 457 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOpt |
| | | 458 | | } |
| | | 459 | | |
| | | 460 | | // If there's a custom validator method, register the generated validator |
| | 23 | 461 | | if (opt.HasValidatorMethod) |
| | | 462 | | { |
| | 12 | 463 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(typeName); |
| | 12 | 464 | | var validatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}Validator"; |
| | 12 | 465 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOpt |
| | | 466 | | |
| | | 467 | | // If external validator with instance method, register it too |
| | 12 | 468 | | if (opt.HasExternalValidator && opt.ValidatorMethod != null && !opt.ValidatorMethod.Value.IsStatic) |
| | | 469 | | { |
| | 3 | 470 | | externalValidatorsToRegister.Add(opt.ValidatorTypeName!); |
| | | 471 | | } |
| | | 472 | | } |
| | | 473 | | } |
| | 55 | 474 | | else if (opt.IsNamed) |
| | | 475 | | { |
| | | 476 | | // Named options: OptionsConfigurationServiceCollectionExtensions.Configure<T>(services, "name", section |
| | 8 | 477 | | builder.AppendLine($" global::Microsoft.Extensions.DependencyInjection.OptionsConfigurationServic |
| | | 478 | | } |
| | | 479 | | else |
| | | 480 | | { |
| | | 481 | | // Default options: OptionsConfigurationServiceCollectionExtensions.Configure<T>(services, section) |
| | 47 | 482 | | builder.AppendLine($" global::Microsoft.Extensions.DependencyInjection.OptionsConfigurationServic |
| | | 483 | | } |
| | | 484 | | } |
| | | 485 | | |
| | | 486 | | // Register external validators that have instance methods |
| | 142 | 487 | | foreach (var validatorType in externalValidatorsToRegister) |
| | | 488 | | { |
| | 3 | 489 | | builder.AppendLine($" services.AddSingleton<{validatorType}>();"); |
| | | 490 | | } |
| | 68 | 491 | | } |
| | | 492 | | |
| | | 493 | | internal static void GenerateAotOptionsRegistration(StringBuilder builder, IReadOnlyList<DiscoveredOptions> options, |
| | | 494 | | { |
| | 78 | 495 | | breadcrumbs.WriteInlineComment(builder, " ", "AOT-compatible options binding (no reflection)"); |
| | | 496 | | |
| | 78 | 497 | | var externalValidatorsToRegister = new HashSet<string>(); |
| | | 498 | | |
| | 330 | 499 | | foreach (var opt in options) |
| | | 500 | | { |
| | 87 | 501 | | var typeName = opt.TypeName; |
| | 87 | 502 | | builder.AppendLine(); |
| | 87 | 503 | | builder.AppendLine($" // Bind {opt.SectionName} section to {GeneratorHelpers.GetShortTypeName(typeNam |
| | | 504 | | |
| | | 505 | | // Choose binding pattern based on type characteristics |
| | 87 | 506 | | if (opt.IsPositionalRecord) |
| | | 507 | | { |
| | | 508 | | // Positional records: Use constructor binding with Options.Create |
| | 5 | 509 | | GeneratePositionalRecordBinding(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | | 510 | | } |
| | 82 | 511 | | else if (opt.HasInitOnlyProperties) |
| | | 512 | | { |
| | | 513 | | // Classes/records with init-only properties: Use object initializer with Options.Create |
| | 7 | 514 | | GenerateInitOnlyBinding(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | | 515 | | } |
| | | 516 | | else |
| | | 517 | | { |
| | | 518 | | // Regular classes with setters: Use Configure delegate pattern |
| | 75 | 519 | | GenerateConfigureBinding(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | | 520 | | } |
| | | 521 | | } |
| | | 522 | | |
| | | 523 | | // Register external validators that have instance methods |
| | 158 | 524 | | foreach (var validatorType in externalValidatorsToRegister) |
| | | 525 | | { |
| | 1 | 526 | | builder.AppendLine($" services.AddSingleton<{validatorType}>();"); |
| | | 527 | | } |
| | 78 | 528 | | } |
| | | 529 | | |
| | | 530 | | private static void GenerateConfigureBinding(StringBuilder builder, DiscoveredOptions opt, string safeAssemblyName, |
| | | 531 | | { |
| | 75 | 532 | | var typeName = opt.TypeName; |
| | | 533 | | |
| | 75 | 534 | | if (opt.IsNamed) |
| | | 535 | | { |
| | 13 | 536 | | builder.AppendLine($" services.AddOptions<{typeName}>(\"{opt.Name}\")"); |
| | | 537 | | } |
| | | 538 | | else |
| | | 539 | | { |
| | 62 | 540 | | builder.AppendLine($" services.AddOptions<{typeName}>()"); |
| | | 541 | | } |
| | | 542 | | |
| | 75 | 543 | | builder.AppendLine(" .Configure<IConfiguration>((options, config) =>"); |
| | 75 | 544 | | builder.AppendLine(" {"); |
| | 75 | 545 | | builder.AppendLine($" var section = config.GetSection(\"{opt.SectionName}\");"); |
| | | 546 | | |
| | | 547 | | // Generate property binding for each property |
| | 75 | 548 | | var propIndex = 0; |
| | 390 | 549 | | foreach (var prop in opt.Properties) |
| | | 550 | | { |
| | 120 | 551 | | GeneratePropertyBinding(builder, prop, propIndex); |
| | 120 | 552 | | propIndex++; |
| | | 553 | | } |
| | | 554 | | |
| | 75 | 555 | | builder.Append(" })"); |
| | | 556 | | |
| | | 557 | | // Add validation chain if ValidateOnStart is enabled |
| | 75 | 558 | | if (opt.ValidateOnStart) |
| | | 559 | | { |
| | 20 | 560 | | builder.AppendLine(); |
| | 20 | 561 | | builder.Append(" .ValidateOnStart()"); |
| | | 562 | | } |
| | | 563 | | |
| | 75 | 564 | | builder.AppendLine(";"); |
| | | 565 | | |
| | 75 | 566 | | RegisterValidator(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | 75 | 567 | | } |
| | | 568 | | |
| | | 569 | | private static void GenerateInitOnlyBinding(StringBuilder builder, DiscoveredOptions opt, string safeAssemblyName, H |
| | | 570 | | { |
| | 7 | 571 | | var typeName = opt.TypeName; |
| | | 572 | | |
| | | 573 | | // Use AddSingleton with IOptions<T> factory pattern for init-only |
| | 7 | 574 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IOptions<{typeName}>>(sp |
| | 7 | 575 | | builder.AppendLine(" {"); |
| | 7 | 576 | | builder.AppendLine($" var config = sp.GetRequiredService<IConfiguration>();"); |
| | 7 | 577 | | builder.AppendLine($" var section = config.GetSection(\"{opt.SectionName}\");"); |
| | | 578 | | |
| | | 579 | | // Generate parsing variables first |
| | 7 | 580 | | var propIndex = 0; |
| | 44 | 581 | | foreach (var prop in opt.Properties) |
| | | 582 | | { |
| | 15 | 583 | | GeneratePropertyParseVariable(builder, prop, propIndex); |
| | 15 | 584 | | propIndex++; |
| | | 585 | | } |
| | | 586 | | |
| | | 587 | | // Create object with initializer |
| | 7 | 588 | | builder.AppendLine($" return global::Microsoft.Extensions.Options.Options.Create(new {typeName}"); |
| | 7 | 589 | | builder.AppendLine(" {"); |
| | | 590 | | |
| | 7 | 591 | | propIndex = 0; |
| | 44 | 592 | | foreach (var prop in opt.Properties) |
| | | 593 | | { |
| | 15 | 594 | | var comma = propIndex < opt.Properties.Count - 1 ? "," : ""; |
| | 15 | 595 | | GeneratePropertyInitializer(builder, prop, propIndex, comma); |
| | 15 | 596 | | propIndex++; |
| | | 597 | | } |
| | | 598 | | |
| | 7 | 599 | | builder.AppendLine(" });"); |
| | 7 | 600 | | builder.AppendLine(" });"); |
| | | 601 | | |
| | | 602 | | // For validation with factory pattern, we need to register the validator separately |
| | 7 | 603 | | if (opt.ValidateOnStart) |
| | | 604 | | { |
| | 1 | 605 | | RegisterValidatorForFactory(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | | 606 | | } |
| | 7 | 607 | | } |
| | | 608 | | |
| | | 609 | | private static void GeneratePositionalRecordBinding(StringBuilder builder, DiscoveredOptions opt, string safeAssembl |
| | | 610 | | { |
| | 5 | 611 | | var typeName = opt.TypeName; |
| | 5 | 612 | | var recordInfo = opt.PositionalRecordInfo!.Value; |
| | | 613 | | |
| | | 614 | | // Use AddSingleton with IOptions<T> factory pattern for positional records |
| | 5 | 615 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IOptions<{typeName}>>(sp |
| | 5 | 616 | | builder.AppendLine(" {"); |
| | 5 | 617 | | builder.AppendLine($" var config = sp.GetRequiredService<IConfiguration>();"); |
| | 5 | 618 | | builder.AppendLine($" var section = config.GetSection(\"{opt.SectionName}\");"); |
| | | 619 | | |
| | | 620 | | // Generate parsing variables for each constructor parameter |
| | 5 | 621 | | var paramIndex = 0; |
| | 36 | 622 | | foreach (var param in recordInfo.Parameters) |
| | | 623 | | { |
| | 13 | 624 | | GenerateParameterParseVariable(builder, param, paramIndex); |
| | 13 | 625 | | paramIndex++; |
| | | 626 | | } |
| | | 627 | | |
| | | 628 | | // Create record with constructor |
| | 5 | 629 | | builder.Append($" return global::Microsoft.Extensions.Options.Options.Create(new {typeName}("); |
| | | 630 | | |
| | 5 | 631 | | paramIndex = 0; |
| | 36 | 632 | | foreach (var param in recordInfo.Parameters) |
| | | 633 | | { |
| | 21 | 634 | | if (paramIndex > 0) builder.Append(", "); |
| | 13 | 635 | | builder.Append($"p{paramIndex}"); |
| | 13 | 636 | | paramIndex++; |
| | | 637 | | } |
| | | 638 | | |
| | 5 | 639 | | builder.AppendLine("));"); |
| | 5 | 640 | | builder.AppendLine(" });"); |
| | | 641 | | |
| | | 642 | | // For validation with factory pattern, we need to register the validator separately |
| | 5 | 643 | | if (opt.ValidateOnStart) |
| | | 644 | | { |
| | 0 | 645 | | RegisterValidatorForFactory(builder, opt, safeAssemblyName, externalValidatorsToRegister); |
| | | 646 | | } |
| | 5 | 647 | | } |
| | | 648 | | |
| | | 649 | | private static void GeneratePropertyParseVariable(StringBuilder builder, OptionsPropertyInfo prop, int index) |
| | | 650 | | { |
| | 15 | 651 | | var varName = $"p{index}"; |
| | 15 | 652 | | var typeName = prop.TypeName; |
| | 15 | 653 | | var baseTypeName = GetBaseTypeName(typeName); |
| | | 654 | | |
| | | 655 | | // Handle complex types |
| | 15 | 656 | | if (prop.ComplexTypeKind != ComplexTypeKind.None) |
| | | 657 | | { |
| | 2 | 658 | | GenerateComplexTypeParseVariable(builder, prop, index); |
| | 2 | 659 | | return; |
| | | 660 | | } |
| | | 661 | | |
| | | 662 | | // Handle enums |
| | 13 | 663 | | if (prop.IsEnum && prop.EnumTypeName != null) |
| | | 664 | | { |
| | 0 | 665 | | var defaultVal = prop.IsNullable ? "null" : "default"; |
| | 0 | 666 | | builder.AppendLine($" var {varName} = section[\"{prop.Name}\"] is {{ }} v{index} && global::Syste |
| | 0 | 667 | | return; |
| | | 668 | | } |
| | | 669 | | |
| | | 670 | | // Handle primitives |
| | 13 | 671 | | if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 672 | | { |
| | 7 | 673 | | var defaultVal = prop.IsNullable ? "null" : "\"\""; |
| | 7 | 674 | | builder.AppendLine($" var {varName} = section[\"{prop.Name}\"] ?? {defaultVal};"); |
| | | 675 | | } |
| | 6 | 676 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 677 | | { |
| | 5 | 678 | | var defaultVal = prop.IsNullable ? "null" : "0"; |
| | 5 | 679 | | builder.AppendLine($" var {varName} = section[\"{prop.Name}\"] is {{ }} v{index} && int.TryParse( |
| | | 680 | | } |
| | 1 | 681 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 682 | | { |
| | 1 | 683 | | var defaultVal = prop.IsNullable ? "null" : "false"; |
| | 1 | 684 | | builder.AppendLine($" var {varName} = section[\"{prop.Name}\"] is {{ }} v{index} && bool.TryParse |
| | | 685 | | } |
| | 0 | 686 | | else if (baseTypeName == "double" || baseTypeName == "global::System.Double") |
| | | 687 | | { |
| | 0 | 688 | | var defaultVal = prop.IsNullable ? "null" : "0.0"; |
| | 0 | 689 | | builder.AppendLine($" var {varName} = section[\"{prop.Name}\"] is {{ }} v{index} && double.TryPar |
| | | 690 | | } |
| | | 691 | | else |
| | | 692 | | { |
| | | 693 | | // Default to default value for unsupported types |
| | 0 | 694 | | builder.AppendLine($" var {varName} = default({typeName}); // Unsupported type"); |
| | | 695 | | } |
| | 0 | 696 | | } |
| | | 697 | | |
| | | 698 | | private static void GenerateComplexTypeParseVariable(StringBuilder builder, OptionsPropertyInfo prop, int index) |
| | | 699 | | { |
| | 2 | 700 | | var varName = $"p{index}"; |
| | 2 | 701 | | var sectionVar = $"sec{index}"; |
| | | 702 | | |
| | 2 | 703 | | switch (prop.ComplexTypeKind) |
| | | 704 | | { |
| | | 705 | | case ComplexTypeKind.NestedObject: |
| | 1 | 706 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 1 | 707 | | builder.AppendLine($" var {varName} = new {GetNonNullableTypeName(prop.TypeName)}();"); |
| | 1 | 708 | | if (prop.NestedProperties != null) |
| | | 709 | | { |
| | 1 | 710 | | var nestedIndex = index * 100; |
| | 6 | 711 | | foreach (var nested in prop.NestedProperties) |
| | | 712 | | { |
| | 2 | 713 | | GenerateNestedPropertyAssignment(builder, nested, nestedIndex, varName, sectionVar); |
| | 2 | 714 | | nestedIndex++; |
| | | 715 | | } |
| | | 716 | | } |
| | | 717 | | break; |
| | | 718 | | |
| | | 719 | | case ComplexTypeKind.List: |
| | 1 | 720 | | var listElemType = prop.ElementTypeName ?? "string"; |
| | 1 | 721 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 1 | 722 | | builder.AppendLine($" var {varName} = new global::System.Collections.Generic.List<{listElemTy |
| | 1 | 723 | | builder.AppendLine($" foreach (var child in {sectionVar}.GetChildren())"); |
| | 1 | 724 | | builder.AppendLine(" {"); |
| | 1 | 725 | | if (prop.NestedProperties != null && prop.NestedProperties.Count > 0) |
| | | 726 | | { |
| | 0 | 727 | | builder.AppendLine($" var item = new {listElemType}();"); |
| | 0 | 728 | | var ni = index * 100; |
| | 0 | 729 | | foreach (var np in prop.NestedProperties) |
| | | 730 | | { |
| | 0 | 731 | | GenerateChildPropertyAssignment(builder, np, ni, "item", "child"); |
| | 0 | 732 | | ni++; |
| | | 733 | | } |
| | 0 | 734 | | builder.AppendLine($" {varName}.Add(item);"); |
| | | 735 | | } |
| | | 736 | | else |
| | | 737 | | { |
| | 1 | 738 | | builder.AppendLine($" if (child.Value is {{ }} val) {varName}.Add(val);"); |
| | | 739 | | } |
| | 1 | 740 | | builder.AppendLine(" }"); |
| | 1 | 741 | | break; |
| | | 742 | | |
| | | 743 | | case ComplexTypeKind.Dictionary: |
| | 0 | 744 | | var dictValType = prop.ElementTypeName ?? "string"; |
| | 0 | 745 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 0 | 746 | | builder.AppendLine($" var {varName} = new global::System.Collections.Generic.Dictionary<strin |
| | 0 | 747 | | builder.AppendLine($" foreach (var child in {sectionVar}.GetChildren())"); |
| | 0 | 748 | | builder.AppendLine(" {"); |
| | 0 | 749 | | if (prop.NestedProperties != null && prop.NestedProperties.Count > 0) |
| | | 750 | | { |
| | 0 | 751 | | builder.AppendLine($" var item = new {dictValType}();"); |
| | 0 | 752 | | var ni = index * 100; |
| | 0 | 753 | | foreach (var np in prop.NestedProperties) |
| | | 754 | | { |
| | 0 | 755 | | GenerateChildPropertyAssignment(builder, np, ni, "item", "child"); |
| | 0 | 756 | | ni++; |
| | | 757 | | } |
| | 0 | 758 | | builder.AppendLine($" {varName}[child.Key] = item;"); |
| | | 759 | | } |
| | 0 | 760 | | else if (dictValType == "int" || dictValType == "global::System.Int32") |
| | | 761 | | { |
| | 0 | 762 | | builder.AppendLine($" if (child.Value is {{ }} val && int.TryParse(val, out var iv)) |
| | | 763 | | } |
| | | 764 | | else |
| | | 765 | | { |
| | 0 | 766 | | builder.AppendLine($" if (child.Value is {{ }} val) {varName}[child.Key] = val;"); |
| | | 767 | | } |
| | 0 | 768 | | builder.AppendLine(" }"); |
| | 0 | 769 | | break; |
| | | 770 | | |
| | | 771 | | default: |
| | 0 | 772 | | builder.AppendLine($" var {varName} = default({prop.TypeName}); // Complex type"); |
| | | 773 | | break; |
| | | 774 | | } |
| | 1 | 775 | | } |
| | | 776 | | |
| | | 777 | | private static void GenerateNestedPropertyAssignment(StringBuilder builder, OptionsPropertyInfo prop, int index, str |
| | | 778 | | { |
| | 2 | 779 | | var varName = $"nv{index}"; |
| | 2 | 780 | | var baseTypeName = GetBaseTypeName(prop.TypeName); |
| | | 781 | | |
| | 2 | 782 | | if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 783 | | { |
| | 1 | 784 | | builder.AppendLine($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName}) {targetVar}.{prop.Nam |
| | | 785 | | } |
| | 1 | 786 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 787 | | { |
| | 1 | 788 | | builder.AppendLine($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName} && int.TryParse({varNa |
| | | 789 | | } |
| | 0 | 790 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 791 | | { |
| | 0 | 792 | | builder.AppendLine($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName} && bool.TryParse({varN |
| | | 793 | | } |
| | 0 | 794 | | } |
| | | 795 | | |
| | | 796 | | private static void GenerateChildPropertyAssignment(StringBuilder builder, OptionsPropertyInfo prop, int index, stri |
| | | 797 | | { |
| | 0 | 798 | | var varName = $"cv{index}"; |
| | 0 | 799 | | var baseTypeName = GetBaseTypeName(prop.TypeName); |
| | | 800 | | |
| | 0 | 801 | | if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 802 | | { |
| | 0 | 803 | | builder.AppendLine($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName}) {targetVar}.{prop |
| | | 804 | | } |
| | 0 | 805 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 806 | | { |
| | 0 | 807 | | builder.AppendLine($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName} && int.TryParse({v |
| | | 808 | | } |
| | 0 | 809 | | } |
| | | 810 | | |
| | | 811 | | private static void GeneratePropertyInitializer(StringBuilder builder, OptionsPropertyInfo prop, int index, string c |
| | | 812 | | { |
| | 15 | 813 | | builder.AppendLine($" {prop.Name} = p{index}{comma}"); |
| | 15 | 814 | | } |
| | | 815 | | |
| | | 816 | | private static void GenerateParameterParseVariable(StringBuilder builder, PositionalRecordParameter param, int index |
| | | 817 | | { |
| | 13 | 818 | | var varName = $"p{index}"; |
| | 13 | 819 | | var typeName = param.TypeName; |
| | 13 | 820 | | var baseTypeName = GetBaseTypeName(typeName); |
| | | 821 | | |
| | | 822 | | // Check if it's an enum |
| | | 823 | | // For simplicity, check if it's a known primitive, otherwise assume it could be an enum |
| | 13 | 824 | | if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 825 | | { |
| | 5 | 826 | | builder.AppendLine($" var {varName} = section[\"{param.Name}\"] ?? \"\";"); |
| | | 827 | | } |
| | 8 | 828 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 829 | | { |
| | 4 | 830 | | builder.AppendLine($" var {varName} = section[\"{param.Name}\"] is {{ }} v{index} && int.TryParse |
| | | 831 | | } |
| | 4 | 832 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 833 | | { |
| | 3 | 834 | | builder.AppendLine($" var {varName} = section[\"{param.Name}\"] is {{ }} v{index} && bool.TryPars |
| | | 835 | | } |
| | 1 | 836 | | else if (baseTypeName == "double" || baseTypeName == "global::System.Double") |
| | | 837 | | { |
| | 0 | 838 | | builder.AppendLine($" var {varName} = section[\"{param.Name}\"] is {{ }} v{index} && double.TryPa |
| | | 839 | | } |
| | | 840 | | else |
| | | 841 | | { |
| | | 842 | | // Try enum parsing for other types |
| | 1 | 843 | | builder.AppendLine($" var {varName} = section[\"{param.Name}\"] is {{ }} v{index} && global::Syst |
| | | 844 | | } |
| | 1 | 845 | | } |
| | | 846 | | |
| | | 847 | | private static void RegisterValidator(StringBuilder builder, DiscoveredOptions opt, string safeAssemblyName, HashSet |
| | | 848 | | { |
| | 75 | 849 | | var typeName = opt.TypeName; |
| | 75 | 850 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(typeName); |
| | | 851 | | |
| | | 852 | | // Register DataAnnotations validator if present |
| | 75 | 853 | | if (opt.HasDataAnnotations) |
| | | 854 | | { |
| | 17 | 855 | | var dataAnnotationsValidatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}DataAnnotation |
| | 17 | 856 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOptions<{ty |
| | | 857 | | } |
| | | 858 | | |
| | 75 | 859 | | if (opt.ValidateOnStart && opt.HasValidatorMethod) |
| | | 860 | | { |
| | 4 | 861 | | var validatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}Validator"; |
| | 4 | 862 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOptions<{ty |
| | | 863 | | |
| | 4 | 864 | | if (opt.HasExternalValidator && opt.ValidatorMethod != null && !opt.ValidatorMethod.Value.IsStatic) |
| | | 865 | | { |
| | 1 | 866 | | externalValidatorsToRegister.Add(opt.ValidatorTypeName!); |
| | | 867 | | } |
| | | 868 | | } |
| | 75 | 869 | | } |
| | | 870 | | |
| | | 871 | | private static void RegisterValidatorForFactory(StringBuilder builder, DiscoveredOptions opt, string safeAssemblyNam |
| | | 872 | | { |
| | 1 | 873 | | var typeName = opt.TypeName; |
| | 1 | 874 | | var shortTypeName = GeneratorHelpers.GetShortTypeName(typeName); |
| | | 875 | | |
| | | 876 | | // For factory pattern, we need to add OptionsBuilder validation manually |
| | | 877 | | // Since we're using AddSingleton<IOptions<T>>, we also need to register for IOptionsSnapshot and IOptionsMonito |
| | 1 | 878 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IOptionsSnapshot<{typeNa |
| | | 879 | | |
| | | 880 | | // Add startup validation |
| | 1 | 881 | | builder.AppendLine($" services.AddOptions<{typeName}>().ValidateOnStart();"); |
| | | 882 | | |
| | | 883 | | // Register DataAnnotations validator if present |
| | 1 | 884 | | if (opt.HasDataAnnotations) |
| | | 885 | | { |
| | 0 | 886 | | var dataAnnotationsValidatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}DataAnnotation |
| | 0 | 887 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOptions<{ty |
| | | 888 | | } |
| | | 889 | | |
| | 1 | 890 | | if (opt.HasValidatorMethod) |
| | | 891 | | { |
| | 1 | 892 | | var validatorClassName = $"global::{safeAssemblyName}.Generated.{shortTypeName}Validator"; |
| | 1 | 893 | | builder.AppendLine($" services.AddSingleton<global::Microsoft.Extensions.Options.IValidateOptions<{ty |
| | | 894 | | |
| | 1 | 895 | | if (opt.HasExternalValidator && opt.ValidatorMethod != null && !opt.ValidatorMethod.Value.IsStatic) |
| | | 896 | | { |
| | 0 | 897 | | externalValidatorsToRegister.Add(opt.ValidatorTypeName!); |
| | | 898 | | } |
| | | 899 | | } |
| | 1 | 900 | | } |
| | | 901 | | |
| | | 902 | | private static void GeneratePropertyBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string targe |
| | | 903 | | { |
| | | 904 | | // Handle complex types first |
| | 120 | 905 | | if (prop.ComplexTypeKind != ComplexTypeKind.None) |
| | | 906 | | { |
| | 18 | 907 | | GenerateComplexTypeBinding(builder, prop, index, targetPath); |
| | 18 | 908 | | return; |
| | | 909 | | } |
| | | 910 | | |
| | 102 | 911 | | var varName = $"v{index}"; |
| | | 912 | | |
| | | 913 | | // Determine how to parse the value based on type |
| | 102 | 914 | | var typeName = prop.TypeName; |
| | 102 | 915 | | var baseTypeName = GetBaseTypeName(typeName); |
| | | 916 | | |
| | 102 | 917 | | builder.Append($" if (section[\"{prop.Name}\"] is {{ }} {varName}"); |
| | | 918 | | |
| | | 919 | | // Check if it's an enum first |
| | 102 | 920 | | if (prop.IsEnum && prop.EnumTypeName != null) |
| | | 921 | | { |
| | 12 | 922 | | builder.AppendLine($" && global::System.Enum.TryParse<{prop.EnumTypeName}>({varName}, true, out var p{index} |
| | | 923 | | } |
| | 90 | 924 | | else if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 925 | | { |
| | | 926 | | // String: direct assignment |
| | 50 | 927 | | builder.AppendLine($") {targetPath}.{prop.Name} = {varName};"); |
| | | 928 | | } |
| | 40 | 929 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 930 | | { |
| | 23 | 931 | | builder.AppendLine($" && int.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 932 | | } |
| | 17 | 933 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 934 | | { |
| | 5 | 935 | | builder.AppendLine($" && bool.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 936 | | } |
| | 12 | 937 | | else if (baseTypeName == "double" || baseTypeName == "global::System.Double") |
| | | 938 | | { |
| | 5 | 939 | | builder.AppendLine($" && double.TryParse({varName}, System.Globalization.NumberStyles.Any, System.Globalizat |
| | | 940 | | } |
| | 7 | 941 | | else if (baseTypeName == "float" || baseTypeName == "global::System.Single") |
| | | 942 | | { |
| | 0 | 943 | | builder.AppendLine($" && float.TryParse({varName}, System.Globalization.NumberStyles.Any, System.Globalizati |
| | | 944 | | } |
| | 7 | 945 | | else if (baseTypeName == "decimal" || baseTypeName == "global::System.Decimal") |
| | | 946 | | { |
| | 0 | 947 | | builder.AppendLine($" && decimal.TryParse({varName}, System.Globalization.NumberStyles.Any, System.Globaliza |
| | | 948 | | } |
| | 7 | 949 | | else if (baseTypeName == "long" || baseTypeName == "global::System.Int64") |
| | | 950 | | { |
| | 0 | 951 | | builder.AppendLine($" && long.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 952 | | } |
| | 7 | 953 | | else if (baseTypeName == "short" || baseTypeName == "global::System.Int16") |
| | | 954 | | { |
| | 0 | 955 | | builder.AppendLine($" && short.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};") |
| | | 956 | | } |
| | 7 | 957 | | else if (baseTypeName == "byte" || baseTypeName == "global::System.Byte") |
| | | 958 | | { |
| | 0 | 959 | | builder.AppendLine($" && byte.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 960 | | } |
| | 7 | 961 | | else if (baseTypeName == "char" || baseTypeName == "global::System.Char") |
| | | 962 | | { |
| | 0 | 963 | | builder.AppendLine($" && {varName}.Length == 1) {targetPath}.{prop.Name} = {varName}[0];"); |
| | | 964 | | } |
| | 7 | 965 | | else if (baseTypeName == "global::System.TimeSpan") |
| | | 966 | | { |
| | 0 | 967 | | builder.AppendLine($" && global::System.TimeSpan.TryParse({varName}, out var p{index})) {targetPath}.{prop.N |
| | | 968 | | } |
| | 7 | 969 | | else if (baseTypeName == "global::System.DateTime") |
| | | 970 | | { |
| | 0 | 971 | | builder.AppendLine($" && global::System.DateTime.TryParse({varName}, out var p{index})) {targetPath}.{prop.N |
| | | 972 | | } |
| | 7 | 973 | | else if (baseTypeName == "global::System.DateTimeOffset") |
| | | 974 | | { |
| | 0 | 975 | | builder.AppendLine($" && global::System.DateTimeOffset.TryParse({varName}, out var p{index})) {targetPath}.{ |
| | | 976 | | } |
| | 7 | 977 | | else if (baseTypeName == "global::System.Guid") |
| | | 978 | | { |
| | 0 | 979 | | builder.AppendLine($" && global::System.Guid.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} |
| | | 980 | | } |
| | 7 | 981 | | else if (baseTypeName == "global::System.Uri") |
| | | 982 | | { |
| | 0 | 983 | | builder.AppendLine($" && global::System.Uri.TryCreate({varName}, global::System.UriKind.RelativeOrAbsolute, |
| | | 984 | | } |
| | | 985 | | else |
| | | 986 | | { |
| | | 987 | | // Unsupported type - skip silently (matching ConfigurationBinder behavior) |
| | 7 | 988 | | builder.AppendLine($") {{ }} // Skipped: {typeName} (not a supported primitive)"); |
| | | 989 | | } |
| | 7 | 990 | | } |
| | | 991 | | |
| | | 992 | | private static void GenerateComplexTypeBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string ta |
| | | 993 | | { |
| | 18 | 994 | | var sectionVar = $"sec{index}"; |
| | | 995 | | |
| | 18 | 996 | | switch (prop.ComplexTypeKind) |
| | | 997 | | { |
| | | 998 | | case ComplexTypeKind.NestedObject: |
| | 6 | 999 | | GenerateNestedObjectBinding(builder, prop, index, targetPath, sectionVar); |
| | 6 | 1000 | | break; |
| | | 1001 | | |
| | | 1002 | | case ComplexTypeKind.Array: |
| | 3 | 1003 | | GenerateArrayBinding(builder, prop, index, targetPath, sectionVar); |
| | 3 | 1004 | | break; |
| | | 1005 | | |
| | | 1006 | | case ComplexTypeKind.List: |
| | 5 | 1007 | | GenerateListBinding(builder, prop, index, targetPath, sectionVar); |
| | 5 | 1008 | | break; |
| | | 1009 | | |
| | | 1010 | | case ComplexTypeKind.Dictionary: |
| | 4 | 1011 | | GenerateDictionaryBinding(builder, prop, index, targetPath, sectionVar); |
| | | 1012 | | break; |
| | | 1013 | | } |
| | 4 | 1014 | | } |
| | | 1015 | | |
| | | 1016 | | private static void GenerateNestedObjectBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string t |
| | | 1017 | | { |
| | 6 | 1018 | | var nestedPath = $"{targetPath}.{prop.Name}"; |
| | | 1019 | | |
| | 6 | 1020 | | builder.AppendLine($" // Bind nested object: {prop.Name}"); |
| | 6 | 1021 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | | 1022 | | |
| | | 1023 | | // Initialize if null (for nullable properties) |
| | 6 | 1024 | | if (prop.IsNullable) |
| | | 1025 | | { |
| | 1 | 1026 | | builder.AppendLine($" {nestedPath} ??= new {GetNonNullableTypeName(prop.TypeName)}();"); |
| | | 1027 | | } |
| | | 1028 | | |
| | | 1029 | | // Generate bindings for nested properties |
| | 6 | 1030 | | if (prop.NestedProperties != null) |
| | | 1031 | | { |
| | 6 | 1032 | | var nestedIndex = index * 100; // Use offset to avoid variable name collisions |
| | 30 | 1033 | | foreach (var nestedProp in prop.NestedProperties) |
| | | 1034 | | { |
| | | 1035 | | // Temporarily swap section context for nested binding |
| | 9 | 1036 | | GenerateNestedPropertyBinding(builder, nestedProp, nestedIndex, nestedPath, sectionVar); |
| | 9 | 1037 | | nestedIndex++; |
| | | 1038 | | } |
| | | 1039 | | } |
| | 6 | 1040 | | } |
| | | 1041 | | |
| | | 1042 | | private static void GenerateNestedPropertyBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string |
| | | 1043 | | { |
| | | 1044 | | // Handle complex types recursively |
| | 10 | 1045 | | if (prop.ComplexTypeKind != ComplexTypeKind.None) |
| | | 1046 | | { |
| | 2 | 1047 | | var innerSectionVar = $"sec{index}"; |
| | 2 | 1048 | | switch (prop.ComplexTypeKind) |
| | | 1049 | | { |
| | | 1050 | | case ComplexTypeKind.NestedObject: |
| | 1 | 1051 | | builder.AppendLine($" // Bind nested object: {prop.Name}"); |
| | 1 | 1052 | | builder.AppendLine($" var {innerSectionVar} = {sectionVarName}.GetSection(\"{prop.Nam |
| | 1 | 1053 | | if (prop.IsNullable) |
| | | 1054 | | { |
| | 0 | 1055 | | builder.AppendLine($" {targetPath}.{prop.Name} ??= new {GetNonNullableTypeName(pr |
| | | 1056 | | } |
| | 1 | 1057 | | if (prop.NestedProperties != null) |
| | | 1058 | | { |
| | 1 | 1059 | | var nestedIndex = index * 100; |
| | 4 | 1060 | | foreach (var nestedProp in prop.NestedProperties) |
| | | 1061 | | { |
| | 1 | 1062 | | GenerateNestedPropertyBinding(builder, nestedProp, nestedIndex, $"{targetPath}.{prop.Name}", |
| | 1 | 1063 | | nestedIndex++; |
| | | 1064 | | } |
| | | 1065 | | } |
| | | 1066 | | break; |
| | | 1067 | | |
| | | 1068 | | case ComplexTypeKind.Array: |
| | | 1069 | | case ComplexTypeKind.List: |
| | | 1070 | | case ComplexTypeKind.Dictionary: |
| | | 1071 | | // For collections inside nested objects, generate appropriate binding |
| | 1 | 1072 | | GenerateCollectionBindingInNested(builder, prop, index, targetPath, sectionVarName); |
| | | 1073 | | break; |
| | | 1074 | | } |
| | 2 | 1075 | | return; |
| | | 1076 | | } |
| | | 1077 | | |
| | | 1078 | | // Generate primitive binding using the nested section |
| | 8 | 1079 | | var varName = $"v{index}"; |
| | 8 | 1080 | | var baseTypeName = GetBaseTypeName(prop.TypeName); |
| | | 1081 | | |
| | 8 | 1082 | | builder.Append($" if ({sectionVarName}[\"{prop.Name}\"] is {{ }} {varName}"); |
| | | 1083 | | |
| | 8 | 1084 | | if (prop.IsEnum && prop.EnumTypeName != null) |
| | | 1085 | | { |
| | 0 | 1086 | | builder.AppendLine($" && global::System.Enum.TryParse<{prop.EnumTypeName}>({varName}, true, out var p{index} |
| | | 1087 | | } |
| | 8 | 1088 | | else if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 1089 | | { |
| | 6 | 1090 | | builder.AppendLine($") {targetPath}.{prop.Name} = {varName};"); |
| | | 1091 | | } |
| | 2 | 1092 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 1093 | | { |
| | 2 | 1094 | | builder.AppendLine($" && int.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 1095 | | } |
| | 0 | 1096 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 1097 | | { |
| | 0 | 1098 | | builder.AppendLine($" && bool.TryParse({varName}, out var p{index})) {targetPath}.{prop.Name} = p{index};"); |
| | | 1099 | | } |
| | | 1100 | | else |
| | | 1101 | | { |
| | | 1102 | | // For other types, generate appropriate TryParse |
| | 0 | 1103 | | builder.AppendLine($") {{ }} // Skipped: {prop.TypeName}"); |
| | | 1104 | | } |
| | 0 | 1105 | | } |
| | | 1106 | | |
| | | 1107 | | private static void GenerateCollectionBindingInNested(StringBuilder builder, OptionsPropertyInfo prop, int index, st |
| | | 1108 | | { |
| | 1 | 1109 | | var collectionSection = $"colSec{index}"; |
| | 1 | 1110 | | builder.AppendLine($" var {collectionSection} = {sectionVarName}.GetSection(\"{prop.Name}\");"); |
| | | 1111 | | |
| | 1 | 1112 | | switch (prop.ComplexTypeKind) |
| | | 1113 | | { |
| | | 1114 | | case ComplexTypeKind.List: |
| | 1 | 1115 | | GenerateListBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", collectionSection); |
| | 1 | 1116 | | break; |
| | | 1117 | | case ComplexTypeKind.Array: |
| | 0 | 1118 | | GenerateArrayBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", collectionSection); |
| | 0 | 1119 | | break; |
| | | 1120 | | case ComplexTypeKind.Dictionary: |
| | 0 | 1121 | | GenerateDictionaryBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", collectionSection); |
| | | 1122 | | break; |
| | | 1123 | | } |
| | 0 | 1124 | | } |
| | | 1125 | | |
| | | 1126 | | private static void GenerateArrayBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string targetPa |
| | | 1127 | | { |
| | 3 | 1128 | | builder.AppendLine($" // Bind array: {prop.Name}"); |
| | 3 | 1129 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 3 | 1130 | | GenerateArrayBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", sectionVar); |
| | 3 | 1131 | | } |
| | | 1132 | | |
| | | 1133 | | private static void GenerateArrayBindingCore(StringBuilder builder, OptionsPropertyInfo prop, int index, string targ |
| | | 1134 | | { |
| | 3 | 1135 | | var itemsVar = $"items{index}"; |
| | 3 | 1136 | | var elementType = prop.ElementTypeName ?? "string"; |
| | 3 | 1137 | | var hasNestedProps = prop.NestedProperties != null && prop.NestedProperties.Count > 0; |
| | | 1138 | | |
| | 3 | 1139 | | builder.AppendLine($" var {itemsVar} = new global::System.Collections.Generic.List<{elementType}> |
| | 3 | 1140 | | builder.AppendLine($" foreach (var child in {sectionVar}.GetChildren())"); |
| | 3 | 1141 | | builder.AppendLine(" {"); |
| | | 1142 | | |
| | 3 | 1143 | | if (hasNestedProps) |
| | | 1144 | | { |
| | | 1145 | | // Complex element type |
| | 1 | 1146 | | var itemVar = $"item{index}"; |
| | 1 | 1147 | | builder.AppendLine($" var {itemVar} = new {elementType}();"); |
| | 1 | 1148 | | var nestedIndex = index * 100; |
| | 6 | 1149 | | foreach (var nestedProp in prop.NestedProperties!) |
| | | 1150 | | { |
| | 2 | 1151 | | GenerateChildPropertyBinding(builder, nestedProp, nestedIndex, itemVar, "child"); |
| | 2 | 1152 | | nestedIndex++; |
| | | 1153 | | } |
| | 1 | 1154 | | builder.AppendLine($" {itemsVar}.Add({itemVar});"); |
| | | 1155 | | } |
| | | 1156 | | else |
| | | 1157 | | { |
| | | 1158 | | // Primitive element type |
| | 2 | 1159 | | GeneratePrimitiveCollectionAdd(builder, elementType, index, itemsVar); |
| | | 1160 | | } |
| | | 1161 | | |
| | 3 | 1162 | | builder.AppendLine(" }"); |
| | 3 | 1163 | | builder.AppendLine($" {targetPath} = {itemsVar}.ToArray();"); |
| | 3 | 1164 | | } |
| | | 1165 | | |
| | | 1166 | | private static void GenerateListBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string targetPat |
| | | 1167 | | { |
| | 5 | 1168 | | builder.AppendLine($" // Bind list: {prop.Name}"); |
| | 5 | 1169 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 5 | 1170 | | GenerateListBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", sectionVar); |
| | 5 | 1171 | | } |
| | | 1172 | | |
| | | 1173 | | private static void GenerateListBindingCore(StringBuilder builder, OptionsPropertyInfo prop, int index, string targe |
| | | 1174 | | { |
| | 6 | 1175 | | var elementType = prop.ElementTypeName ?? "string"; |
| | 6 | 1176 | | var hasNestedProps = prop.NestedProperties != null && prop.NestedProperties.Count > 0; |
| | | 1177 | | |
| | 6 | 1178 | | builder.AppendLine($" {targetPath}.Clear();"); |
| | 6 | 1179 | | builder.AppendLine($" foreach (var child in {sectionVar}.GetChildren())"); |
| | 6 | 1180 | | builder.AppendLine(" {"); |
| | | 1181 | | |
| | 6 | 1182 | | if (hasNestedProps) |
| | | 1183 | | { |
| | | 1184 | | // Complex element type |
| | 1 | 1185 | | var itemVar = $"item{index}"; |
| | 1 | 1186 | | builder.AppendLine($" var {itemVar} = new {elementType}();"); |
| | 1 | 1187 | | var nestedIndex = index * 100; |
| | 6 | 1188 | | foreach (var nestedProp in prop.NestedProperties!) |
| | | 1189 | | { |
| | 2 | 1190 | | GenerateChildPropertyBinding(builder, nestedProp, nestedIndex, itemVar, "child"); |
| | 2 | 1191 | | nestedIndex++; |
| | | 1192 | | } |
| | 1 | 1193 | | builder.AppendLine($" {targetPath}.Add({itemVar});"); |
| | | 1194 | | } |
| | | 1195 | | else |
| | | 1196 | | { |
| | | 1197 | | // Primitive element type |
| | 5 | 1198 | | GeneratePrimitiveListAdd(builder, elementType, index, targetPath); |
| | | 1199 | | } |
| | | 1200 | | |
| | 6 | 1201 | | builder.AppendLine(" }"); |
| | 6 | 1202 | | } |
| | | 1203 | | |
| | | 1204 | | private static void GenerateDictionaryBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string tar |
| | | 1205 | | { |
| | 4 | 1206 | | builder.AppendLine($" // Bind dictionary: {prop.Name}"); |
| | 4 | 1207 | | builder.AppendLine($" var {sectionVar} = section.GetSection(\"{prop.Name}\");"); |
| | 4 | 1208 | | GenerateDictionaryBindingCore(builder, prop, index, $"{targetPath}.{prop.Name}", sectionVar); |
| | 4 | 1209 | | } |
| | | 1210 | | |
| | | 1211 | | private static void GenerateDictionaryBindingCore(StringBuilder builder, OptionsPropertyInfo prop, int index, string |
| | | 1212 | | { |
| | 4 | 1213 | | var elementType = prop.ElementTypeName ?? "string"; |
| | 4 | 1214 | | var hasNestedProps = prop.NestedProperties != null && prop.NestedProperties.Count > 0; |
| | | 1215 | | |
| | 4 | 1216 | | builder.AppendLine($" {targetPath}.Clear();"); |
| | 4 | 1217 | | builder.AppendLine($" foreach (var child in {sectionVar}.GetChildren())"); |
| | 4 | 1218 | | builder.AppendLine(" {"); |
| | | 1219 | | |
| | 4 | 1220 | | if (hasNestedProps) |
| | | 1221 | | { |
| | | 1222 | | // Complex value type |
| | 1 | 1223 | | var itemVar = $"item{index}"; |
| | 1 | 1224 | | builder.AppendLine($" var {itemVar} = new {elementType}();"); |
| | 1 | 1225 | | var nestedIndex = index * 100; |
| | 6 | 1226 | | foreach (var nestedProp in prop.NestedProperties!) |
| | | 1227 | | { |
| | 2 | 1228 | | GenerateChildPropertyBinding(builder, nestedProp, nestedIndex, itemVar, "child"); |
| | 2 | 1229 | | nestedIndex++; |
| | | 1230 | | } |
| | 1 | 1231 | | builder.AppendLine($" {targetPath}[child.Key] = {itemVar};"); |
| | | 1232 | | } |
| | | 1233 | | else |
| | | 1234 | | { |
| | | 1235 | | // Primitive value type |
| | 3 | 1236 | | GeneratePrimitiveDictionaryAdd(builder, elementType, index, targetPath); |
| | | 1237 | | } |
| | | 1238 | | |
| | 4 | 1239 | | builder.AppendLine(" }"); |
| | 4 | 1240 | | } |
| | | 1241 | | |
| | | 1242 | | private static void GenerateChildPropertyBinding(StringBuilder builder, OptionsPropertyInfo prop, int index, string |
| | | 1243 | | { |
| | 6 | 1244 | | var varName = $"cv{index}"; |
| | 6 | 1245 | | var baseTypeName = GetBaseTypeName(prop.TypeName); |
| | | 1246 | | |
| | 6 | 1247 | | builder.Append($" if ({sectionVar}[\"{prop.Name}\"] is {{ }} {varName}"); |
| | | 1248 | | |
| | 6 | 1249 | | if (prop.IsEnum && prop.EnumTypeName != null) |
| | | 1250 | | { |
| | 0 | 1251 | | builder.AppendLine($" && global::System.Enum.TryParse<{prop.EnumTypeName}>({varName}, true, out var cp{index |
| | | 1252 | | } |
| | 6 | 1253 | | else if (baseTypeName == "string" || baseTypeName == "global::System.String") |
| | | 1254 | | { |
| | 3 | 1255 | | builder.AppendLine($") {targetVar}.{prop.Name} = {varName};"); |
| | | 1256 | | } |
| | 3 | 1257 | | else if (baseTypeName == "int" || baseTypeName == "global::System.Int32") |
| | | 1258 | | { |
| | 3 | 1259 | | builder.AppendLine($" && int.TryParse({varName}, out var cp{index})) {targetVar}.{prop.Name} = cp{index};"); |
| | | 1260 | | } |
| | 0 | 1261 | | else if (baseTypeName == "bool" || baseTypeName == "global::System.Boolean") |
| | | 1262 | | { |
| | 0 | 1263 | | builder.AppendLine($" && bool.TryParse({varName}, out var cp{index})) {targetVar}.{prop.Name} = cp{index};") |
| | | 1264 | | } |
| | | 1265 | | else |
| | | 1266 | | { |
| | 0 | 1267 | | builder.AppendLine($") {{ }} // Skipped: {prop.TypeName}"); |
| | | 1268 | | } |
| | 0 | 1269 | | } |
| | | 1270 | | |
| | | 1271 | | private static void GeneratePrimitiveCollectionAdd(StringBuilder builder, string elementType, int index, string list |
| | | 1272 | | { |
| | 2 | 1273 | | var baseType = GetBaseTypeName(elementType); |
| | | 1274 | | |
| | 2 | 1275 | | if (baseType == "string" || baseType == "global::System.String") |
| | | 1276 | | { |
| | 1 | 1277 | | builder.AppendLine($" if (child.Value is {{ }} val{index}) {listVar}.Add(val{index});"); |
| | | 1278 | | } |
| | 1 | 1279 | | else if (baseType == "int" || baseType == "global::System.Int32") |
| | | 1280 | | { |
| | 1 | 1281 | | builder.AppendLine($" if (child.Value is {{ }} val{index} && int.TryParse(val{index}, out |
| | | 1282 | | } |
| | | 1283 | | else |
| | | 1284 | | { |
| | 0 | 1285 | | builder.AppendLine($" // Skipped: unsupported element type {elementType}"); |
| | | 1286 | | } |
| | 0 | 1287 | | } |
| | | 1288 | | |
| | | 1289 | | private static void GeneratePrimitiveListAdd(StringBuilder builder, string elementType, int index, string targetPath |
| | | 1290 | | { |
| | 5 | 1291 | | var baseType = GetBaseTypeName(elementType); |
| | | 1292 | | |
| | 5 | 1293 | | if (baseType == "string" || baseType == "global::System.String") |
| | | 1294 | | { |
| | 4 | 1295 | | builder.AppendLine($" if (child.Value is {{ }} val{index}) {targetPath}.Add(val{index});" |
| | | 1296 | | } |
| | 1 | 1297 | | else if (baseType == "int" || baseType == "global::System.Int32") |
| | | 1298 | | { |
| | 1 | 1299 | | builder.AppendLine($" if (child.Value is {{ }} val{index} && int.TryParse(val{index}, out |
| | | 1300 | | } |
| | | 1301 | | else |
| | | 1302 | | { |
| | 0 | 1303 | | builder.AppendLine($" // Skipped: unsupported element type {elementType}"); |
| | | 1304 | | } |
| | 0 | 1305 | | } |
| | | 1306 | | |
| | | 1307 | | private static void GeneratePrimitiveDictionaryAdd(StringBuilder builder, string elementType, int index, string targ |
| | | 1308 | | { |
| | 3 | 1309 | | var baseType = GetBaseTypeName(elementType); |
| | | 1310 | | |
| | 3 | 1311 | | if (baseType == "string" || baseType == "global::System.String") |
| | | 1312 | | { |
| | 1 | 1313 | | builder.AppendLine($" if (child.Value is {{ }} val{index}) {targetPath}[child.Key] = val{ |
| | | 1314 | | } |
| | 2 | 1315 | | else if (baseType == "int" || baseType == "global::System.Int32") |
| | | 1316 | | { |
| | 2 | 1317 | | builder.AppendLine($" if (child.Value is {{ }} val{index} && int.TryParse(val{index}, out |
| | | 1318 | | } |
| | | 1319 | | else |
| | | 1320 | | { |
| | 0 | 1321 | | builder.AppendLine($" // Skipped: unsupported element type {elementType}"); |
| | | 1322 | | } |
| | 0 | 1323 | | } |
| | | 1324 | | |
| | | 1325 | | private static string GetNonNullableTypeName(string typeName) |
| | | 1326 | | { |
| | 2 | 1327 | | if (typeName.EndsWith("?")) |
| | 0 | 1328 | | return typeName.Substring(0, typeName.Length - 1); |
| | 2 | 1329 | | return typeName; |
| | | 1330 | | } |
| | | 1331 | | |
| | | 1332 | | private static string GetBaseTypeName(string typeName) |
| | | 1333 | | { |
| | | 1334 | | // Handle nullable types like "global::System.Nullable<int>" or "int?" |
| | 156 | 1335 | | if (typeName.StartsWith("global::System.Nullable<") && typeName.EndsWith(">")) |
| | | 1336 | | { |
| | 0 | 1337 | | return typeName.Substring("global::System.Nullable<".Length, typeName.Length - "global::System.Nullable<".Le |
| | | 1338 | | } |
| | 156 | 1339 | | if (typeName.EndsWith("?")) |
| | | 1340 | | { |
| | 4 | 1341 | | return typeName.Substring(0, typeName.Length - 1); |
| | | 1342 | | } |
| | 152 | 1343 | | return typeName; |
| | | 1344 | | } |
| | | 1345 | | } |
| | | 1346 | | |