Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some enhancements and additions to DataAnnotations, incluiding implementation of a few missing pieces of Sys.ComponentModel.DataAnnotations v4.5, like: #740

Merged
merged 3 commits into from Aug 26, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,118 @@
//
// CompareAttribute.cs
//
// Authors:
// Pablo Ruiz García <pablo.ruiz@gmail.com>
//
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2013 Pablo Ruiz García
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if NET_4_5

using System;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;

namespace System.ComponentModel.DataAnnotations
{
[AttributeUsageAttribute (AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class CompareAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "'{0}' and '{1}' do not match.";
private const string NonExistingPropertyErrorMessage = "Could not find a property named {0}.";
private string _otherProperty;
private string _otherPropertyDisplayName;

public CompareAttribute (string otherProperty)
: base (() => DefaultErrorMessage)
{
if (string.IsNullOrEmpty (otherProperty))
throw new ArgumentNullException ("otherProperty");

_otherProperty = otherProperty;
}

public string OtherProperty { get { return _otherProperty; } }
public string OtherPropertyDisplayName { get { return _otherPropertyDisplayName; } }
public override bool RequiresValidationContext { get { return true; } }

private IEnumerable<Attribute> GetPropertyAttributes (Type type, string propertyName)
{
#if MOBILE
return TypeDescriptor.GetProperties (type).Find (propertyName, false).Attributes.OfType<Attribute> ();
#else
// Using AMTTDP seems the way to go to be able to relay on attributes declared
// by means of associated classes not directly decorating the property.
// See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.associatedmetadatatypetypedescriptionprovider.aspx
return new AssociatedMetadataTypeTypeDescriptionProvider (type)
.GetTypeDescriptor (type)
.GetProperties ()
.Find (propertyName, false)
.Attributes.OfType<Attribute> ();
#endif
}

private void ResolveOtherPropertyDisplayName (ValidationContext context)
{
if (_otherPropertyDisplayName == null)
{
// NOTE: From my own tests, it seems MS.NET looksup displayName from various sources, what follows
// is a best guess from my on tests, however, I am probably missing some corner cases. (pruiz)
var attributes = GetPropertyAttributes (context.ObjectType, _otherProperty);
var displayAttr = attributes.FirstOrDefault (x => x is DisplayAttribute) as DisplayAttribute;
var displayNameAttr = attributes.FirstOrDefault (x => x is DisplayNameAttribute) as DisplayNameAttribute;

if (displayAttr != null) _otherPropertyDisplayName = displayAttr.GetName ();
else if (displayNameAttr != null) _otherPropertyDisplayName = displayNameAttr.DisplayName;
_otherPropertyDisplayName = _otherProperty;
}
}

public override string FormatErrorMessage (string name)
{
var oname = string.IsNullOrEmpty (_otherPropertyDisplayName) ? _otherProperty : _otherPropertyDisplayName;
return string.Format (ErrorMessageString, name, oname);
}

protected override ValidationResult IsValid(object value, ValidationContext context)
{
var property = context.ObjectType.GetProperty (_otherProperty);

if (property == null) {
string message = string.Format (NonExistingPropertyErrorMessage, _otherProperty);
return new ValidationResult (message);
}

// XXX: Could not find a better place to call this, as this is
// the only place we have access to a ValidationContext. (pruiz)
ResolveOtherPropertyDisplayName (context);

return object.Equals (property.GetValue (context.ObjectInstance, null), value) ? null
: new ValidationResult (FormatErrorMessage (context.DisplayName));
}
}
}

#endif
@@ -0,0 +1,81 @@
//
// CreditCardAttribute.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
// Pablo Ruiz García <pablo.ruiz@gmail.com>
//
// Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2013 Pablo Ruiz García
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if NET_4_5

using System;
using System.Linq;
using System.Globalization;

namespace System.ComponentModel.DataAnnotations
{
[AttributeUsageAttribute (AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class CreditCardAttribute : DataTypeAttribute
{
private const string DefaultErrorMessage = "The {0} field is not a valid credit card number.";

public CreditCardAttribute ()
: base(DataType.CreditCard)
{
// XXX: There is no .ctor accepting Func<string> on DataTypeAttribute.. :?
base.ErrorMessage = DefaultErrorMessage;
}

public override bool IsValid(object value)
{
if (value == null)
return true;

if (string.IsNullOrEmpty(value as string))
return false;

// Remove any invalid characters..
var creditCardNumber = (value as string).Replace("-", "").Replace(" ", "");

if (creditCardNumber.Any (x => !Char.IsDigit (x)))
return false;

// Performan a Luhn-based check against credit card number.
//
// See: http://en.wikipedia.org/wiki/Luhn_algorithm
// See: http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
// See: http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-10-algorithm

int sumOfDigits = creditCardNumber.Where((e) => e >= '0' && e <= '9')
.Reverse()
.Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
.Sum((e) => e / 10 + e % 10);

return sumOfDigits % 10 == 0;
}
}
}

#endif
Expand Up @@ -46,7 +46,12 @@ public enum DataType
Password,
Url,
#if NET_4_0
ImageUrl
ImageUrl,
#endif
#if NET_4_5
CreditCard,
PostalCode,
Upload
#endif
}
}
Expand Up @@ -3,10 +3,10 @@
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
// Pablo Ruiz García <pablo.ruiz@gmail.com>
//
// Copyright (C) 2008 Novell Inc. http://novell.com
//

// Copyright (C) 2013 Pablo Ruiz García
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
Expand Down Expand Up @@ -50,6 +50,27 @@ public DataTypeAttribute (DataType dataType)
displayFormat.ApplyFormatInEditMode = true;
displayFormat.ConvertEmptyStringToNull = true;
displayFormat.DataFormatString = "{0:t}";
#if NET_4_0
displayFormat.HtmlEncode = true;
#endif
break;
case DataType.Date:
displayFormat = new DisplayFormatAttribute ();
displayFormat.ApplyFormatInEditMode = true;
displayFormat.ConvertEmptyStringToNull = true;
displayFormat.DataFormatString = "{0:d}";
#if NET_4_0
displayFormat.HtmlEncode = true;
#endif
break;
case DataType.Currency:
displayFormat = new DisplayFormatAttribute ();
displayFormat.ApplyFormatInEditMode = false;
displayFormat.ConvertEmptyStringToNull = true;
displayFormat.DataFormatString = "{0:C}";
#if NET_4_0
displayFormat.HtmlEncode = true;
#endif
break;

default:
Expand Down
@@ -0,0 +1,73 @@
//
// EmailAddressAttribute.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
// Pablo Ruiz García <pablo.ruiz@gmail.com>
//
// Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
// Copyright (C) 2013 Pablo Ruiz García
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if NET_4_5

using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace System.ComponentModel.DataAnnotations
{
[AttributeUsageAttribute (AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EmailAddressAttribute : DataTypeAttribute
{
private const string DefaultErrorMessage = "The {0} field is not a valid e-mail address.";
// See: http://stackoverflow.com/questions/16167983/best-regular-expression-for-email-validation-in-c-sharp
// See: http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
private const string _emailRegexStr = @"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
@"@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-z0-9])?\.)+(?:[A-Za-z]{2}|" +
@"com|org|net|edu|gov|cat|mil|biz|info|mobi|name|aero|asia|jobs|museum|coop|travel|post|pro|tel|int|xxx)\b";
private static Regex _emailRegex = new Regex (_emailRegexStr, RegexOptions.IgnoreCase | RegexOptions.Compiled);

public EmailAddressAttribute ()
: base(DataType.EmailAddress)
{
// XXX: There is no .ctor accepting Func<string> on DataTypeAttribute.. :?
base.ErrorMessage = DefaultErrorMessage;
}

public override bool IsValid(object value)
{
if (value == null)
return true;

if (value is string)
{
var str = value as string;
return !string.IsNullOrEmpty(str) ? _emailRegex.IsMatch(str) : false;
}

return false;
}
}
}

#endif