| | | 1 | | using System.Collections; |
| | | 2 | | using System.ComponentModel; |
| | | 3 | | using System.Diagnostics.CodeAnalysis; |
| | | 4 | | using System.Diagnostics.SymbolStore; |
| | | 5 | | using System.Dynamic; |
| | | 6 | | using System.Globalization; |
| | | 7 | | using System.Text.Encodings.Web; |
| | | 8 | | using System.Text.Json; |
| | | 9 | | using System.Text.Json.Nodes; |
| | | 10 | | using System.Text.Json.Serialization; |
| | | 11 | | using System.Text.Unicode; |
| | | 12 | | using Elsa.Expressions.Contracts; |
| | | 13 | | using Elsa.Expressions.Exceptions; |
| | | 14 | | using Elsa.Expressions.Extensions; |
| | | 15 | | using Elsa.Expressions.Models; |
| | | 16 | | using Elsa.Extensions; |
| | | 17 | | |
| | | 18 | | namespace Elsa.Expressions.Helpers; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Provides options to the conversion method. |
| | | 22 | | /// </summary> |
| | | 23 | | public record ObjectConverterOptions( |
| | | 24 | | JsonSerializerOptions? SerializerOptions = null, |
| | | 25 | | IWellKnownTypeRegistry? WellKnownTypeRegistry = null, |
| | | 26 | | bool DeserializeJsonObjectToObject = false, |
| | | 27 | | bool? StrictMode = null); |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// A helper that attempts many strategies to try and convert the source value into the destination type. |
| | | 31 | | /// </summary> |
| | | 32 | | public static class ObjectConverter |
| | | 33 | | { |
| | | 34 | | public static bool StrictMode = false; // Set to true to opt into strict mode. |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Attempts to convert the source value into the destination type. |
| | | 38 | | /// </summary> |
| | 16009 | 39 | | public static Result TryConvertTo<T>(this object? value, ObjectConverterOptions? converterOptions = null) => value.T |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Attempts to convert the source value into the destination type. |
| | | 43 | | /// </summary> |
| | | 44 | | [RequiresUnreferencedCode("The JsonSerializer type is not trim-compatible.")] |
| | | 45 | | public static Result TryConvertTo(this object? value, Type targetType, ObjectConverterOptions? converterOptions = nu |
| | | 46 | | { |
| | | 47 | | try |
| | | 48 | | { |
| | 16363 | 49 | | var convertedValue = value.ConvertTo(targetType, converterOptions); |
| | 16363 | 50 | | return new(true, convertedValue, null); |
| | | 51 | | } |
| | 0 | 52 | | catch (Exception e) |
| | | 53 | | { |
| | 0 | 54 | | return new(false, null, e); |
| | | 55 | | } |
| | 16363 | 56 | | } |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Attempts to convert the source value into the destination type. |
| | | 60 | | /// </summary> |
| | 1580 | 61 | | public static T? ConvertTo<T>(this object? value, ObjectConverterOptions? converterOptions = null) => value != null |
| | | 62 | | |
| | | 63 | | private static JsonSerializerOptions? _defaultSerializerOptions; |
| | | 64 | | private static JsonSerializerOptions? _internalSerializerOptions; |
| | | 65 | | |
| | 591 | 66 | | private static JsonSerializerOptions DefaultSerializerOptions => _defaultSerializerOptions ??= new() |
| | 591 | 67 | | { |
| | 591 | 68 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 591 | 69 | | PropertyNameCaseInsensitive = true, |
| | 591 | 70 | | ReferenceHandler = ReferenceHandler.Preserve, |
| | 591 | 71 | | Converters = |
| | 591 | 72 | | { |
| | 591 | 73 | | new JsonStringEnumConverter() |
| | 591 | 74 | | }, |
| | 591 | 75 | | Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) |
| | 591 | 76 | | }; |
| | | 77 | | |
| | 514 | 78 | | private static JsonSerializerOptions InternalSerializerOptions => _internalSerializerOptions ??= new() |
| | 514 | 79 | | { |
| | 514 | 80 | | Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) |
| | 514 | 81 | | }; |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Attempts to convert the source value into the destination type. |
| | | 85 | | /// </summary> |
| | | 86 | | [RequiresUnreferencedCode("The JsonSerializer type is not trim-compatible.")] |
| | | 87 | | public static object? ConvertTo(this object? value, Type targetType, ObjectConverterOptions? converterOptions = null |
| | | 88 | | { |
| | 19497 | 89 | | var strictMode = converterOptions?.StrictMode ?? StrictMode; |
| | | 90 | | |
| | 19497 | 91 | | if (value == null) |
| | 411 | 92 | | return null; |
| | | 93 | | |
| | 19086 | 94 | | var sourceType = value.GetType(); |
| | | 95 | | |
| | 19086 | 96 | | if (targetType.IsAssignableFrom(sourceType)) |
| | 18249 | 97 | | return value; |
| | | 98 | | |
| | 837 | 99 | | var serializerOptions = converterOptions?.SerializerOptions ?? DefaultSerializerOptions; |
| | 837 | 100 | | var underlyingTargetType = Nullable.GetUnderlyingType(targetType) ?? targetType; |
| | 837 | 101 | | var underlyingSourceType = Nullable.GetUnderlyingType(sourceType) ?? sourceType; |
| | | 102 | | |
| | 837 | 103 | | if (value is JsonElement { ValueKind: JsonValueKind.Number } jsonNumber && underlyingTargetType == typeof(string |
| | 0 | 104 | | return jsonNumber.ToString().ConvertTo(underlyingTargetType); |
| | | 105 | | |
| | 837 | 106 | | if (value is JsonElement jsonElement) |
| | | 107 | | { |
| | 34 | 108 | | if (jsonElement.ValueKind == JsonValueKind.String && underlyingTargetType != typeof(string)) |
| | 11 | 109 | | return jsonElement.GetString().ConvertTo(underlyingTargetType); |
| | | 110 | | |
| | 23 | 111 | | return jsonElement.Deserialize(targetType, serializerOptions); |
| | | 112 | | } |
| | | 113 | | |
| | 803 | 114 | | if (value is JsonNode jsonNode) |
| | | 115 | | { |
| | 24 | 116 | | if (jsonNode is not JsonArray jsonArray) |
| | | 117 | | { |
| | 18 | 118 | | var valueKind = jsonNode.GetValueKind(); |
| | 18 | 119 | | if (valueKind == JsonValueKind.Null) |
| | 0 | 120 | | return null; |
| | | 121 | | |
| | 18 | 122 | | if (valueKind == JsonValueKind.Undefined) |
| | 0 | 123 | | return null; |
| | | 124 | | |
| | 18 | 125 | | return underlyingTargetType switch |
| | 18 | 126 | | { |
| | 18 | 127 | | { } t when t == typeof(bool) && valueKind == JsonValueKind.False => false, |
| | 18 | 128 | | { } t when t == typeof(bool) && valueKind == JsonValueKind.True => true, |
| | 35 | 129 | | { } t when t.IsNumericType() && valueKind == JsonValueKind.Number => ConvertTo(jsonNode.ToString(), |
| | 2 | 130 | | { } t when t == typeof(string) && valueKind == JsonValueKind.String => jsonNode.ToString(), |
| | 0 | 131 | | { } t when t == typeof(string) => jsonNode.ToString(), |
| | 0 | 132 | | { } t when t == typeof(ExpandoObject) && jsonNode.GetValueKind() == JsonValueKind.Object => JsonSeri |
| | 0 | 133 | | { } t when t != typeof(object) || converterOptions?.DeserializeJsonObjectToObject == true => jsonNod |
| | 0 | 134 | | _ => jsonNode |
| | 18 | 135 | | }; |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | // Convert to target type if target type is an array or a generic collection. |
| | 6 | 139 | | if (targetType.IsArray || targetType.IsCollectionType()) |
| | | 140 | | { |
| | | 141 | | // The element type of the source array is JsonObject. If the element type of the target array is Object |
| | | 142 | | // Deserializing normally would return an array of JsonElement instead of JsonObject, but we want to kee |
| | 6 | 143 | | var targetElementType = targetType.IsArray ? targetType.GetElementType()! : targetType.GenericTypeArgume |
| | | 144 | | |
| | 6 | 145 | | if (targetElementType != typeof(object)) |
| | 6 | 146 | | return jsonArray.Deserialize(targetType, serializerOptions); |
| | | 147 | | } |
| | | 148 | | } |
| | | 149 | | |
| | 779 | 150 | | if (underlyingSourceType == typeof(string) && !underlyingTargetType.IsPrimitive && underlyingTargetType != typeo |
| | | 151 | | { |
| | 521 | 152 | | var stringValue = (string)value; |
| | | 153 | | |
| | 521 | 154 | | if (underlyingTargetType == typeof(byte[])) |
| | | 155 | | { |
| | | 156 | | // Byte arrays are serialized to base64, so in this case, we convert the string back to the requested ta |
| | 0 | 157 | | return Convert.FromBase64String(stringValue); |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | try |
| | | 161 | | { |
| | 521 | 162 | | var firstChar = stringValue.TrimStart().FirstOrDefault(); |
| | | 163 | | |
| | 521 | 164 | | if (firstChar is '{' or '[') |
| | 265 | 165 | | return JsonSerializer.Deserialize(stringValue, underlyingTargetType, serializerOptions); |
| | 256 | 166 | | } |
| | 0 | 167 | | catch (Exception e) |
| | | 168 | | { |
| | 0 | 169 | | throw new TypeConversionException($"Failed to deserialize {stringValue} to {underlyingTargetType}", valu |
| | | 170 | | } |
| | | 171 | | } |
| | | 172 | | |
| | 514 | 173 | | if (targetType == typeof(object)) |
| | 0 | 174 | | return value; |
| | | 175 | | |
| | 514 | 176 | | if (underlyingTargetType.IsInstanceOfType(value)) |
| | 0 | 177 | | return value; |
| | | 178 | | |
| | 514 | 179 | | if (underlyingSourceType == underlyingTargetType) |
| | 0 | 180 | | return value; |
| | | 181 | | |
| | 514 | 182 | | if (IsDateType(underlyingSourceType) && IsDateType(underlyingTargetType)) |
| | 0 | 183 | | return ConvertAnyDateType(value, underlyingTargetType); |
| | | 184 | | |
| | 514 | 185 | | var internalSerializerOptions = InternalSerializerOptions; |
| | | 186 | | |
| | 514 | 187 | | if (typeof(IDictionary<string, object>).IsAssignableFrom(underlyingSourceType) && (underlyingTargetType.IsClass |
| | | 188 | | { |
| | 16 | 189 | | if (typeof(ExpandoObject) == underlyingTargetType) |
| | | 190 | | { |
| | 0 | 191 | | var expandoJson = JsonSerializer.Serialize(value, internalSerializerOptions); |
| | 0 | 192 | | return ConvertTo(expandoJson, underlyingTargetType, converterOptions); |
| | | 193 | | } |
| | | 194 | | |
| | 16 | 195 | | if (typeof(IDictionary<string, object>).IsAssignableFrom(underlyingTargetType)) |
| | 16 | 196 | | return new Dictionary<string, object>((IDictionary<string, object>)value); |
| | | 197 | | |
| | 0 | 198 | | var sourceDictionary = (IDictionary<string, object>)value; |
| | 0 | 199 | | var json = JsonSerializer.Serialize(sourceDictionary, internalSerializerOptions); |
| | 0 | 200 | | return ConvertTo(json, underlyingTargetType, converterOptions); |
| | | 201 | | } |
| | | 202 | | |
| | 498 | 203 | | if (typeof(IEnumerable<object>).IsAssignableFrom(underlyingSourceType)) |
| | 0 | 204 | | if (underlyingTargetType == typeof(string)) |
| | 0 | 205 | | return JsonSerializer.Serialize(value, internalSerializerOptions); |
| | | 206 | | |
| | 498 | 207 | | var targetTypeConverter = TypeDescriptor.GetConverter(underlyingTargetType); |
| | | 208 | | |
| | 498 | 209 | | if (targetTypeConverter.CanConvertFrom(underlyingSourceType)) |
| | | 210 | | { |
| | 439 | 211 | | var isValid = targetTypeConverter.IsValid(value); |
| | | 212 | | |
| | 439 | 213 | | if (isValid) |
| | 439 | 214 | | return targetTypeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, value); |
| | | 215 | | } |
| | | 216 | | |
| | 59 | 217 | | var sourceTypeConverter = TypeDescriptor.GetConverter(underlyingSourceType); |
| | | 218 | | |
| | 59 | 219 | | if (sourceTypeConverter.CanConvertTo(underlyingTargetType)) |
| | | 220 | | { |
| | | 221 | | // TypeConverter.IsValid is not supported for ConvertTo, so we have to try and ignore any exceptions. |
| | | 222 | | try |
| | | 223 | | { |
| | 59 | 224 | | return sourceTypeConverter.ConvertTo(value, underlyingTargetType); |
| | | 225 | | } |
| | 0 | 226 | | catch |
| | | 227 | | { |
| | | 228 | | // Ignore and try other conversion strategies. |
| | 0 | 229 | | } |
| | | 230 | | } |
| | | 231 | | |
| | 0 | 232 | | if (underlyingTargetType.IsEnum) |
| | | 233 | | { |
| | 0 | 234 | | if (underlyingSourceType == typeof(string)) |
| | 0 | 235 | | return Enum.Parse(underlyingTargetType, (string)value); |
| | | 236 | | |
| | 0 | 237 | | if (underlyingSourceType == typeof(int)) |
| | 0 | 238 | | return Enum.ToObject(underlyingTargetType, value); |
| | | 239 | | |
| | 0 | 240 | | if (underlyingSourceType == typeof(double)) |
| | 0 | 241 | | return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int), CultureInfo.InvariantC |
| | | 242 | | |
| | 0 | 243 | | if (underlyingSourceType == typeof(long)) |
| | 0 | 244 | | return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int), CultureInfo.InvariantC |
| | | 245 | | } |
| | | 246 | | |
| | 0 | 247 | | if (value is string s) |
| | | 248 | | { |
| | 0 | 249 | | if (string.IsNullOrWhiteSpace(s)) |
| | 0 | 250 | | return null; |
| | | 251 | | |
| | 0 | 252 | | if (underlyingTargetType == typeof(Type)) |
| | 0 | 253 | | return converterOptions?.WellKnownTypeRegistry != null ? converterOptions.WellKnownTypeRegistry.GetTypeO |
| | | 254 | | |
| | | 255 | | // At this point, if the input is a string and the target type is IEnumerable<string>, assume the string is |
| | 0 | 256 | | if (typeof(IEnumerable<string>).IsAssignableFrom(underlyingTargetType)) |
| | 0 | 257 | | return new[] |
| | 0 | 258 | | { |
| | 0 | 259 | | s |
| | 0 | 260 | | }; |
| | | 261 | | } |
| | | 262 | | |
| | 0 | 263 | | if (value is IEnumerable enumerable) |
| | | 264 | | { |
| | 0 | 265 | | if (underlyingTargetType is { IsGenericType: true }) |
| | | 266 | | { |
| | 0 | 267 | | var desiredCollectionItemType = targetType.GenericTypeArguments[0]; |
| | 0 | 268 | | var desiredCollectionType = typeof(ICollection<>).MakeGenericType(desiredCollectionItemType); |
| | | 269 | | |
| | 0 | 270 | | if (underlyingTargetType.IsAssignableFrom(desiredCollectionType) || desiredCollectionType.IsAssignableFr |
| | | 271 | | { |
| | 0 | 272 | | var collectionType = typeof(List<>).MakeGenericType(desiredCollectionItemType); |
| | 0 | 273 | | var collection = (IList)Activator.CreateInstance(collectionType)!; |
| | | 274 | | |
| | 0 | 275 | | foreach (var item in enumerable) |
| | | 276 | | { |
| | 0 | 277 | | var convertedItem = ConvertTo(item, desiredCollectionItemType); |
| | 0 | 278 | | collection.Add(convertedItem); |
| | | 279 | | } |
| | | 280 | | |
| | 0 | 281 | | return collection; |
| | | 282 | | } |
| | | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | if (underlyingTargetType.IsArray) |
| | | 286 | | { |
| | 0 | 287 | | var executedEnumerable = enumerable.Cast<object>().ToList(); |
| | 0 | 288 | | var underlyingTargetElementType = underlyingTargetType.GetElementType()!; |
| | 0 | 289 | | var array = Array.CreateInstance(underlyingTargetElementType, executedEnumerable.Count); |
| | 0 | 290 | | var index = 0; |
| | 0 | 291 | | foreach (var item in executedEnumerable) |
| | | 292 | | { |
| | 0 | 293 | | var convertedItem = ConvertTo(item, underlyingTargetElementType); |
| | 0 | 294 | | array.SetValue(convertedItem, index); |
| | 0 | 295 | | index++; |
| | | 296 | | } |
| | | 297 | | |
| | 0 | 298 | | return array; |
| | | 299 | | } |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | try |
| | | 303 | | { |
| | 0 | 304 | | return Convert.ChangeType(value, underlyingTargetType, CultureInfo.InvariantCulture); |
| | | 305 | | } |
| | | 306 | | catch (FormatException e) |
| | | 307 | | { |
| | 0 | 308 | | return ReturnOrThrow(e); |
| | | 309 | | } |
| | | 310 | | catch (InvalidCastException e) |
| | | 311 | | { |
| | 0 | 312 | | return ReturnOrThrow(e); |
| | | 313 | | } |
| | | 314 | | |
| | | 315 | | object? ReturnOrThrow(Exception e) |
| | | 316 | | { |
| | 0 | 317 | | if (!strictMode) |
| | 0 | 318 | | return targetType.GetDefaultValue(); // Backward compatibility: return default value if strict mode is o |
| | | 319 | | |
| | 0 | 320 | | throw new TypeConversionException($"Failed to convert an object of type {sourceType} to {underlyingTargetTyp |
| | | 321 | | } |
| | 324 | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary> |
| | | 325 | | /// Returns true if the specified type is a date-like type, false otherwise. |
| | | 326 | | /// </summary> |
| | | 327 | | private static bool IsDateType(Type type) |
| | | 328 | | { |
| | 514 | 329 | | var dateTypes = new[] |
| | 514 | 330 | | { |
| | 514 | 331 | | typeof(DateTime), typeof(DateTimeOffset), typeof(DateOnly) |
| | 514 | 332 | | }; |
| | | 333 | | |
| | 514 | 334 | | return dateTypes.Contains(type); |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | /// <summary> |
| | | 338 | | /// Converts any date type to the specified target type. |
| | | 339 | | /// </summary> |
| | | 340 | | /// <param name="value">Any of <see cref="DateTime"/>, <see cref="DateTimeOffset"/> or <see cref="DateOnly"/>.</para |
| | | 341 | | /// <param name="targetType">Any of <see cref="DateTime"/>, <see cref="DateTimeOffset"/> or <see cref="DateOnly"/>.< |
| | | 342 | | /// <returns>The converted value.</returns> |
| | | 343 | | /// <exception cref="ArgumentException">Thrown if <paramref name="value"/> is not of type <see cref="DateTime"/>, <s |
| | | 344 | | private static object ConvertAnyDateType(object value, Type targetType) |
| | | 345 | | { |
| | 0 | 346 | | return targetType switch |
| | 0 | 347 | | { |
| | 0 | 348 | | { } t when t == typeof(DateTime) => value switch |
| | 0 | 349 | | { |
| | 0 | 350 | | DateTime dateTime => dateTime, |
| | 0 | 351 | | DateTimeOffset dateTimeOffset => dateTimeOffset.DateTime, |
| | 0 | 352 | | DateOnly date => new(date.Year, date.Month, date.Day), |
| | 0 | 353 | | _ => throw new ArgumentException("Invalid value type.") |
| | 0 | 354 | | }, |
| | 0 | 355 | | { } t when t == typeof(DateTimeOffset) => value switch |
| | 0 | 356 | | { |
| | 0 | 357 | | DateTime dateTime => new(dateTime), |
| | 0 | 358 | | DateTimeOffset dateTimeOffset => dateTimeOffset, |
| | 0 | 359 | | DateOnly date => new(date.Year, date.Month, date.Day, 0, 0, 0, TimeSpan.Zero), |
| | 0 | 360 | | _ => throw new ArgumentException("Invalid value type.") |
| | 0 | 361 | | }, |
| | 0 | 362 | | { } t when t == typeof(DateOnly) => value switch |
| | 0 | 363 | | { |
| | 0 | 364 | | DateTime dateTime => new(dateTime.Year, dateTime.Month, dateTime.Day), |
| | 0 | 365 | | DateTimeOffset dateTimeOffset => new(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day), |
| | 0 | 366 | | DateOnly date => date, |
| | 0 | 367 | | _ => throw new ArgumentException("Invalid value type.") |
| | 0 | 368 | | }, |
| | 0 | 369 | | _ => throw new ArgumentException("Invalid target type.") |
| | 0 | 370 | | }; |
| | | 371 | | } |
| | | 372 | | } |