From 4e89aecbb14545d973987830858ded81b4f575e2 Mon Sep 17 00:00:00 2001 From: pbls31 Date: Fri, 13 Sep 2024 10:42:39 +0200 Subject: [PATCH] Applied changes from latest dev to avoid NullReferenceExceptions when accessing value of property --- .../ValueProvider/ValueProviderExecutor.cs | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/Moryx/Configuration/ValueProvider/ValueProviderExecutor.cs b/src/Moryx/Configuration/ValueProvider/ValueProviderExecutor.cs index 088e7dced..98ed1b509 100644 --- a/src/Moryx/Configuration/ValueProvider/ValueProviderExecutor.cs +++ b/src/Moryx/Configuration/ValueProvider/ValueProviderExecutor.cs @@ -36,6 +36,11 @@ public void FillEmpty(object obj) /// public static void Execute(object targetObject, ValueProviderExecutorSettings settings) { + if (targetObject is null) + { + throw new ArgumentNullException(nameof(targetObject)); + } + if (settings.Providers == null) { throw new ArgumentNullException(nameof(settings.Providers)); @@ -55,30 +60,34 @@ private static void Iterate(object target, ValueProviderExecutorSettings setting { foreach (var settingsProvider in settings.Providers) { - if (settingsProvider.Handle(target, property) == ValueProviderResult.Handled) + try { - break; + if (settingsProvider.Handle(target, property) == ValueProviderResult.Handled) + { + break; + } + } + catch (Exception) + { + // TODO: Restrict exception type + // TODO: Consider enabling logging } } var value = property.GetValue(target); - - if (property.PropertyType.IsValueType && !property.PropertyType.IsPrimitive || - property.PropertyType.IsClass && - property.PropertyType != typeof(string) && - !(value is IEnumerable)) + // Iterate each item of an enumerable + if (value is IEnumerable enumerable) { - Iterate(value, settings); - } - - if (value is IEnumerable) - { - var enumerable = value as IEnumerable; foreach (var item in enumerable) { - Iterate(item, settings); + if (item != null) + Iterate(item, settings); } } + else if (value != null && property.PropertyType.IsClass && property.PropertyType != typeof(string)) + { + Iterate(value, settings); + } } }