| | | 1 | | using System.Collections; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Management.Automation; |
| | | 4 | | using System.Reflection; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Xml; |
| | | 7 | | using System.Xml.Linq; |
| | | 8 | | using CsvHelper; |
| | | 9 | | using CsvHelper.Configuration; |
| | | 10 | | using Kestrun.Logging; |
| | | 11 | | using Kestrun.Models; |
| | | 12 | | using Kestrun.Utilities; |
| | | 13 | | using Microsoft.Extensions.Primitives; |
| | | 14 | | using Microsoft.OpenApi; |
| | | 15 | | using MongoDB.Bson; |
| | | 16 | | using MongoDB.Bson.Serialization; |
| | | 17 | | using PeterO.Cbor; |
| | | 18 | | using YamlDotNet.Serialization; |
| | | 19 | | using YamlDotNet.Serialization.NamingConventions; |
| | | 20 | | |
| | | 21 | | namespace Kestrun.Languages; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Information about a parameter to be injected into a script. |
| | | 25 | | /// </summary> |
| | | 26 | | public class ParameterForInjectionInfo : ParameterForInjectionInfoBase |
| | | 27 | | { |
| | | 28 | | private static ParameterMetadata Validate(ParameterMetadata? paramInfo) |
| | | 29 | | { |
| | 37 | 30 | | ArgumentNullException.ThrowIfNull(paramInfo); |
| | 36 | 31 | | return paramInfo; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Constructs a ParameterForInjectionInfo from an OpenApiParameter. |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 38 | | /// <param name="parameter">The OpenApiParameter to construct from.</param> |
| | | 39 | | public ParameterForInjectionInfo(ParameterMetadata paramInfo, OpenApiParameter? parameter) : |
| | 9 | 40 | | base(Validate(paramInfo).Name, Validate(paramInfo).ParameterType) |
| | | 41 | | { |
| | 8 | 42 | | ArgumentNullException.ThrowIfNull(parameter); |
| | 7 | 43 | | Type = parameter.Schema?.Type; |
| | 7 | 44 | | DefaultValue = parameter.Schema?.Default; |
| | 7 | 45 | | In = parameter.In; |
| | 7 | 46 | | if (parameter.Content is not null) |
| | | 47 | | { |
| | 0 | 48 | | foreach (var key in parameter.Content.Keys) |
| | | 49 | | { |
| | 0 | 50 | | ContentTypes.Add(key); |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | else |
| | | 54 | | { |
| | 7 | 55 | | Explode = parameter.Explode; |
| | 7 | 56 | | Style = parameter.Style; |
| | | 57 | | } |
| | 7 | 58 | | } |
| | | 59 | | /// <summary> |
| | | 60 | | /// Constructs a ParameterForInjectionInfo from an OpenApiRequestBody. |
| | | 61 | | /// </summary> |
| | | 62 | | /// <param name="paramInfo">The parameter metadata.</param> |
| | | 63 | | /// <param name="requestBody">The OpenApiRequestBody to construct from.</param> |
| | | 64 | | public ParameterForInjectionInfo(ParameterMetadata paramInfo, OpenApiRequestBody requestBody) : |
| | 10 | 65 | | base(Validate(paramInfo).Name, Validate(paramInfo).ParameterType) |
| | | 66 | | { |
| | 10 | 67 | | ArgumentNullException.ThrowIfNull(requestBody); |
| | 10 | 68 | | Type = requestBody.Content?.Values.FirstOrDefault()?.Schema?.Type; |
| | 10 | 69 | | var schema = requestBody.Content?.Values.FirstOrDefault()?.Schema; |
| | 10 | 70 | | if (schema is OpenApiSchemaReference) |
| | | 71 | | { |
| | 1 | 72 | | Type = JsonSchemaType.Object; |
| | | 73 | | } |
| | 9 | 74 | | else if (schema is OpenApiSchema sch) |
| | | 75 | | { |
| | 9 | 76 | | Type = sch.Type; |
| | 9 | 77 | | DefaultValue = sch.Default; |
| | | 78 | | } |
| | 10 | 79 | | In = null; |
| | 10 | 80 | | if (requestBody.Content is not null) |
| | | 81 | | { |
| | 40 | 82 | | foreach (var key in requestBody.Content.Keys) |
| | | 83 | | { |
| | 10 | 84 | | ContentTypes.Add(key); |
| | | 85 | | } |
| | | 86 | | } |
| | 10 | 87 | | } |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Adds parameters from the HTTP context to the PowerShell instance. |
| | | 91 | | /// </summary> |
| | | 92 | | /// <param name="context">The current HTTP context.</param> |
| | | 93 | | /// <param name="ps">The PowerShell instance to which parameters will be added.</param> |
| | | 94 | | internal static void InjectParameters(KestrunContext context, PowerShell ps) |
| | | 95 | | { |
| | 15 | 96 | | if (context.HttpContext.GetEndpoint()? |
| | 15 | 97 | | .Metadata |
| | 26 | 98 | | .FirstOrDefault(m => m is List<ParameterForInjectionInfo>) is not List<ParameterForInjectionInfo> paramet |
| | | 99 | | { |
| | 4 | 100 | | return; |
| | | 101 | | } |
| | | 102 | | |
| | 11 | 103 | | var logger = context.Host.Logger; |
| | 11 | 104 | | if (logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 105 | | { |
| | 11 | 106 | | logger.Debug("Injecting {Count} parameters into PowerShell script.", parameters.Count); |
| | | 107 | | } |
| | | 108 | | |
| | 44 | 109 | | foreach (var param in parameters) |
| | | 110 | | { |
| | 11 | 111 | | InjectSingleParameter(context, ps, param); |
| | | 112 | | } |
| | 11 | 113 | | } |
| | | 114 | | |
| | | 115 | | /// <summary> |
| | | 116 | | /// Mapping of content types to body conversion functions. |
| | | 117 | | /// </summary> |
| | 1 | 118 | | private static readonly IReadOnlyDictionary<string, Func<KestrunContext, string, object?>> BodyConverters = |
| | 1 | 119 | | new Dictionary<string, Func<KestrunContext, string, object?>>(StringComparer.OrdinalIgnoreCase) |
| | 1 | 120 | | { |
| | 0 | 121 | | ["application/json"] = (_, raw) => ConvertJsonToHashtable(raw), |
| | 0 | 122 | | ["application/yaml"] = (_, raw) => ConvertYamlToHashtable(raw), |
| | 1 | 123 | | // XML conversion needs to consider OpenAPI XML modeling; handled in the callers that have ParameterType. |
| | 0 | 124 | | ["application/bson"] = (_, raw) => ConvertBsonToHashtable(raw), |
| | 0 | 125 | | ["application/cbor"] = (_, raw) => ConvertCborToHashtable(raw), |
| | 0 | 126 | | ["text/csv"] = (_, raw) => ConvertCsvToHashtable(raw), |
| | 1 | 127 | | |
| | 1 | 128 | | // This one typically needs the request form, not the raw string. |
| | 0 | 129 | | ["application/x-www-form-urlencoded"] = (ctx, _) => ConvertFormToHashtable(ctx.Request.Form), |
| | 1 | 130 | | }; |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Determines whether the body parameter should be converted based on its type information. |
| | | 134 | | /// </summary> |
| | | 135 | | /// <param name="param">The parameter information.</param> |
| | | 136 | | /// <param name="converted">The converted object.</param> |
| | | 137 | | /// <returns>True if the body should be converted; otherwise, false.</returns> |
| | | 138 | | private static bool ShouldConvertBody(ParameterForInjectionInfo param, object? converted) => |
| | 11 | 139 | | converted is string && param.Type is null && param.ParameterType is not null && param.ParameterType != typeof(string |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Tries to convert the body parameter based on the content types specified. |
| | | 143 | | /// </summary> |
| | | 144 | | /// <param name="context">The current Kestrun context.</param> |
| | | 145 | | /// <param name="param">The parameter information.</param> |
| | | 146 | | /// <param name="rawString">The raw body string.</param> |
| | | 147 | | private static object? TryConvertBodyByContentType(KestrunContext context, ParameterForInjectionInfo param, string r |
| | | 148 | | { |
| | | 149 | | // Collect canonical content types once |
| | 0 | 150 | | var canonicalTypes = param.ContentTypes |
| | 0 | 151 | | .Select(MediaTypeHelper.Canonicalize) |
| | 0 | 152 | | .Where(ct => !string.IsNullOrWhiteSpace(ct)) |
| | 0 | 153 | | .Distinct(StringComparer.OrdinalIgnoreCase); |
| | | 154 | | // Try each content type in order |
| | 0 | 155 | | foreach (var ct in canonicalTypes) |
| | | 156 | | { |
| | 0 | 157 | | if (ct.Equals("application/xml", StringComparison.OrdinalIgnoreCase)) |
| | | 158 | | { |
| | 0 | 159 | | return ConvertXmlBodyToParameterType(rawString, param.ParameterType); |
| | | 160 | | } |
| | | 161 | | |
| | 0 | 162 | | if (BodyConverters.TryGetValue(ct, out var converter)) |
| | | 163 | | { |
| | | 164 | | // Special-case: form-url-encoded conversion only makes sense with explode/form style. |
| | 0 | 165 | | if (ct.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && |
| | 0 | 166 | | !(param.Explode || param.Style == ParameterStyle.Form)) |
| | | 167 | | { |
| | | 168 | | continue; |
| | | 169 | | } |
| | | 170 | | // Use the converter |
| | 0 | 171 | | return converter(context, rawString); |
| | | 172 | | } |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | // If it's "form" style explode, you can still treat it as a hashtable even without explicit content-type. |
| | 0 | 176 | | return param.Style == ParameterStyle.Form && param.Explode && context.Request.Form is not null |
| | 0 | 177 | | ? ConvertFormToHashtable(context.Request.Form) |
| | 0 | 178 | | : (object?)null; |
| | 0 | 179 | | } |
| | | 180 | | |
| | | 181 | | /// <summary> |
| | | 182 | | /// Injects a single parameter into the PowerShell instance based on its location and type. |
| | | 183 | | /// </summary> |
| | | 184 | | /// <param name="context">The current Kestrun context.</param> |
| | | 185 | | /// <param name="ps">The PowerShell instance to inject parameters into.</param> |
| | | 186 | | /// <param name="param">The parameter information to inject.</param> |
| | | 187 | | private static void InjectSingleParameter(KestrunContext context, PowerShell ps, ParameterForInjectionInfo param) |
| | | 188 | | { |
| | 11 | 189 | | var logger = context.Host.Logger; |
| | 11 | 190 | | var name = param.Name; |
| | | 191 | | |
| | 11 | 192 | | LogInjectingParameter(logger, param); |
| | | 193 | | |
| | 11 | 194 | | var converted = GetConvertedParameterValue(context, param, out var shouldLog); |
| | 11 | 195 | | converted = ConvertBodyParameterIfNeeded(context, param, converted); |
| | | 196 | | |
| | 11 | 197 | | LogAddingParameter(logger, name, converted, shouldLog); |
| | | 198 | | |
| | 11 | 199 | | _ = ps.AddParameter(name, converted); |
| | 11 | 200 | | StoreResolvedParameter(context, param, name, converted); |
| | 11 | 201 | | } |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Logs the injection of a parameter when debug logging is enabled. |
| | | 205 | | /// </summary> |
| | | 206 | | /// <param name="logger">The host logger.</param> |
| | | 207 | | /// <param name="param">The parameter being injected.</param> |
| | | 208 | | private static void LogInjectingParameter(Serilog.ILogger logger, ParameterForInjectionInfo param) |
| | | 209 | | { |
| | 11 | 210 | | if (!logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 211 | | { |
| | 0 | 212 | | return; |
| | | 213 | | } |
| | | 214 | | |
| | 11 | 215 | | var schemaType = param.Type?.ToString() ?? "<none>"; |
| | 11 | 216 | | var clrType = param.ParameterType?.FullName ?? "<unknown>"; |
| | 11 | 217 | | logger.Debug( |
| | 11 | 218 | | "Injecting parameter '{Name}' schemaType='{SchemaType}' clrType='{ClrType}' from '{In}'.", |
| | 11 | 219 | | param.Name, |
| | 11 | 220 | | schemaType, |
| | 11 | 221 | | clrType, |
| | 11 | 222 | | param.In); |
| | 11 | 223 | | } |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Gets the converted parameter value from the current request context. |
| | | 227 | | /// </summary> |
| | | 228 | | /// <param name="context">The current Kestrun context.</param> |
| | | 229 | | /// <param name="param">The parameter metadata.</param> |
| | | 230 | | /// <param name="shouldLog">Whether the value should be logged.</param> |
| | | 231 | | /// <returns>The converted parameter value.</returns> |
| | | 232 | | private static object? GetConvertedParameterValue(KestrunContext context, ParameterForInjectionInfo param, out bool |
| | | 233 | | { |
| | 11 | 234 | | shouldLog = true; |
| | | 235 | | |
| | 11 | 236 | | return context.Request.Form is not null && context.Request.HasFormContentType |
| | 11 | 237 | | ? ConvertFormToValue(context.Request.Form, param) |
| | 11 | 238 | | : GetParameterValueFromContext(context, param, out shouldLog); |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | /// <summary> |
| | | 242 | | /// Converts a request-body parameter from a raw string to a structured object when possible. |
| | | 243 | | /// </summary> |
| | | 244 | | /// <param name="context">The current Kestrun context.</param> |
| | | 245 | | /// <param name="param">The parameter metadata.</param> |
| | | 246 | | /// <param name="converted">The current converted value.</param> |
| | | 247 | | /// <returns>The updated value, possibly converted to an object/hashtable.</returns> |
| | | 248 | | private static object? ConvertBodyParameterIfNeeded(KestrunContext context, ParameterForInjectionInfo param, object? |
| | | 249 | | { |
| | 11 | 250 | | if (!ShouldConvertBody(param, converted)) |
| | | 251 | | { |
| | 11 | 252 | | return converted; |
| | | 253 | | } |
| | | 254 | | |
| | 0 | 255 | | var rawString = (string)converted!; |
| | 0 | 256 | | var bodyObj = TryConvertBodyByContentType(context, param, rawString); |
| | | 257 | | |
| | 0 | 258 | | if (bodyObj is not null) |
| | | 259 | | { |
| | 0 | 260 | | return bodyObj; |
| | | 261 | | } |
| | | 262 | | |
| | 0 | 263 | | context.Logger.WarningSanitized( |
| | 0 | 264 | | "Unable to convert body parameter '{Name}' with content types: {ContentTypes}. Using raw string value.", |
| | 0 | 265 | | param.Name, |
| | 0 | 266 | | param.ContentTypes); |
| | | 267 | | |
| | 0 | 268 | | return converted; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | /// <summary> |
| | | 272 | | /// Logs the addition of a parameter to the PowerShell invocation when requested and debug logging is enabled. |
| | | 273 | | /// </summary> |
| | | 274 | | /// <param name="logger">The host logger.</param> |
| | | 275 | | /// <param name="name">The parameter name.</param> |
| | | 276 | | /// <param name="value">The value to be added.</param> |
| | | 277 | | /// <param name="shouldLog">Whether logging should be performed.</param> |
| | | 278 | | private static void LogAddingParameter(Serilog.ILogger logger, string name, object? value, bool shouldLog) |
| | | 279 | | { |
| | 11 | 280 | | if (!shouldLog || !logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 281 | | { |
| | 0 | 282 | | return; |
| | | 283 | | } |
| | | 284 | | |
| | 11 | 285 | | var valueType = value?.GetType().FullName ?? "<null>"; |
| | 11 | 286 | | logger.DebugSanitized("Adding parameter '{Name}' ({ValueType}): {ConvertedValue}", name, valueType, value); |
| | 11 | 287 | | } |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Stores the resolved parameter on the request context, either as the request body or a named parameter. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <param name="context">The current Kestrun context.</param> |
| | | 293 | | /// <param name="param">The parameter metadata.</param> |
| | | 294 | | /// <param name="name">The parameter name.</param> |
| | | 295 | | /// <param name="value">The resolved value.</param> |
| | | 296 | | private static void StoreResolvedParameter(KestrunContext context, ParameterForInjectionInfo param, string name, obj |
| | | 297 | | { |
| | 11 | 298 | | var resolved = new ParameterForInjectionResolved(param, value); |
| | 11 | 299 | | if (param.IsRequestBody) |
| | | 300 | | { |
| | 9 | 301 | | context.Parameters.Body = resolved; |
| | 9 | 302 | | return; |
| | | 303 | | } |
| | | 304 | | |
| | 2 | 305 | | context.Parameters.Parameters[name] = resolved; |
| | 2 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <summary> |
| | | 309 | | /// Retrieves and converts the parameter value from the HTTP context. |
| | | 310 | | /// </summary> |
| | | 311 | | /// <param name="context">The current HTTP context.</param> |
| | | 312 | | /// <param name="param">The parameter information.</param> |
| | | 313 | | /// <param name="shouldLog">Indicates whether logging should be performed.</param> |
| | | 314 | | /// <returns>The converted parameter value.</returns> |
| | | 315 | | private static object? GetParameterValueFromContext(KestrunContext context, ParameterForInjectionInfo param, out boo |
| | | 316 | | { |
| | 11 | 317 | | shouldLog = true; |
| | 11 | 318 | | var logger = context.Host.Logger; |
| | 11 | 319 | | var raw = GetRawValue(param, context); |
| | | 320 | | |
| | 11 | 321 | | if (raw is null) |
| | | 322 | | { |
| | 1 | 323 | | if (param.DefaultValue is not null) |
| | | 324 | | { |
| | 1 | 325 | | raw = param.DefaultValue.GetValue<object>(); |
| | | 326 | | } |
| | | 327 | | else |
| | | 328 | | { |
| | 0 | 329 | | shouldLog = false; |
| | 0 | 330 | | return null; |
| | | 331 | | } |
| | | 332 | | } |
| | | 333 | | |
| | 11 | 334 | | if (logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 335 | | { |
| | 11 | 336 | | logger.Debug("Raw value for parameter '{Name}': {RawValue}", param.Name, raw); |
| | | 337 | | } |
| | | 338 | | |
| | 11 | 339 | | var (singleValue, multiValue) = NormalizeRaw(raw); |
| | | 340 | | |
| | 11 | 341 | | if (singleValue is null && multiValue is null) |
| | | 342 | | { |
| | 0 | 343 | | shouldLog = false; |
| | 0 | 344 | | return null; |
| | | 345 | | } |
| | | 346 | | |
| | 11 | 347 | | return ConvertValue(context, param, singleValue, multiValue); |
| | | 348 | | } |
| | | 349 | | |
| | | 350 | | /// <summary> |
| | | 351 | | /// Retrieves the raw value of a parameter from the HTTP context based on its location. |
| | | 352 | | /// </summary> |
| | | 353 | | /// <param name="param">The parameter information.</param> |
| | | 354 | | /// <param name="context">The current HTTP context.</param> |
| | | 355 | | /// <returns>The raw value of the parameter.</returns> |
| | | 356 | | private static object? GetRawValue(ParameterForInjectionInfo param, KestrunContext context) |
| | | 357 | | { |
| | 11 | 358 | | return param.In switch |
| | 11 | 359 | | { |
| | 11 | 360 | | ParameterLocation.Path => |
| | 0 | 361 | | context.Request.RouteValues.TryGetValue(param.Name, out var routeVal) |
| | 0 | 362 | | ? routeVal |
| | 0 | 363 | | : null, |
| | 11 | 364 | | |
| | 11 | 365 | | ParameterLocation.Query => |
| | 2 | 366 | | context.Request.Query.TryGetValue(param.Name, out var queryVal) |
| | 2 | 367 | | ? (string?)queryVal |
| | 2 | 368 | | : null, |
| | 11 | 369 | | |
| | 11 | 370 | | ParameterLocation.Header => |
| | 0 | 371 | | context.Request.Headers.TryGetValue(param.Name, out var headerVal) |
| | 0 | 372 | | ? (string?)headerVal |
| | 0 | 373 | | : null, |
| | 11 | 374 | | |
| | 11 | 375 | | ParameterLocation.Cookie => |
| | 0 | 376 | | context.Request.Cookies.TryGetValue(param.Name, out var cookieVal) |
| | 0 | 377 | | ? cookieVal |
| | 0 | 378 | | : null, |
| | 9 | 379 | | null => (context.Request.Form is not null && context.Request.HasFormContentType) ? |
| | 9 | 380 | | context.Request.Form : |
| | 9 | 381 | | context.Request.Body, |
| | 11 | 382 | | |
| | 0 | 383 | | _ => null, |
| | 11 | 384 | | }; |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | /// <summary> |
| | | 388 | | /// Normalizes the raw parameter value into single and multi-value forms. |
| | | 389 | | /// </summary> |
| | | 390 | | /// <param name="raw">The raw parameter value.</param> |
| | | 391 | | /// <returns>A tuple containing the single and multi-value forms of the parameter.</returns> |
| | | 392 | | private static (string? single, string?[]? multi) NormalizeRaw(object raw) |
| | | 393 | | { |
| | 11 | 394 | | string?[]? multiValue = null; |
| | | 395 | | |
| | | 396 | | string? singleValue; |
| | | 397 | | switch (raw) |
| | | 398 | | { |
| | | 399 | | case StringValues sv: |
| | 0 | 400 | | multiValue = [.. sv]; |
| | 0 | 401 | | singleValue = sv.Count > 0 ? sv[0] : null; |
| | 0 | 402 | | break; |
| | | 403 | | |
| | | 404 | | case string s: |
| | 10 | 405 | | singleValue = s; |
| | 10 | 406 | | break; |
| | | 407 | | |
| | | 408 | | default: |
| | 1 | 409 | | singleValue = raw?.ToString(); |
| | | 410 | | break; |
| | | 411 | | } |
| | | 412 | | |
| | 11 | 413 | | return (singleValue, multiValue); |
| | | 414 | | } |
| | | 415 | | |
| | | 416 | | /// <summary> |
| | | 417 | | /// Converts the parameter value to the appropriate type based on the JSON schema type. |
| | | 418 | | /// </summary> |
| | | 419 | | /// <param name="context">The current HTTP context.</param> |
| | | 420 | | /// <param name="param">The parameter information.</param> |
| | | 421 | | /// <param name="singleValue">The single value of the parameter.</param> |
| | | 422 | | /// <param name="multiValue">The multi-value of the parameter.</param> |
| | | 423 | | /// <returns>The converted parameter value.</returns> |
| | | 424 | | private static object? ConvertValue(KestrunContext context, ParameterForInjectionInfo param, |
| | | 425 | | string? singleValue, string?[]? multiValue) |
| | | 426 | | { |
| | | 427 | | // Convert based on schema type |
| | 11 | 428 | | return param.Type switch |
| | 11 | 429 | | { |
| | 2 | 430 | | JsonSchemaType.Integer => int.TryParse(singleValue, out var i) ? (int?)i : null, |
| | 0 | 431 | | JsonSchemaType.Number => double.TryParse(singleValue, out var d) ? (double?)d : null, |
| | 0 | 432 | | JsonSchemaType.Boolean => bool.TryParse(singleValue, out var b) ? (bool?)b : null, |
| | 0 | 433 | | JsonSchemaType.Array => multiValue ?? (singleValue is not null ? new[] { singleValue } : null), // keep your |
| | 9 | 434 | | JsonSchemaType.Object => param.IsRequestBody |
| | 9 | 435 | | ? ConvertBodyBasedOnContentType(context, singleValue ?? "", param) |
| | 9 | 436 | | : singleValue, |
| | 0 | 437 | | JsonSchemaType.String => singleValue, |
| | 0 | 438 | | _ => singleValue, |
| | 11 | 439 | | }; |
| | | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Converts the request body based on the Content-Type header. |
| | | 444 | | /// </summary> |
| | | 445 | | /// <param name="context">The current Kestrun context.</param> |
| | | 446 | | /// <param name="rawBodyString">The raw body string from the request.</param> |
| | | 447 | | /// <param name="param">The parameter information.</param> |
| | | 448 | | /// <returns>The converted body object.</returns> |
| | | 449 | | /// <exception cref="InvalidOperationException">Thrown when the Content-Type header is missing and cannot convert bo |
| | | 450 | | private static object? ConvertBodyBasedOnContentType( |
| | | 451 | | KestrunContext context, |
| | | 452 | | string rawBodyString, |
| | | 453 | | ParameterForInjectionInfo param) |
| | | 454 | | { |
| | 9 | 455 | | var isSingleContentType = param.ContentTypes.Count == 1; |
| | | 456 | | |
| | 9 | 457 | | var requestMediaType = MediaTypeHelper.Canonicalize(context.Request.ContentType); |
| | | 458 | | |
| | 9 | 459 | | if (string.IsNullOrEmpty(requestMediaType)) |
| | | 460 | | { |
| | 1 | 461 | | if (!isSingleContentType) |
| | | 462 | | { |
| | 0 | 463 | | throw new InvalidOperationException( |
| | 0 | 464 | | "Content-Type header is missing; cannot convert body to object."); |
| | | 465 | | } |
| | | 466 | | |
| | 1 | 467 | | var inferred = MediaTypeHelper.Canonicalize(param.ContentTypes[0]); |
| | 1 | 468 | | return ConvertByCanonicalMediaType(inferred, context, rawBodyString, param); |
| | | 469 | | } |
| | | 470 | | |
| | 8 | 471 | | return ConvertByCanonicalMediaType(requestMediaType, context, rawBodyString, param); |
| | | 472 | | } |
| | | 473 | | |
| | | 474 | | /// <summary> |
| | | 475 | | /// Converts the body string to an object based on the canonical media type. |
| | | 476 | | /// </summary> |
| | | 477 | | /// <param name="canonicalMediaType"> The canonical media type of the request body.</param> |
| | | 478 | | /// <param name="context"> The current Kestrun context.</param> |
| | | 479 | | /// <param name="rawBodyString"> The raw body string from the request.</param> |
| | | 480 | | /// <param name="param">The parameter information.</param> |
| | | 481 | | /// <returns> The converted body object.</returns> |
| | | 482 | | private static object? ConvertByCanonicalMediaType( |
| | | 483 | | string canonicalMediaType, |
| | | 484 | | KestrunContext context, |
| | | 485 | | string rawBodyString, |
| | | 486 | | ParameterForInjectionInfo param) |
| | | 487 | | { |
| | 9 | 488 | | return canonicalMediaType switch |
| | 9 | 489 | | { |
| | 2 | 490 | | "application/json" => ConvertJsonToHashtable(rawBodyString), |
| | 1 | 491 | | "application/yaml" => ConvertYamlToHashtable(rawBodyString), |
| | 2 | 492 | | "application/xml" => ConvertXmlBodyToParameterType(rawBodyString, param.ParameterType), |
| | 1 | 493 | | "application/bson" => ConvertBsonToHashtable(rawBodyString), |
| | 1 | 494 | | "application/cbor" => ConvertCborToHashtable(rawBodyString), |
| | 2 | 495 | | "text/csv" => ConvertCsvToHashtable(rawBodyString), |
| | 9 | 496 | | "application/x-www-form-urlencoded" => |
| | 0 | 497 | | ConvertFormToHashtable(context.Request.Form), |
| | 0 | 498 | | _ => rawBodyString, |
| | 9 | 499 | | }; |
| | | 500 | | } |
| | | 501 | | |
| | | 502 | | /// <summary> |
| | | 503 | | /// CBOR deserializer instance. |
| | | 504 | | /// </summary> |
| | 1 | 505 | | private static readonly IDeserializer YamlDeserializer = |
| | 1 | 506 | | new DeserializerBuilder() |
| | 1 | 507 | | .WithNamingConvention(CamelCaseNamingConvention.Instance) |
| | 1 | 508 | | .Build(); |
| | | 509 | | |
| | | 510 | | private static Hashtable? ConvertYamlToHashtable(string yaml) |
| | | 511 | | { |
| | 1 | 512 | | if (string.IsNullOrWhiteSpace(yaml)) |
| | | 513 | | { |
| | 0 | 514 | | return null; |
| | | 515 | | } |
| | | 516 | | |
| | | 517 | | // Top-level YAML mapping → Hashtable |
| | 1 | 518 | | var ht = YamlDeserializer.Deserialize<Hashtable>(yaml); |
| | 1 | 519 | | return ht; |
| | | 520 | | } |
| | | 521 | | private static object? ConvertJsonToHashtable(string? json) |
| | | 522 | | { |
| | 2 | 523 | | if (string.IsNullOrWhiteSpace(json)) |
| | | 524 | | { |
| | 0 | 525 | | return null; |
| | | 526 | | } |
| | | 527 | | |
| | 2 | 528 | | using var doc = JsonDocument.Parse(json); |
| | 2 | 529 | | return JsonElementToClr(doc.RootElement); |
| | 2 | 530 | | } |
| | | 531 | | |
| | | 532 | | private static object? JsonElementToClr(JsonElement element) |
| | | 533 | | { |
| | 6 | 534 | | return element.ValueKind switch |
| | 6 | 535 | | { |
| | 2 | 536 | | JsonValueKind.Object => ToHashtable(element), |
| | 0 | 537 | | JsonValueKind.Array => ToArray(element), |
| | 2 | 538 | | JsonValueKind.String => element.GetString(), |
| | 2 | 539 | | JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDouble(), |
| | 0 | 540 | | JsonValueKind.True => true, |
| | 0 | 541 | | JsonValueKind.False => false, |
| | 0 | 542 | | JsonValueKind.Null => null, |
| | 0 | 543 | | JsonValueKind.Undefined => null, |
| | 0 | 544 | | _ => null |
| | 6 | 545 | | }; |
| | | 546 | | } |
| | | 547 | | |
| | | 548 | | private static Hashtable ToHashtable(JsonElement element) |
| | | 549 | | { |
| | 2 | 550 | | var ht = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | 12 | 551 | | foreach (var prop in element.EnumerateObject()) |
| | | 552 | | { |
| | 4 | 553 | | ht[prop.Name] = JsonElementToClr(prop.Value); |
| | | 554 | | } |
| | 2 | 555 | | return ht; |
| | | 556 | | } |
| | | 557 | | |
| | | 558 | | private static object?[] ToArray(JsonElement element) |
| | | 559 | | { |
| | 0 | 560 | | var list = new List<object?>(); |
| | 0 | 561 | | foreach (var item in element.EnumerateArray()) |
| | | 562 | | { |
| | 0 | 563 | | list.Add(JsonElementToClr(item)); |
| | | 564 | | } |
| | 0 | 565 | | return [.. list]; |
| | | 566 | | } |
| | | 567 | | |
| | | 568 | | private const int MaxObjectBindingDepth = 32; |
| | | 569 | | |
| | | 570 | | private static object? ConvertXmlBodyToParameterType(string xml, Type parameterType) |
| | | 571 | | { |
| | 3 | 572 | | if (string.IsNullOrWhiteSpace(xml)) |
| | | 573 | | { |
| | 0 | 574 | | return null; |
| | | 575 | | } |
| | | 576 | | |
| | | 577 | | XElement root; |
| | | 578 | | try |
| | | 579 | | { |
| | | 580 | | // Clients often include an XML declaration with an encoding (e.g. UTF-8). When parsing from a .NET |
| | | 581 | | // string (already decoded), some parsers can reject mismatched/pointless encoding declarations. |
| | | 582 | | // Strip the declaration if present. |
| | 3 | 583 | | var cleaned = xml.TrimStart('\uFEFF', '\u200B', '\u0000', ' ', '\t', '\r', '\n'); |
| | 3 | 584 | | if (cleaned.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase)) |
| | | 585 | | { |
| | 2 | 586 | | var endDecl = cleaned.IndexOf("?>", StringComparison.Ordinal); |
| | 2 | 587 | | if (endDecl >= 0) |
| | | 588 | | { |
| | 2 | 589 | | cleaned = cleaned[(endDecl + 2)..].TrimStart(); |
| | | 590 | | } |
| | | 591 | | } |
| | | 592 | | |
| | | 593 | | XDocument doc; |
| | | 594 | | try |
| | | 595 | | { |
| | 3 | 596 | | doc = XDocument.Parse(cleaned); |
| | 3 | 597 | | } |
| | 0 | 598 | | catch |
| | | 599 | | { |
| | 0 | 600 | | var settings = new XmlReaderSettings |
| | 0 | 601 | | { |
| | 0 | 602 | | DtdProcessing = DtdProcessing.Prohibit, |
| | 0 | 603 | | XmlResolver = null, |
| | 0 | 604 | | }; |
| | | 605 | | |
| | 0 | 606 | | using var reader = XmlReader.Create(new StringReader(cleaned), settings); |
| | 0 | 607 | | doc = XDocument.Load(reader); |
| | 0 | 608 | | } |
| | | 609 | | |
| | 3 | 610 | | root = doc.Root ?? throw new InvalidOperationException("XML document has no root element."); |
| | 3 | 611 | | } |
| | 0 | 612 | | catch |
| | | 613 | | { |
| | 0 | 614 | | return null; |
| | | 615 | | } |
| | | 616 | | |
| | | 617 | | // If the parameter expects a string, don't attempt to parse. |
| | 3 | 618 | | if (parameterType == typeof(string)) |
| | | 619 | | { |
| | 0 | 620 | | return xml; |
| | | 621 | | } |
| | | 622 | | |
| | 3 | 623 | | var xmlMetadata = XmlHelper.GetOpenApiXmlMetadataForType(parameterType); |
| | 3 | 624 | | var wrapped = XmlHelper.ToHashtable(root, xmlMetadata); |
| | | 625 | | |
| | | 626 | | // Normalize from XmlHelper's { RootName = { ... } } shape into the element map itself. |
| | 3 | 627 | | var rootMap = ExtractRootMapForBinding(wrapped, root.Name.LocalName); |
| | 3 | 628 | | if (rootMap is null) |
| | | 629 | | { |
| | 0 | 630 | | return null; |
| | | 631 | | } |
| | | 632 | | |
| | 3 | 633 | | NormalizeWrappedArrays(rootMap, xmlMetadata); |
| | | 634 | | |
| | | 635 | | // For PowerShell script classes, the runtime may produce a new (dynamic) type in the request runspace. |
| | | 636 | | // Creating an instance here (using a Type captured during route registration) can produce a type-identity |
| | | 637 | | // mismatch at parameter-binding time ("cannot convert Product to Product"). |
| | | 638 | | // Returning a hashtable lets PowerShell perform the conversion to the *current* runspace type. |
| | 3 | 639 | | if (parameterType == typeof(object) || typeof(IDictionary).IsAssignableFrom(parameterType) || parameterType.Asse |
| | | 640 | | { |
| | 1 | 641 | | return rootMap; |
| | | 642 | | } |
| | | 643 | | // Otherwise, attempt to convert to the target type. |
| | 2 | 644 | | return ConvertHashtableToObject(rootMap, parameterType, depth: 0); |
| | 0 | 645 | | } |
| | | 646 | | |
| | | 647 | | private static Hashtable? ExtractRootMapForBinding(Hashtable wrapped, string rootLocalName) |
| | | 648 | | { |
| | | 649 | | // XmlHelper.ToHashtable returns { rootName = childMap } plus any mapped attributes at the same level. |
| | 3 | 650 | | if (!TryGetHashtableValue(wrapped, rootLocalName, out var rootObj)) |
| | | 651 | | { |
| | | 652 | | // Fallback: if there's exactly one entry and it's a hashtable, use it. |
| | 0 | 653 | | if (wrapped.Count == 1) |
| | | 654 | | { |
| | 0 | 655 | | var only = wrapped.Values.Cast<object?>().FirstOrDefault(); |
| | 0 | 656 | | return only as Hashtable; |
| | | 657 | | } |
| | 0 | 658 | | return wrapped; |
| | | 659 | | } |
| | | 660 | | |
| | 3 | 661 | | if (rootObj is not Hashtable rootMap) |
| | | 662 | | { |
| | 0 | 663 | | return null; |
| | | 664 | | } |
| | | 665 | | |
| | | 666 | | // Merge any sibling keys (e.g., metadata-guided attributes) into the root map. |
| | 16 | 667 | | foreach (DictionaryEntry entry in wrapped) |
| | | 668 | | { |
| | 5 | 669 | | if (entry.Key is not string key) |
| | | 670 | | { |
| | | 671 | | continue; |
| | | 672 | | } |
| | | 673 | | |
| | 5 | 674 | | if (string.Equals(key, rootLocalName, StringComparison.OrdinalIgnoreCase)) |
| | | 675 | | { |
| | | 676 | | continue; |
| | | 677 | | } |
| | | 678 | | |
| | 2 | 679 | | rootMap[key] = entry.Value; |
| | | 680 | | } |
| | | 681 | | |
| | 3 | 682 | | return rootMap; |
| | | 683 | | } |
| | | 684 | | |
| | | 685 | | /// <summary> |
| | | 686 | | /// Normalizes wrapped arrays in the root map based on XML metadata. |
| | | 687 | | /// </summary> |
| | | 688 | | /// <param name="rootMap">The root hashtable map.</param> |
| | | 689 | | /// <param name="xmlMetadata">The XML metadata hashtable.</param> |
| | | 690 | | private static void NormalizeWrappedArrays(Hashtable rootMap, Hashtable? xmlMetadata) |
| | | 691 | | { |
| | 3 | 692 | | if (!TryGetXmlMetadataProperties(xmlMetadata, out var propsHash)) |
| | | 693 | | { |
| | 1 | 694 | | return; |
| | | 695 | | } |
| | | 696 | | |
| | 20 | 697 | | foreach (DictionaryEntry entry in propsHash) |
| | | 698 | | { |
| | 8 | 699 | | if (!TryGetWrappedArrayMetadata(entry, out var propertyName, out var xmlName)) |
| | | 700 | | { |
| | | 701 | | continue; |
| | | 702 | | } |
| | | 703 | | |
| | 2 | 704 | | if (!TryGetWrapperHashtable(rootMap, propertyName, xmlName, out var wrapper)) |
| | | 705 | | { |
| | | 706 | | continue; |
| | | 707 | | } |
| | | 708 | | |
| | 2 | 709 | | var unwrapped = TryUnwrapWrapper(wrapper); |
| | 2 | 710 | | if (unwrapped is not null) |
| | | 711 | | { |
| | 2 | 712 | | rootMap[propertyName] = unwrapped; |
| | | 713 | | } |
| | | 714 | | } |
| | 2 | 715 | | } |
| | | 716 | | |
| | | 717 | | /// <summary> |
| | | 718 | | /// Attempts to retrieve the <c>Properties</c> hashtable from XML metadata. |
| | | 719 | | /// </summary> |
| | | 720 | | /// <param name="xmlMetadata">XML metadata hashtable.</param> |
| | | 721 | | /// <param name="properties">The properties hashtable when present.</param> |
| | | 722 | | /// <returns><c>true</c> when the properties hashtable exists; otherwise <c>false</c>.</returns> |
| | | 723 | | private static bool TryGetXmlMetadataProperties(Hashtable? xmlMetadata, out Hashtable properties) |
| | | 724 | | { |
| | 3 | 725 | | if (xmlMetadata?["Properties"] is Hashtable propsHash) |
| | | 726 | | { |
| | 2 | 727 | | properties = propsHash; |
| | 2 | 728 | | return true; |
| | | 729 | | } |
| | | 730 | | |
| | 1 | 731 | | properties = default!; |
| | 1 | 732 | | return false; |
| | | 733 | | } |
| | | 734 | | |
| | | 735 | | /// <summary> |
| | | 736 | | /// Extracts metadata for a wrapped array property from a single <see cref="DictionaryEntry"/>. |
| | | 737 | | /// </summary> |
| | | 738 | | /// <param name="entry">Entry from <c>xmlMetadata.Properties</c>.</param> |
| | | 739 | | /// <param name="propertyName">The CLR property name.</param> |
| | | 740 | | /// <param name="xmlName">The XML element name (or the CLR name when not overridden).</param> |
| | | 741 | | /// <returns><c>true</c> when the entry describes a wrapped property; otherwise <c>false</c>.</returns> |
| | | 742 | | private static bool TryGetWrappedArrayMetadata(DictionaryEntry entry, out string propertyName, out string xmlName) |
| | | 743 | | { |
| | 8 | 744 | | if (entry.Key is not string propName || entry.Value is not Hashtable propMeta) |
| | | 745 | | { |
| | 0 | 746 | | propertyName = default!; |
| | 0 | 747 | | xmlName = default!; |
| | 0 | 748 | | return false; |
| | | 749 | | } |
| | | 750 | | |
| | 8 | 751 | | if (propMeta["Wrapped"] is not bool wrapped || !wrapped) |
| | | 752 | | { |
| | 6 | 753 | | propertyName = default!; |
| | 6 | 754 | | xmlName = default!; |
| | 6 | 755 | | return false; |
| | | 756 | | } |
| | | 757 | | |
| | 2 | 758 | | propertyName = propName; |
| | 2 | 759 | | xmlName = propMeta["Name"] as string ?? propName; |
| | 2 | 760 | | return true; |
| | | 761 | | } |
| | | 762 | | |
| | | 763 | | /// <summary> |
| | | 764 | | /// Attempts to find a wrapper hashtable for a wrapped array property in the root map. |
| | | 765 | | /// </summary> |
| | | 766 | | /// <param name="rootMap">The root map produced by XML parsing.</param> |
| | | 767 | | /// <param name="propertyName">CLR property name to search.</param> |
| | | 768 | | /// <param name="xmlName">XML element name to search (fallback).</param> |
| | | 769 | | /// <param name="wrapper">The wrapper hashtable if found.</param> |
| | | 770 | | /// <returns><c>true</c> when a wrapper hashtable is found; otherwise <c>false</c>.</returns> |
| | | 771 | | private static bool TryGetWrapperHashtable(Hashtable rootMap, string propertyName, string xmlName, out Hashtable wra |
| | | 772 | | { |
| | 2 | 773 | | if (!TryGetHashtableValue(rootMap, propertyName, out var raw) |
| | 2 | 774 | | && !TryGetHashtableValue(rootMap, xmlName, out raw)) |
| | | 775 | | { |
| | 0 | 776 | | wrapper = default!; |
| | 0 | 777 | | return false; |
| | | 778 | | } |
| | | 779 | | |
| | 2 | 780 | | if (raw is Hashtable wrapperHash) |
| | | 781 | | { |
| | 2 | 782 | | wrapper = wrapperHash; |
| | 2 | 783 | | return true; |
| | | 784 | | } |
| | | 785 | | |
| | 0 | 786 | | wrapper = default!; |
| | 0 | 787 | | return false; |
| | | 788 | | } |
| | | 789 | | |
| | | 790 | | /// <summary> |
| | | 791 | | /// Unwraps a wrapper hashtable into an item list/value when possible. |
| | | 792 | | /// </summary> |
| | | 793 | | /// <param name="wrapper">Wrapper hashtable.</param> |
| | | 794 | | /// <returns>The unwrapped value, or <c>null</c> if it cannot be unwrapped.</returns> |
| | | 795 | | private static object? TryUnwrapWrapper(Hashtable wrapper) |
| | | 796 | | { |
| | 2 | 797 | | return TryGetHashtableValue(wrapper, "Item", out var itemValue) |
| | 2 | 798 | | ? itemValue |
| | 2 | 799 | | : wrapper.Count == 1 |
| | 2 | 800 | | ? wrapper.Values.Cast<object?>().FirstOrDefault() |
| | 2 | 801 | | : null; |
| | | 802 | | } |
| | | 803 | | |
| | | 804 | | private static object? ConvertHashtableToObject(Hashtable data, Type targetType, int depth) |
| | | 805 | | { |
| | 2 | 806 | | if (depth >= MaxObjectBindingDepth) |
| | | 807 | | { |
| | 0 | 808 | | return null; |
| | | 809 | | } |
| | | 810 | | |
| | 2 | 811 | | var instance = Activator.CreateInstance(targetType, nonPublic: true); |
| | 2 | 812 | | if (instance is null) |
| | | 813 | | { |
| | 0 | 814 | | return null; |
| | | 815 | | } |
| | | 816 | | |
| | 2 | 817 | | var props = targetType |
| | 2 | 818 | | .GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| | 8 | 819 | | .Where(p => p.CanWrite && p.SetMethod is not null) |
| | 10 | 820 | | .ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); |
| | | 821 | | |
| | 2 | 822 | | var fields = targetType |
| | 2 | 823 | | .GetFields(BindingFlags.Public | BindingFlags.Instance) |
| | 2 | 824 | | .ToDictionary(f => f.Name, StringComparer.OrdinalIgnoreCase); |
| | | 825 | | |
| | 20 | 826 | | foreach (DictionaryEntry entry in data) |
| | | 827 | | { |
| | 8 | 828 | | if (entry.Key is not string rawKey) |
| | | 829 | | { |
| | | 830 | | continue; |
| | | 831 | | } |
| | | 832 | | |
| | 8 | 833 | | var key = rawKey.StartsWith('@') ? rawKey[1..] : rawKey; |
| | | 834 | | |
| | 8 | 835 | | if (props.TryGetValue(key, out var prop)) |
| | | 836 | | { |
| | 8 | 837 | | var converted = ConvertToTargetType(entry.Value, prop.PropertyType, depth + 1); |
| | 8 | 838 | | prop.SetValue(instance, converted); |
| | 8 | 839 | | continue; |
| | | 840 | | } |
| | | 841 | | |
| | 0 | 842 | | if (fields.TryGetValue(key, out var field)) |
| | | 843 | | { |
| | 0 | 844 | | var converted = ConvertToTargetType(entry.Value, field.FieldType, depth + 1); |
| | 0 | 845 | | field.SetValue(instance, converted); |
| | | 846 | | } |
| | | 847 | | } |
| | | 848 | | |
| | 2 | 849 | | return instance; |
| | | 850 | | } |
| | | 851 | | |
| | | 852 | | /// <summary> |
| | | 853 | | /// Converts a value to the specified target type, handling complex objects and collections. |
| | | 854 | | /// </summary> |
| | | 855 | | /// <param name="value">The value to convert.</param> |
| | | 856 | | /// <param name="targetType">The target type to convert to.</param> |
| | | 857 | | /// <param name="depth">The current recursion depth.</param> |
| | | 858 | | /// <returns>The converted value, or null if conversion is not possible.</returns> |
| | | 859 | | private static object? ConvertToTargetType(object? value, Type targetType, int depth) |
| | | 860 | | { |
| | 14 | 861 | | if (value is null) |
| | | 862 | | { |
| | 0 | 863 | | return null; |
| | | 864 | | } |
| | | 865 | | |
| | 14 | 866 | | targetType = UnwrapNullableTargetType(targetType); |
| | | 867 | | |
| | 14 | 868 | | return targetType.IsInstanceOfType(value) |
| | 14 | 869 | | ? value |
| | 14 | 870 | | : TryConvertHashtableValue(value, targetType, depth, out var convertedFromHashtable) |
| | 14 | 871 | | ? convertedFromHashtable |
| | 14 | 872 | | : TryConvertListOrArrayValue(value, targetType, depth, out var convertedFromEnumerable) |
| | 14 | 873 | | ? convertedFromEnumerable |
| | 14 | 874 | | : ConvertScalarValue(value, targetType); |
| | | 875 | | } |
| | | 876 | | |
| | | 877 | | /// <summary> |
| | | 878 | | /// Unwraps a nullable target type to its underlying non-nullable type. |
| | | 879 | | /// </summary> |
| | | 880 | | /// <param name="targetType">The target type.</param> |
| | | 881 | | /// <returns>The underlying non-nullable type, or the original type when not nullable.</returns> |
| | | 882 | | private static Type UnwrapNullableTargetType(Type targetType) |
| | 14 | 883 | | => Nullable.GetUnderlyingType(targetType) ?? targetType; |
| | | 884 | | |
| | | 885 | | /// <summary> |
| | | 886 | | /// Converts a hashtable value into the target type when applicable. |
| | | 887 | | /// </summary> |
| | | 888 | | /// <param name="value">Value to convert.</param> |
| | | 889 | | /// <param name="targetType">Target type.</param> |
| | | 890 | | /// <param name="depth">Current recursion depth.</param> |
| | | 891 | | /// <param name="converted">Converted result.</param> |
| | | 892 | | /// <returns><c>true</c> when the value was handled; otherwise <c>false</c>.</returns> |
| | | 893 | | private static bool TryConvertHashtableValue(object value, Type targetType, int depth, out object? converted) |
| | | 894 | | { |
| | 6 | 895 | | if (value is not Hashtable ht) |
| | | 896 | | { |
| | 6 | 897 | | converted = null; |
| | 6 | 898 | | return false; |
| | | 899 | | } |
| | | 900 | | |
| | 0 | 901 | | converted = typeof(IDictionary).IsAssignableFrom(targetType) |
| | 0 | 902 | | ? ht |
| | 0 | 903 | | : ConvertHashtableToObject(ht, targetType, depth); |
| | 0 | 904 | | return true; |
| | | 905 | | } |
| | | 906 | | |
| | | 907 | | /// <summary> |
| | | 908 | | /// Converts list/array values into the target type when applicable. |
| | | 909 | | /// </summary> |
| | | 910 | | /// <param name="value">Value to convert.</param> |
| | | 911 | | /// <param name="targetType">Target type.</param> |
| | | 912 | | /// <param name="depth">Current recursion depth.</param> |
| | | 913 | | /// <param name="converted">Converted result.</param> |
| | | 914 | | /// <returns><c>true</c> when the value was handled; otherwise <c>false</c>.</returns> |
| | | 915 | | private static bool TryConvertListOrArrayValue(object value, Type targetType, int depth, out object? converted) |
| | | 916 | | { |
| | 6 | 917 | | if (value is List<object?> list) |
| | | 918 | | { |
| | 2 | 919 | | converted = ConvertEnumerableToTargetType(list, targetType, depth); |
| | 2 | 920 | | return true; |
| | | 921 | | } |
| | | 922 | | |
| | 4 | 923 | | if (value is object?[] arr) |
| | | 924 | | { |
| | 0 | 925 | | converted = ConvertEnumerableToTargetType(arr, targetType, depth); |
| | 0 | 926 | | return true; |
| | | 927 | | } |
| | | 928 | | |
| | 4 | 929 | | converted = null; |
| | 4 | 930 | | return false; |
| | | 931 | | } |
| | | 932 | | |
| | | 933 | | /// <summary> |
| | | 934 | | /// Converts a scalar (non-hashtable, non-collection) value into the target type. |
| | | 935 | | /// </summary> |
| | | 936 | | /// <param name="value">Scalar value to convert.</param> |
| | | 937 | | /// <param name="targetType">Target type.</param> |
| | | 938 | | /// <returns>The converted value, or <c>null</c> when conversion fails.</returns> |
| | | 939 | | private static object? ConvertScalarValue(object value, Type targetType) |
| | | 940 | | { |
| | 4 | 941 | | var str = value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture); |
| | | 942 | | |
| | 4 | 943 | | return TryConvertScalarByType(str, targetType, out var converted) |
| | 4 | 944 | | ? converted |
| | 4 | 945 | | : TryChangeType(value, targetType); |
| | | 946 | | } |
| | | 947 | | |
| | | 948 | | /// <summary> |
| | | 949 | | /// Attempts to convert a scalar string representation to common primitive target types. |
| | | 950 | | /// </summary> |
| | | 951 | | /// <param name="str">String representation of the value.</param> |
| | | 952 | | /// <param name="targetType">Target type.</param> |
| | | 953 | | /// <param name="converted">Converted result.</param> |
| | | 954 | | /// <returns><c>true</c> when converted; otherwise <c>false</c>.</returns> |
| | | 955 | | private static bool TryConvertScalarByType(string? str, Type targetType, out object? converted) |
| | | 956 | | { |
| | 4 | 957 | | if (TryConvertPrimitiveScalar(str, targetType, out converted)) |
| | | 958 | | { |
| | 4 | 959 | | return true; |
| | | 960 | | } |
| | | 961 | | |
| | 0 | 962 | | if (targetType.IsEnum) |
| | | 963 | | { |
| | 0 | 964 | | converted = TryParseEnum(targetType, str); |
| | 0 | 965 | | return converted is not null; |
| | | 966 | | } |
| | | 967 | | |
| | 0 | 968 | | converted = null; |
| | 0 | 969 | | return false; |
| | | 970 | | } |
| | | 971 | | |
| | | 972 | | /// <summary> |
| | | 973 | | /// Attempts to convert a scalar string representation into a primitive CLR type. |
| | | 974 | | /// </summary> |
| | | 975 | | /// <param name="str">String representation of the value.</param> |
| | | 976 | | /// <param name="targetType">Target type.</param> |
| | | 977 | | /// <param name="converted">Converted result.</param> |
| | | 978 | | /// <returns><c>true</c> when converted; otherwise <c>false</c>.</returns> |
| | | 979 | | private static bool TryConvertPrimitiveScalar(string? str, Type targetType, out object? converted) |
| | | 980 | | { |
| | 4 | 981 | | switch (System.Type.GetTypeCode(targetType)) |
| | | 982 | | { |
| | | 983 | | case TypeCode.String: |
| | 0 | 984 | | converted = str; |
| | 0 | 985 | | return true; |
| | | 986 | | case TypeCode.Int32: |
| | 2 | 987 | | converted = TryParseInt32(str); |
| | 2 | 988 | | return converted is not null; |
| | | 989 | | case TypeCode.Int64: |
| | 0 | 990 | | converted = TryParseInt64(str); |
| | 0 | 991 | | return converted is not null; |
| | | 992 | | case TypeCode.Double: |
| | 0 | 993 | | converted = TryParseDouble(str); |
| | 0 | 994 | | return converted is not null; |
| | | 995 | | case TypeCode.Decimal: |
| | 2 | 996 | | converted = TryParseDecimal(str); |
| | 2 | 997 | | return converted is not null; |
| | | 998 | | case TypeCode.Boolean: |
| | 0 | 999 | | converted = TryParseBoolean(str); |
| | 0 | 1000 | | return converted is not null; |
| | | 1001 | | default: |
| | 0 | 1002 | | converted = null; |
| | 0 | 1003 | | return false; |
| | | 1004 | | } |
| | | 1005 | | } |
| | | 1006 | | |
| | | 1007 | | /// <summary> |
| | | 1008 | | /// Attempts to parse an <see cref="int"/> from a string. |
| | | 1009 | | /// </summary> |
| | | 1010 | | /// <param name="str">String representation.</param> |
| | | 1011 | | /// <returns>The parsed value, or <c>null</c> when parsing fails.</returns> |
| | | 1012 | | private static int? TryParseInt32(string? str) |
| | 2 | 1013 | | => int.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out var i) ? i : null; |
| | | 1014 | | |
| | | 1015 | | /// <summary> |
| | | 1016 | | /// Attempts to parse a <see cref="long"/> from a string. |
| | | 1017 | | /// </summary> |
| | | 1018 | | /// <param name="str">String representation.</param> |
| | | 1019 | | /// <returns>The parsed value, or <c>null</c> when parsing fails.</returns> |
| | | 1020 | | private static long? TryParseInt64(string? str) |
| | 0 | 1021 | | => long.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out var l) ? l : null; |
| | | 1022 | | |
| | | 1023 | | /// <summary> |
| | | 1024 | | /// Attempts to parse a <see cref="double"/> from a string. |
| | | 1025 | | /// </summary> |
| | | 1026 | | /// <param name="str">String representation.</param> |
| | | 1027 | | /// <returns>The parsed value, or <c>null</c> when parsing fails.</returns> |
| | | 1028 | | private static double? TryParseDouble(string? str) |
| | 0 | 1029 | | => double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : null; |
| | | 1030 | | |
| | | 1031 | | /// <summary> |
| | | 1032 | | /// Attempts to parse a <see cref="decimal"/> from a string. |
| | | 1033 | | /// </summary> |
| | | 1034 | | /// <param name="str">String representation.</param> |
| | | 1035 | | /// <returns>The parsed value, or <c>null</c> when parsing fails.</returns> |
| | | 1036 | | private static decimal? TryParseDecimal(string? str) |
| | 2 | 1037 | | => decimal.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var dec) ? dec : null; |
| | | 1038 | | |
| | | 1039 | | /// <summary> |
| | | 1040 | | /// Attempts to parse a <see cref="bool"/> from a string. |
| | | 1041 | | /// </summary> |
| | | 1042 | | /// <param name="str">String representation.</param> |
| | | 1043 | | /// <returns>The parsed value, or <c>null</c> when parsing fails.</returns> |
| | | 1044 | | private static bool? TryParseBoolean(string? str) |
| | 0 | 1045 | | => bool.TryParse(str, out var b) ? b : null; |
| | | 1046 | | |
| | | 1047 | | /// <summary> |
| | | 1048 | | /// Attempts to parse an enum value from a string. |
| | | 1049 | | /// </summary> |
| | | 1050 | | /// <param name="targetType">Enum type.</param> |
| | | 1051 | | /// <param name="str">String representation.</param> |
| | | 1052 | | /// <returns>The parsed enum value, or <c>null</c> when parsing fails.</returns> |
| | | 1053 | | private static object? TryParseEnum(Type targetType, string? str) |
| | | 1054 | | { |
| | 0 | 1055 | | if (str is null) |
| | | 1056 | | { |
| | 0 | 1057 | | return null; |
| | | 1058 | | } |
| | | 1059 | | |
| | | 1060 | | try |
| | | 1061 | | { |
| | 0 | 1062 | | return Enum.Parse(targetType, str, ignoreCase: true); |
| | | 1063 | | } |
| | 0 | 1064 | | catch |
| | | 1065 | | { |
| | 0 | 1066 | | return null; |
| | | 1067 | | } |
| | 0 | 1068 | | } |
| | | 1069 | | |
| | | 1070 | | /// <summary> |
| | | 1071 | | /// Attempts a generic scalar conversion via <see cref="Convert.ChangeType(object, Type, IFormatProvider)"/>. |
| | | 1072 | | /// </summary> |
| | | 1073 | | /// <param name="value">Source value.</param> |
| | | 1074 | | /// <param name="targetType">Target type.</param> |
| | | 1075 | | /// <returns>The converted value, or <c>null</c> when conversion fails.</returns> |
| | | 1076 | | private static object? TryChangeType(object value, Type targetType) |
| | | 1077 | | { |
| | | 1078 | | try |
| | | 1079 | | { |
| | 0 | 1080 | | return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); |
| | | 1081 | | } |
| | 0 | 1082 | | catch |
| | | 1083 | | { |
| | 0 | 1084 | | return null; |
| | | 1085 | | } |
| | 0 | 1086 | | } |
| | | 1087 | | |
| | | 1088 | | private static object? ConvertEnumerableToTargetType(IEnumerable enumerable, Type targetType, int depth) |
| | | 1089 | | { |
| | 2 | 1090 | | if (targetType.IsArray) |
| | | 1091 | | { |
| | 2 | 1092 | | var elementType = targetType.GetElementType() ?? typeof(object); |
| | 2 | 1093 | | var items = new List<object?>(); |
| | 16 | 1094 | | foreach (var item in enumerable) |
| | | 1095 | | { |
| | 6 | 1096 | | items.Add(ConvertToTargetType(item, elementType, depth + 1)); |
| | | 1097 | | } |
| | | 1098 | | |
| | 2 | 1099 | | var arr = Array.CreateInstance(elementType, items.Count); |
| | 16 | 1100 | | for (var i = 0; i < items.Count; i++) |
| | | 1101 | | { |
| | 6 | 1102 | | arr.SetValue(items[i], i); |
| | | 1103 | | } |
| | | 1104 | | |
| | 2 | 1105 | | return arr; |
| | | 1106 | | } |
| | | 1107 | | |
| | | 1108 | | // Default to List<T> for generic IEnumerable targets. |
| | 0 | 1109 | | if (targetType.IsGenericType) |
| | | 1110 | | { |
| | 0 | 1111 | | var genDef = targetType.GetGenericTypeDefinition(); |
| | 0 | 1112 | | if (genDef == typeof(List<>) || genDef == typeof(IList<>) || genDef == typeof(IEnumerable<>)) |
| | | 1113 | | { |
| | 0 | 1114 | | var elementType = targetType.GetGenericArguments()[0]; |
| | 0 | 1115 | | var listType = typeof(List<>).MakeGenericType(elementType); |
| | 0 | 1116 | | var list = (IList)Activator.CreateInstance(listType)!; |
| | 0 | 1117 | | foreach (var item in enumerable) |
| | | 1118 | | { |
| | 0 | 1119 | | _ = list.Add(ConvertToTargetType(item, elementType, depth + 1)); |
| | | 1120 | | } |
| | 0 | 1121 | | return list; |
| | | 1122 | | } |
| | | 1123 | | } |
| | | 1124 | | |
| | 0 | 1125 | | return null; |
| | | 1126 | | } |
| | | 1127 | | |
| | | 1128 | | private static bool TryGetHashtableValue(Hashtable table, string key, out object? value) |
| | | 1129 | | { |
| | 33 | 1130 | | foreach (DictionaryEntry entry in table) |
| | | 1131 | | { |
| | 13 | 1132 | | if (entry.Key is string s && string.Equals(s, key, StringComparison.OrdinalIgnoreCase)) |
| | | 1133 | | { |
| | 7 | 1134 | | value = entry.Value; |
| | 7 | 1135 | | return true; |
| | | 1136 | | } |
| | | 1137 | | } |
| | | 1138 | | |
| | 0 | 1139 | | value = null; |
| | 0 | 1140 | | return false; |
| | 7 | 1141 | | } |
| | | 1142 | | |
| | | 1143 | | /// <summary> |
| | | 1144 | | /// Converts a form dictionary to a hashtable. |
| | | 1145 | | /// </summary> |
| | | 1146 | | /// <param name="form">The form dictionary to convert.</param> |
| | | 1147 | | /// <returns>A hashtable representing the form data.</returns> |
| | | 1148 | | private static Hashtable? ConvertFormToHashtable(Dictionary<string, string>? form) |
| | | 1149 | | { |
| | 0 | 1150 | | if (form is null || form.Count == 0) |
| | | 1151 | | { |
| | 0 | 1152 | | return null; |
| | | 1153 | | } |
| | | 1154 | | |
| | 0 | 1155 | | var ht = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | | 1156 | | |
| | 0 | 1157 | | foreach (var kvp in form) |
| | | 1158 | | { |
| | | 1159 | | // x-www-form-urlencoded in your case has a single value per key |
| | 0 | 1160 | | ht[kvp.Key] = kvp.Value; |
| | | 1161 | | } |
| | | 1162 | | |
| | 0 | 1163 | | return ht; |
| | | 1164 | | } |
| | | 1165 | | |
| | | 1166 | | private static object? ConvertFormToValue(Dictionary<string, string>? form, ParameterForInjectionInfo param) |
| | | 1167 | | { |
| | 0 | 1168 | | if (form is null || form.Count == 0) |
| | | 1169 | | { |
| | 0 | 1170 | | return null; |
| | | 1171 | | } |
| | | 1172 | | |
| | | 1173 | | // If the parameter is a simple type, return the first key if there's only one key-value pair |
| | | 1174 | | // and it's a simple type (not an object or array) |
| | 0 | 1175 | | return param.Type is JsonSchemaType.Integer or JsonSchemaType.Number or JsonSchemaType.Boolean or JsonSchemaType |
| | 0 | 1176 | | ? form.Count == 1 ? form.First().Key : null |
| | 0 | 1177 | | : ConvertFormToHashtable(form); |
| | | 1178 | | } |
| | | 1179 | | |
| | | 1180 | | private static object? ConvertBsonToHashtable(string bson) |
| | | 1181 | | { |
| | 1 | 1182 | | if (string.IsNullOrWhiteSpace(bson)) |
| | | 1183 | | { |
| | 0 | 1184 | | return null; |
| | | 1185 | | } |
| | | 1186 | | |
| | 1 | 1187 | | var bytes = DecodeBodyStringToBytes(bson); |
| | 1 | 1188 | | if (bytes is null || bytes.Length == 0) |
| | | 1189 | | { |
| | 0 | 1190 | | return null; |
| | | 1191 | | } |
| | | 1192 | | |
| | 1 | 1193 | | var doc = BsonSerializer.Deserialize<BsonDocument>(bytes); |
| | 1 | 1194 | | return BsonValueToClr(doc); |
| | | 1195 | | } |
| | | 1196 | | |
| | | 1197 | | private static object? BsonValueToClr(BsonValue value) |
| | | 1198 | | { |
| | 3 | 1199 | | return value is null || value.IsBsonNull |
| | 3 | 1200 | | ? null |
| | 3 | 1201 | | : value.BsonType switch |
| | 3 | 1202 | | { |
| | 1 | 1203 | | BsonType.Document => BsonDocumentToHashtable(value.AsBsonDocument), |
| | 0 | 1204 | | BsonType.Array => BsonArrayToClrArray(value.AsBsonArray), |
| | 0 | 1205 | | BsonType.Boolean => value.AsBoolean, |
| | 1 | 1206 | | BsonType.Int32 => value.AsInt32, |
| | 0 | 1207 | | BsonType.Int64 => value.AsInt64, |
| | 0 | 1208 | | BsonType.Double => value.AsDouble, |
| | 0 | 1209 | | BsonType.Decimal128 => value.AsDecimal, |
| | 1 | 1210 | | BsonType.String => value.AsString, |
| | 0 | 1211 | | BsonType.DateTime => value.ToUniversalTime(), |
| | 0 | 1212 | | BsonType.ObjectId => value.AsObjectId.ToString(), |
| | 0 | 1213 | | BsonType.Binary => value.AsBsonBinaryData.Bytes, |
| | 0 | 1214 | | BsonType.Null => null, |
| | 0 | 1215 | | _ => value.ToString(), |
| | 3 | 1216 | | }; |
| | | 1217 | | } |
| | | 1218 | | |
| | | 1219 | | private static Hashtable BsonDocumentToHashtable(BsonDocument doc) |
| | | 1220 | | { |
| | 1 | 1221 | | var ht = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | 6 | 1222 | | foreach (var element in doc.Elements) |
| | | 1223 | | { |
| | 2 | 1224 | | ht[element.Name] = BsonValueToClr(element.Value); |
| | | 1225 | | } |
| | | 1226 | | |
| | 1 | 1227 | | return ht; |
| | | 1228 | | } |
| | | 1229 | | |
| | | 1230 | | private static object?[] BsonArrayToClrArray(BsonArray arr) |
| | | 1231 | | { |
| | 0 | 1232 | | var list = new object?[arr.Count]; |
| | 0 | 1233 | | for (var i = 0; i < arr.Count; i++) |
| | | 1234 | | { |
| | 0 | 1235 | | list[i] = BsonValueToClr(arr[i]); |
| | | 1236 | | } |
| | | 1237 | | |
| | 0 | 1238 | | return list; |
| | | 1239 | | } |
| | | 1240 | | |
| | | 1241 | | private static object? ConvertCborToHashtable(string cbor) |
| | | 1242 | | { |
| | 1 | 1243 | | if (string.IsNullOrWhiteSpace(cbor)) |
| | | 1244 | | { |
| | 0 | 1245 | | return null; |
| | | 1246 | | } |
| | | 1247 | | |
| | 1 | 1248 | | var bytes = DecodeBodyStringToBytes(cbor); |
| | 1 | 1249 | | if (bytes is null || bytes.Length == 0) |
| | | 1250 | | { |
| | 0 | 1251 | | return null; |
| | | 1252 | | } |
| | | 1253 | | |
| | 1 | 1254 | | var obj = CBORObject.DecodeFromBytes(bytes); |
| | 1 | 1255 | | return CborToClr(obj); |
| | | 1256 | | } |
| | | 1257 | | |
| | | 1258 | | /// <summary> |
| | | 1259 | | /// Converts a CBORObject to a CLR object (Hashtable, array, or scalar). |
| | | 1260 | | /// </summary> |
| | | 1261 | | /// <param name="obj">The CBORObject to convert.</param> |
| | | 1262 | | /// <returns>A CLR object representation of the CBORObject.</returns> |
| | | 1263 | | private static object? CborToClr(CBORObject obj) |
| | | 1264 | | { |
| | 3 | 1265 | | return obj is null || obj.IsNull |
| | 3 | 1266 | | ? null |
| | 3 | 1267 | | : obj.Type switch |
| | 3 | 1268 | | { |
| | 1 | 1269 | | CBORType.Map => ConvertCborMapToHashtable(obj), |
| | 0 | 1270 | | CBORType.Array => ConvertCborArrayToClrArray(obj), |
| | 2 | 1271 | | _ => ConvertCborScalarToClr(obj), |
| | 3 | 1272 | | }; |
| | | 1273 | | } |
| | | 1274 | | |
| | | 1275 | | /// <summary> |
| | | 1276 | | /// Converts a CBOR map into a CLR <see cref="Hashtable"/>. |
| | | 1277 | | /// </summary> |
| | | 1278 | | /// <param name="map">The CBOR object expected to be of type <see cref="CBORType.Map"/>.</param> |
| | | 1279 | | /// <returns>A case-insensitive hashtable representing the map.</returns> |
| | | 1280 | | private static Hashtable ConvertCborMapToHashtable(CBORObject map) |
| | | 1281 | | { |
| | 1 | 1282 | | var ht = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | 6 | 1283 | | foreach (var key in map.Keys) |
| | | 1284 | | { |
| | 2 | 1285 | | var keyString = GetCborMapKeyString(key); |
| | 2 | 1286 | | ht[keyString] = CborToClr(map[key]); |
| | | 1287 | | } |
| | | 1288 | | |
| | 1 | 1289 | | return ht; |
| | | 1290 | | } |
| | | 1291 | | |
| | | 1292 | | /// <summary> |
| | | 1293 | | /// Converts a CBOR array into a CLR object array. |
| | | 1294 | | /// </summary> |
| | | 1295 | | /// <param name="array">The CBOR object expected to be of type <see cref="CBORType.Array"/>.</param> |
| | | 1296 | | /// <returns>An array of converted elements.</returns> |
| | | 1297 | | private static object?[] ConvertCborArrayToClrArray(CBORObject array) |
| | | 1298 | | { |
| | 0 | 1299 | | var list = new object?[array.Count]; |
| | 0 | 1300 | | for (var i = 0; i < array.Count; i++) |
| | | 1301 | | { |
| | 0 | 1302 | | list[i] = CborToClr(array[i]); |
| | | 1303 | | } |
| | | 1304 | | |
| | 0 | 1305 | | return list; |
| | | 1306 | | } |
| | | 1307 | | |
| | | 1308 | | /// <summary> |
| | | 1309 | | /// Converts a CBOR scalar value (number, string, boolean, byte string, etc.) into a CLR value. |
| | | 1310 | | /// </summary> |
| | | 1311 | | /// <param name="scalar">The CBOR scalar to convert.</param> |
| | | 1312 | | /// <returns>The converted CLR value.</returns> |
| | | 1313 | | private static object? ConvertCborScalarToClr(CBORObject scalar) |
| | | 1314 | | { |
| | 2 | 1315 | | if (scalar.IsNumber) |
| | | 1316 | | { |
| | | 1317 | | // Prefer integral if representable; else double/decimal as available. |
| | 1 | 1318 | | var number = scalar.AsNumber(); |
| | 1 | 1319 | | if (number.CanFitInInt64()) |
| | | 1320 | | { |
| | 1 | 1321 | | return number.ToInt64Checked(); |
| | | 1322 | | } |
| | | 1323 | | |
| | 0 | 1324 | | if (number.CanFitInDouble()) |
| | | 1325 | | { |
| | 0 | 1326 | | return scalar.ToObject<double>(); |
| | | 1327 | | } |
| | | 1328 | | |
| | | 1329 | | // For extremely large/precise numbers, keep a string representation. |
| | 0 | 1330 | | return number.ToString(); |
| | | 1331 | | } |
| | | 1332 | | |
| | 1 | 1333 | | if (scalar.Type == CBORType.Boolean) |
| | | 1334 | | { |
| | 0 | 1335 | | return scalar.AsBoolean(); |
| | | 1336 | | } |
| | | 1337 | | |
| | 1 | 1338 | | if (scalar.Type == CBORType.ByteString) |
| | | 1339 | | { |
| | 0 | 1340 | | return scalar.GetByteString(); |
| | | 1341 | | } |
| | | 1342 | | |
| | | 1343 | | // TextString, SimpleValue, etc. |
| | 1 | 1344 | | return scalar.Type switch |
| | 1 | 1345 | | { |
| | 1 | 1346 | | CBORType.TextString => scalar.AsString(), |
| | 0 | 1347 | | CBORType.SimpleValue => scalar.ToString(), |
| | 0 | 1348 | | _ => scalar.ToString(), |
| | 1 | 1349 | | }; |
| | | 1350 | | } |
| | | 1351 | | |
| | | 1352 | | /// <summary> |
| | | 1353 | | /// Converts a CBOR map key into a CLR string key. |
| | | 1354 | | /// </summary> |
| | | 1355 | | /// <param name="key">The CBOR key object.</param> |
| | | 1356 | | /// <returns>A best-effort string representation of the key.</returns> |
| | | 1357 | | private static string GetCborMapKeyString(CBORObject? key) |
| | | 1358 | | { |
| | 2 | 1359 | | return key is not null && key.Type == CBORType.TextString |
| | 2 | 1360 | | ? key.AsString() |
| | 2 | 1361 | | : (key?.ToString() ?? string.Empty); |
| | | 1362 | | } |
| | | 1363 | | |
| | | 1364 | | /// <summary> |
| | | 1365 | | /// Converts a CSV string to a hashtable or array of hashtables. |
| | | 1366 | | /// </summary> |
| | | 1367 | | /// <param name="csv">The CSV string to convert.</param> |
| | | 1368 | | /// <returns>A hashtable if one record is present, an array of hashtables if multiple records are present, or null i |
| | | 1369 | | private static object? ConvertCsvToHashtable(string csv) |
| | | 1370 | | { |
| | 2 | 1371 | | if (string.IsNullOrWhiteSpace(csv)) |
| | | 1372 | | { |
| | 0 | 1373 | | return null; |
| | | 1374 | | } |
| | | 1375 | | |
| | 2 | 1376 | | using var reader = new StringReader(csv); |
| | 2 | 1377 | | var config = new CsvConfiguration(CultureInfo.InvariantCulture) |
| | 2 | 1378 | | { |
| | 2 | 1379 | | HasHeaderRecord = true, |
| | 2 | 1380 | | BadDataFound = null, |
| | 2 | 1381 | | MissingFieldFound = null, |
| | 2 | 1382 | | HeaderValidated = null, |
| | 2 | 1383 | | IgnoreBlankLines = true, |
| | 2 | 1384 | | TrimOptions = TrimOptions.Trim, |
| | 2 | 1385 | | }; |
| | | 1386 | | |
| | 2 | 1387 | | using var csvReader = new CsvReader(reader, config); |
| | 2 | 1388 | | var records = new List<Hashtable>(); |
| | | 1389 | | |
| | 10 | 1390 | | foreach (var rec in csvReader.GetRecords<dynamic>()) |
| | | 1391 | | { |
| | 3 | 1392 | | if (rec is not IDictionary<string, object?> dict) |
| | | 1393 | | { |
| | | 1394 | | continue; |
| | | 1395 | | } |
| | | 1396 | | |
| | 3 | 1397 | | var ht = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | 18 | 1398 | | foreach (var kvp in dict) |
| | | 1399 | | { |
| | 6 | 1400 | | ht[kvp.Key] = kvp.Value; |
| | | 1401 | | } |
| | | 1402 | | |
| | 3 | 1403 | | records.Add(ht); |
| | | 1404 | | } |
| | | 1405 | | |
| | 2 | 1406 | | return records.Count == 0 |
| | 2 | 1407 | | ? null |
| | 2 | 1408 | | : (records.Count == 1 ? records[0] : records.Cast<object?>().ToArray()); |
| | 2 | 1409 | | } |
| | | 1410 | | |
| | | 1411 | | private static byte[]? DecodeBodyStringToBytes(string body) |
| | | 1412 | | { |
| | 2 | 1413 | | if (string.IsNullOrWhiteSpace(body)) |
| | | 1414 | | { |
| | 0 | 1415 | | return null; |
| | | 1416 | | } |
| | | 1417 | | |
| | 2 | 1418 | | var trimmed = body.Trim(); |
| | 2 | 1419 | | if (trimmed.StartsWith("base64:", StringComparison.OrdinalIgnoreCase)) |
| | | 1420 | | { |
| | 2 | 1421 | | trimmed = trimmed["base64:".Length..].Trim(); |
| | | 1422 | | } |
| | | 1423 | | |
| | 2 | 1424 | | if (TryDecodeBase64(trimmed, out var base64Bytes)) |
| | | 1425 | | { |
| | 2 | 1426 | | return base64Bytes; |
| | | 1427 | | } |
| | | 1428 | | |
| | 0 | 1429 | | if (TryDecodeHex(trimmed, out var hexBytes)) |
| | | 1430 | | { |
| | 0 | 1431 | | return hexBytes; |
| | | 1432 | | } |
| | | 1433 | | |
| | | 1434 | | // Fallback: interpret as UTF-8 text (best-effort). |
| | 0 | 1435 | | return System.Text.Encoding.UTF8.GetBytes(trimmed); |
| | | 1436 | | } |
| | | 1437 | | |
| | | 1438 | | private static bool TryDecodeBase64(string input, out byte[] bytes) |
| | | 1439 | | { |
| | 2 | 1440 | | bytes = []; |
| | | 1441 | | |
| | | 1442 | | // Quick reject for non-base64 strings. |
| | 2 | 1443 | | if (input.Length < 4 || (input.Length % 4) != 0) |
| | | 1444 | | { |
| | 0 | 1445 | | return false; |
| | | 1446 | | } |
| | | 1447 | | |
| | | 1448 | | // Avoid throwing on clearly non-base64 content. |
| | 84 | 1449 | | for (var i = 0; i < input.Length; i++) |
| | | 1450 | | { |
| | 40 | 1451 | | var c = input[i]; |
| | 40 | 1452 | | var isValid = |
| | 40 | 1453 | | c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or '+' or '/' or '=' or '\r' or ' |
| | | 1454 | | |
| | 40 | 1455 | | if (!isValid) |
| | | 1456 | | { |
| | 0 | 1457 | | return false; |
| | | 1458 | | } |
| | | 1459 | | } |
| | | 1460 | | |
| | | 1461 | | try |
| | | 1462 | | { |
| | 2 | 1463 | | bytes = Convert.FromBase64String(input); |
| | 2 | 1464 | | return true; |
| | | 1465 | | } |
| | 0 | 1466 | | catch (FormatException) |
| | | 1467 | | { |
| | 0 | 1468 | | return false; |
| | | 1469 | | } |
| | 2 | 1470 | | } |
| | | 1471 | | |
| | | 1472 | | private static bool TryDecodeHex(string input, out byte[] bytes) |
| | | 1473 | | { |
| | 0 | 1474 | | bytes = []; |
| | 0 | 1475 | | var s = input.Trim(); |
| | | 1476 | | |
| | 0 | 1477 | | if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) |
| | | 1478 | | { |
| | 0 | 1479 | | s = s[2..]; |
| | | 1480 | | } |
| | | 1481 | | |
| | 0 | 1482 | | if (s.Length < 2 || (s.Length % 2) != 0) |
| | | 1483 | | { |
| | 0 | 1484 | | return false; |
| | | 1485 | | } |
| | | 1486 | | |
| | 0 | 1487 | | for (var i = 0; i < s.Length; i++) |
| | | 1488 | | { |
| | 0 | 1489 | | var c = s[i]; |
| | 0 | 1490 | | var isHex = c is (>= '0' and <= '9') or (>= 'a' and <= 'f') or (>= 'A' and <= 'F'); |
| | | 1491 | | |
| | 0 | 1492 | | if (!isHex) |
| | | 1493 | | { |
| | 0 | 1494 | | return false; |
| | | 1495 | | } |
| | | 1496 | | } |
| | | 1497 | | |
| | 0 | 1498 | | bytes = new byte[s.Length / 2]; |
| | 0 | 1499 | | for (var i = 0; i < bytes.Length; i++) |
| | | 1500 | | { |
| | 0 | 1501 | | bytes[i] = byte.Parse(s.AsSpan(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); |
| | | 1502 | | } |
| | | 1503 | | |
| | 0 | 1504 | | return true; |
| | | 1505 | | } |
| | | 1506 | | } |