如何为多个 BO 属性定义 IDataErrorInfo 错误属性

发布于 2024-08-18 16:17:40 字数 923 浏览 6 评论 0原文

我开始通过 IDataErrorInfo 接口在我的 WPF 项目中实现验证。 我的业务对象包含多个带有验证信息的属性。如何获取与该对象关联的所有错误消息的列表。我的想法是,这就是 Error 属性的用途,但我无法追踪任何使用它来报告多个属性的人。

谢谢!

public string this[string property]
    {
        get {

            string msg = null;
            switch (property)
            {
                case "LastName":
                    if (string.IsNullOrEmpty(LastName))
                        msg = "Need a last name";
                    break;
                case "FirstName":
                    if (string.IsNullOrEmpty(LastName))
                        msg = "Need a first name";
                    break;

                default:
                    throw new ArgumentException(
                        "Unrecognized property: " + property);
            }
            return msg;

        }
    }

    public string Error
    {
        get
        {
            return null ;
        }
    }

I'm starting to implement validation in my WPF project via the IDataErrorInfo interface.
My business object contains multiple properties with validation info. How do I get a list of ALL the error messages associated with the object. My thought is that thats what the Error property is for, but I cannot track down anyone using this for reporting on multiple properties.

Thanks!

public string this[string property]
    {
        get {

            string msg = null;
            switch (property)
            {
                case "LastName":
                    if (string.IsNullOrEmpty(LastName))
                        msg = "Need a last name";
                    break;
                case "FirstName":
                    if (string.IsNullOrEmpty(LastName))
                        msg = "Need a first name";
                    break;

                default:
                    throw new ArgumentException(
                        "Unrecognized property: " + property);
            }
            return msg;

        }
    }

    public string Error
    {
        get
        {
            return null ;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

憧憬巴黎街头的黎明 2024-08-25 16:17:40

我认为使用验证属性要容易得多。

class MyBusinessObject {
    [Required(ErrorMessage="Must enter customer")]
    public string Customer { get; set; }

    [Range(10,99, ErrorMessage="Price must be between 10 and 99")]
    public decimal Price { get; set; }

    // I have also created some custom attributes, e.g. validate paths
    [File(FileValidation.IsDirectory, ErrorMessage = "Must enter an importfolder")]
    public string ImportFolder { get; set; }

    public string this[string columnName] {
        return InputValidation<MyBusinessObject>.Validate(this, columnName);
    }

    public ICollection<string> AllErrors() {
        return InputValidation<MyBusinessObject>.Validate(this);
    }
}

辅助类 InputValidation 看起来像这样

internal static class InputValidation<T>
    where T : IDataErrorInfo
{
    /// <summary>
    /// Validate a single column in the source
    /// </summary>
    /// <remarks>
    /// Usually called from IErrorDataInfo.this[]</remarks>
    /// <param name="source">Instance to validate</param>
    /// <param name="columnName">Name of column to validate</param>
    /// <returns>Error messages separated by newline or string.Empty if no errors</returns>
    public static string Validate(T source, string columnName) {
       KeyValuePair<Func<T, object>, ValidationAttribute[]> validators;
       if (mAllValidators.TryGetValue(columnName, out validators)) {
           var value = validators.Key(source);
           var errors = validators.Value.Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage ?? "").ToArray();
           return string.Join(Environment.NewLine, errors);
       }
       return string.Empty;
    }

    /// <summary>
    /// Validate all columns in the source
    /// </summary>
    /// <param name="source">Instance to validate</param>
    /// <returns>List of all error messages. Empty list if no errors</returns>
    public static ICollection<string> Validate(T source) {
        List<string> messages = new List<string>();
        foreach (var validators in mAllValidators.Values) {
            var value = validators.Key(source);
            messages.AddRange(validators.Value.Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage ?? ""));
        }
        return messages;
    }

    /// <summary>
    /// Get all validation attributes on a property
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private static ValidationAttribute[] GetValidations(PropertyInfo property) {
        return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
    }

    /// <summary>
    /// Create a lambda to receive a property value
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private static Func<T, object> CreateValueGetter(PropertyInfo property) {
        var instance = Expression.Parameter(typeof(T), "i");
        var cast = Expression.TypeAs(Expression.Property(instance, property), typeof(object));
        return (Func<T, object>)Expression.Lambda(cast, instance).Compile();
    }

    private static readonly Dictionary<string, KeyValuePair<Func<T, object>, ValidationAttribute[]>>  mAllValidators;

    static InputValidation() {
        mAllValidators = new Dictionary<string, KeyValuePair<Func<T, object>, ValidationAttribute[]>>();
        foreach (var property in typeof(T).GetProperties()) {
            var validations = GetValidations(property);
            if (validations.Length > 0)
                mAllValidators.Add(property.Name,
                       new KeyValuePair<Func<T, object>, ValidationAttribute[]>(
                         CreateValueGetter(property), validations));
        }       
    }
}

I think it is much easier to use the Validation attributes.

class MyBusinessObject {
    [Required(ErrorMessage="Must enter customer")]
    public string Customer { get; set; }

    [Range(10,99, ErrorMessage="Price must be between 10 and 99")]
    public decimal Price { get; set; }

    // I have also created some custom attributes, e.g. validate paths
    [File(FileValidation.IsDirectory, ErrorMessage = "Must enter an importfolder")]
    public string ImportFolder { get; set; }

    public string this[string columnName] {
        return InputValidation<MyBusinessObject>.Validate(this, columnName);
    }

