ComponentModel.DataAnnotations uses attributes to mark properties with validation behavior. For example, if I have the following program:
using System.ComponentModel.DataAnnotations;
class Program
{
static void Main(string[] args)
{
var poco = new Poco()
{
Name = "User",
Email = "blah",
};
List<ValidationResult> results = new List<ValidationResult>();
Validator.TryValidateObject(poco, new ValidationContext(poco), results, validateAllProperties: true);
Console.WriteLine(results.Count);
}
}
public class Poco
{
[Display]
public string Name { get; set; }
[EmailAddress(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.BadEmail))]
public string Email { get; set; }
}
It will print out that there is a validation error because blah is not a valid email address.
However, when I link this application with --used-attrs-only true, the EmailAddress attribute is getting stripped from the program. This is because the way Validator.TryValidateObject tries getting the attributes is not recognized by the linker.
First, it calls CustomAttributeExtensions.GetCustomAttributes on each property on the object. Then it passes those attributes to a method that filters them to just the attributes.OfType<ValidationAttribute>().
Possible ways to support this pattern that I can think of:
- By seeing that
ValidationAttribute is not sealed, and keeping any attribute that is derived from it since we are looking at attributes.OfType<ValidationAttribute>().
- By adding a mechanism inside of
Validator.TryValidateObject that says "when an app calls this method, preserve any attributes derived from ValidationAttribute".
- Note: this isn't as simple as
PreserveDependency, because a 3rd party can write a ValidationAttribute, and Validator won't be able to know about it.
cc @vitek-karas
ComponentModel.DataAnnotationsuses attributes to mark properties with validation behavior. For example, if I have the following program:It will print out that there is a validation error because
blahis not a valid email address.However, when I link this application with
--used-attrs-only true, theEmailAddressattribute is getting stripped from the program. This is because the wayValidator.TryValidateObjecttries getting the attributes is not recognized by the linker.First, it calls CustomAttributeExtensions.GetCustomAttributes on each property on the object. Then it passes those attributes to a method that filters them to just the
attributes.OfType<ValidationAttribute>().Possible ways to support this pattern that I can think of:
ValidationAttributeis not sealed, and keeping any attribute that is derived from it since we are looking atattributes.OfType<ValidationAttribute>().Validator.TryValidateObjectthat says "when an app calls this method, preserve any attributes derived fromValidationAttribute".PreserveDependency, because a 3rd party can write aValidationAttribute, andValidatorwon't be able to know about it.cc @vitek-karas