From 88955fb1e597b08d802710063cd40da987c44d78 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Oct 2024 20:18:34 -0500 Subject: update ValidationAttribute to work with arrays --- src/slskd/Common/Validation/ValidateAttribute.cs | 36 +++++++++++++++++++----- 1 file changed, 29 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index c7efaa92..540e61bc 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,6 +17,7 @@ namespace slskd.Validation { + using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -34,22 +35,43 @@ namespace slskd.Validation return ValidationResult.Success; } + // note: here's a great place to log the type and value if there are issues: + // Console.WriteLine($"{value.GetType()}: {value.ToJson()}"); var results = new List(); var context = new ValidationContext(value, null, null); - if (value.IsDictionary()) + // we should only be using dictionaries and arrays (e.g. []), not IEnumerable, because the YAML library + // somehow has nondeterministic behavior, sometimes turning YAML arrays into arrays, and sometimes List + // this could be handled by checking for List but let's just keep it simple and remember to use arrays + if (value.IsDictionary() || value is Array) { var compositeResults = new CompositeValidationResult(validationContext.DisplayName); - // given the context in this application, key type should never be anything but a string - foreach (string key in ((IDictionary)value).Keys) + if (value.IsDictionary()) { - var val = ((IDictionary)value)[key]; - var result = IsValid(val, new ValidationContext(val, null, null)); + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); - if (result != ValidationResult.Success) + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + } + else if (value is Array array) + { + for (int i = 0; i < array.Length; i++) { - compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + var val = array.GetValue(i); + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(i.ToString(), new[] { result }.ToList())); + } } } -- cgit v1.2.3