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