    public ICollection<string> AllErrors() {
        return InputValidation<MyBusinessObject>.Validate(this);
    }
}

The helper class InputValidation looks like this

internal static class InputValidation<T>
    where T : IDataErrorInfo
{
    /// <summary>
    /// Validate a single column in the source
    /// </summary>
    /// <remarks>
    /// Usually called from IErrorDataInfo.this[]</remarks>
    /// <param name="source">Instance to validate</param>
    /// <param name="columnName">Name of column to validate</param>
    /// <returns>Error messages separated by newline or string.Empty if no errors</returns>
    public static string Validate(T source, string columnName) {
       KeyValuePair<Func<T, object>, ValidationAttribute[]> validators;
       if (mAllValidators.TryGetValue(columnName, out validators)) {
           var value = validators.Key(source);
           var errors = validators.Value.Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage ?? "").ToArray();
           return string.Join(Environment.NewLine, errors);
       }
       return string.Empty;
    }

    /// <summary>
    /// Validate all columns in the source
    /// </summary>
    /// <param name="source">Instance to validate</param>
    /// <returns>List of all error messages. Empty list if no errors</returns>
    public static ICollection<string> Validate(T source) {
        List<string> messages = new List<string>();
        foreach (var validators in mAllValidators.Values) {
            var value = validators.Key(source);
            messages.AddRange(validators.Value.Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage ?? ""));
        }
        return messages;
    }

    /// <summary>
    /// Get all validation attributes on a property
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private static ValidationAttribute[] GetValidations(PropertyInfo property) {
        return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
    }

    /// <summary>
    /// Create a lambda to receive a property value
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    private static Func<T, object> CreateValueGetter(PropertyInfo property) {
        var instance = Expression.Parameter(typeof(T), "i");
        var cast = Expression.TypeAs(Expression.Property(instance, property), typeof(object));
        return (Func<T, object>)Expression.Lambda(cast, instance).Compile();
    }

    private static readonly Dictionary<string, KeyValuePair<Func<T, object>, ValidationAttribute[]>>  mAllValidators;

    static InputValidation() {
        mAllValidators = new Dictionary<string, KeyValuePair<Func<T, object>, ValidationAttribute[]>>();
        foreach (var property in typeof(T).GetProperties()) {
            var validations = GetValidations(property);
            if (validations.Length > 0)
                mAllValidators.Add(property.Name,
                       new KeyValuePair<Func<T, object>, ValidationAttribute[]>(
                         CreateValueGetter(property), validations));
        }       
    }
}
娇俏 2024-08-25 16:17:40

是的,我知道你可以在哪里使用索引器。我想这不是一个坏方法。不过,我真正关注的是“错误”属性。我喜欢将错误包含在业务对象中的概念。我认为我想要做的事情本身并不存在,所以我只是在对象上创建了一个错误字典(在属性更改时更新),并让错误返回回车分隔的错误列表,如下所示:

    public string this[string property]
    {
        get {

            string msg = null;
            switch (property)
            {
                case "LastName":
                    if (string.IsNullOrEmpty(LastName))
                       msg = "Need a last name";
                    break;
                case "FirstName":
                    if (string.IsNullOrEmpty(FirstName))
                        msg = "Need a first name";
                    break;
                default:
                    throw new ArgumentException(
                        "Unrecognized property: " + property);
            }

            if (msg != null && !errorCollection.ContainsKey(property))
                errorCollection.Add(property, msg);
            if (msg == null && errorCollection.ContainsKey(property))
                errorCollection.Remove(property);

            return msg;
        }
    }

    public string Error
    {
        get
        {
            if(errorCollection.Count == 0)
                return null;

            StringBuilder errorList = new StringBuilder();
            var errorMessages = errorCollection.Values.GetEnumerator();
            while (errorMessages.MoveNext())
                errorList.AppendLine(errorMessages.Current);

            return errorList.ToString();
        }
    }

Yeah, I see where you could use the indexer. Not a bad way to go I guess. I was really focused on the 'Error' property though. I like the notion of having the errors contained within the business object. I think what I want to do doesnt exist natively, so I just created a dictionary of errors (updated anytime a property changes) on the object and let the Error return a CarriageReturn delimited list of errors, like so :

    public string this[string property]
    {
        get {

            string msg = null;
            switch (property)
            {
                case "LastName":
                    if (string.IsNullOrEmpty(LastName))
                       msg = "Need a last name";
                    break;
                case "FirstName":
                    if (string.IsNullOrEmpty(FirstName))
                        msg = "Need a first name";
                    break;
                default:
                    throw new ArgumentException(
                        "Unrecognized property: " + property);
            }

            if (msg != null && !errorCollection.ContainsKey(property))
                errorCollection.Add(property, msg);
            if (msg == null && errorCollection.ContainsKey(property))
                errorCollection.Remove(property);

            return msg;
        }
    }

    public string Error
    {
        get
        {
            if(errorCollection.Count == 0)
                return null;

            StringBuilder errorList = new StringBuilder();
            var errorMessages = errorCollection.Values.GetEnumerator();
            while (errorMessages.MoveNext())
                errorList.AppendLine(errorMessages.Current);

            return errorList.ToString();
        }
    }
仙气飘飘 2024-08-25 16:17:40

我的理解是,要使用此接口,您需要枚举对象的属性,并为每个属性调用一次索引器。调用者有责任聚合所有错误消息。

My understanding is that to use this interface, you enumerate the properties on the object, and call the indexer once for each property. It is the caller's responsibility to aggregate any error messages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文