/// <summary> /// Saves the specified entity record. /// </summary> /// <returns>A task representing an asynchronous LoadAll operation.</returns> /// <param name="entries">The source entity.</param> /// <param name="operation">The source bulk save operation.</param> public virtual async Task <IEnumerable <T> > SaveManyAsync(IEnumerable <T> entries, BulkSaveOperation operation) { if (entries == null) { throw new ArgumentNullException(nameof(entries)); } List <T> updates = new List <T>(); List <T> creates = new List <T>(); foreach (T entry in entries) { if (entry is IValidateable) { IValidateable validateable = entry as IValidateable; if (!validateable.IsValid()) { throw new RecordValidationException(RecordValidationException.DefaultMessage); } } } return((operation == BulkSaveOperation.Create) ? await _repository.InsertAsync(entries) : await _repository.UpdateAsync(entries)); }
public static IEnumerable <string> Validate(this IValidateable obj) { List <string> errors = new List <string>(); IEnumerable <PropertyInfo> properties = obj.GetType().GetProperties(); foreach (PropertyInfo property in properties) { DisplayAttribute nameAttribute = property.GetCustomAttribute <DisplayAttribute>(); string propName = (nameAttribute == null) ? property.Name : nameAttribute.Name; object value = property.GetValue(obj); IEnumerable <ValidationAttribute> attributes = property.GetCustomAttributes <ValidationAttribute>(true); foreach (ValidationAttribute attribute in attributes) { if (!attribute.IsValid(value)) { errors.Add(attribute.FormatErrorMessage(propName)); } } } return(errors); }
public static void CallPreValidationRoutine(IValidateable entity, MethodInfo method, Actions action) { if (method.ReturnType != typeof(void)) { throw new InvalidOperationException("Custom Validation Method must not return a type, the return type must be [void]"); } var parameters = method.GetParameters(); if (parameters.Count() > 1) { throw new InvalidOperationException("Custom Validation Method most not accept more than one parameters, it may optionally [Actions action]."); } if (parameters.Count() == 1 && parameters[0].ParameterType != typeof(Actions)) { throw new InvalidOperationException("Custom Validation Method must optionally accept only a first parameter of [Actions action]."); } if (parameters.Count() == 1) { method.Invoke(entity, new object[] { action }); } else { method.Invoke(entity, new object[] {}); } }
protected void SetModelErrors(IValidateable entity) { foreach (ValidationFailure error in entity.Errors) { ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } }
protected void SetModelErrors(IValidateable entity, string message) { foreach (ValidationFailure error in entity.Errors) { ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } if (!string.IsNullOrEmpty(message)) SetErrorMessage(message); }
protected void ValidationCheck(IValidateable entity, Actions action) { var result = Validator.Validate(entity, action); if (!result.Successful) { throw new ValidationException("Invalid Data", result.Errors); } }
public static void Init(IValidateable o, TabPage p) { foreach (PropertyInfo pr in o.GetType().GetProperties()) { PropertyInfo pi = o.GetType().GetProperty(pr.Name, typeof(string)); if (pi != null) { pi.SetValue(o, p.Controls[pr.Name].Text); } } }
public static void ParseNValidate(IValidateable o, List <ValidationResult> errors) { //List<ValidationAttribute> atts = new List<ValidationAttribute>(); //atts.Add(new RegularExpressionAttribute()) o.GetType().GetProperties().Where(el => Attribute.IsDefined(el, typeof(StringLengthAttribute))) .ToList().ForEach(pr => { TryValidateValue(o, pr.Name, o.GetType().GetProperty(pr.Name).GetValue(o, null), errors); }); }
public ValidationResult ValidateObject(IValidateable validationObject, ValidationCompleteness validationCompleteness) { var errors = new List <PropertyError>(); errors.AddRange(this.ValidationRules.SelectMany(rule => rule.ValidateObject(validationObject, validationCompleteness).Errors)); var validationResult = new ValidationResult(errors); return(validationResult); }
private void button1_Click_1(object sender, EventArgs e) { List <ValidationResult> errors = new List <ValidationResult>(); foreach (TabPage p in tabControl1.TabPages) { IValidateable obj = (IValidateable)Activator.CreateInstance(Type.GetType("DataAnnotation1." + p.Name.Substring(3))); obj.Init(p); //VALIDATION!! Validator.ParseNValidate(obj, errors); } MessageBox.Show(errors.Count < 1 ? "SUCCESS!!" : string.Join("", errors.Select(er => er.ErrorMessage).ToArray())); }
/// <summary> /// Validates if the object is ok. /// </summary> /// <param name="target">The target.</param> /// <exception cref="BadArgumentsException">If the object is bad.</exception> public static void Validate(IValidateable target) { var reasons = target.IsValid().ToList(); if (false == reasons.Any()) { return; } var result = string.Join(",", reasons.Select(r => $"{r.key} : {r.reason}")); throw new BadArgumentsException(result); }
public ValidationResult ValidateObject(IValidateable validationObject, ValidationCompleteness validationCompleteness) { var match = validationObject as TValidationObject; if (match == null) { return(ValidationResult.Empty()); } var result = this.ValidateObject(match, validationCompleteness); return(result); }
public string ValidateProperty(IValidateable validationObject, string propertyName) { var result = ValidationConstants.NoError(); var validationRuleResults = this.ValidationRules .Select(rule => rule.ValidateProperty(validationObject, propertyName)) .Where(err => !string.IsNullOrWhiteSpace(err)).ToArray(); if (validationRuleResults.Any()) { result += string.Join(Environment.NewLine, validationRuleResults); } return(result); }
public String GetFieldIdentifier(IValidateable validateable, String property) { if (validateable == null) { throw new ArgumentNullException(nameof(validateable)); } var identifier = fieldIdentifier.FirstOrDefault(x => x.Key.Owner == validateable && x.Key.Property == property); if (identifier.Key == null) { fieldIdentifier.Add(FieldReference.Create(validateable, property), Guid.NewGuid()); identifier = fieldIdentifier.FirstOrDefault(x => x.Key.Owner == validateable && x.Key.Property == property); } return(String.Format("{0}_{1}", identifier.Key.DisplayName, identifier.Value.ToString())); }
/// <summary> /// Saves the specified entity record. /// </summary> /// <returns>A task representing an asynchronous LoadAll operation.</returns> /// <param name="entry">The source entity.</param> public virtual async Task <T> SaveAsync(T entry) { if (entry == null) { throw new ArgumentException(nameof(entry)); } if (entry is IValidateable) { IValidateable validateable = entry as IValidateable; if (!validateable.IsValid()) { throw new RecordValidationException(RecordValidationException.DefaultMessage); } } return((entry.Id != Guid.Empty) ? await _repository.UpdateAsync(entry, entry.Id) : await _repository.InsertAsync(entry)); }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { IValidateable entry = (value as BindingGroup).Items[0] as IValidateable; if (entry == null) { return(ValidationResult.ValidResult); } string error = entry.ValidateAndGetError(); if (string.IsNullOrEmpty(error)) { return(ValidationResult.ValidResult); } return(new ValidationResult(false, error)); }
public IEnumerable <string> GetValidationErrors(TRecord record, SaveAction action = SaveAction.NotSet, IDbConnection connection = null) { foreach (var prop in record.GetType().GetProperties().Where(pi => pi.HasSaveAction(action))) { if (RequiredDateNotSet(prop, record)) { yield return($"The {prop.Name} date field requires a value."); } var postulateAttr = prop.GetCustomAttributes <Validation.ValidationAttribute>(); foreach (var attr in postulateAttr) { object value = prop.GetValue(record); if (!attr.IsValid(prop, value, connection)) { yield return(attr.ErrorMessage); } } var validationAttr = prop.GetCustomAttributes <System.ComponentModel.DataAnnotations.ValidationAttribute>(); foreach (var attr in validationAttr) { if (!IsRequiredWithInsertExpression(prop, attr)) { object value = prop.GetValue(record); if (!attr.IsValid(value)) { yield return(attr.FormatErrorMessage(prop.Name)); } } } } IValidateable validateable = record as IValidateable; if (validateable != null) { var errors = validateable.Validate(connection); foreach (var err in errors) { yield return(err); } } }
/// <summary> /// Saves the specified entity record. /// </summary> /// <param name="entry">The source T.</param> public T Save(T entry) { if (entry == null) { throw new ArgumentNullException(nameof(entry)); } if (entry is IValidateable) { IValidateable validateable = entry as IValidateable; if (!validateable.IsValid()) { throw new RecordValidationException(RecordValidationException.DefaultMessage); } } return((entry.Id != Guid.Empty) ? _repository.Update(entry, entry.Id) : _repository.Insert(entry)); }
private static void ValidateId(ValidationResult result, IValidateable entity) { if (entity is IIDEntity) { var idModel = entity as IIDEntity; if (String.IsNullOrEmpty(idModel.Id)) { result.AddSystemError(Resources.ValidationResource.IDIsRequired); } else { if (idModel.Id == Guid.Empty.ToId()) { result.AddSystemError(Resources.ValidationResource.IDMustNotBeEmptyGuid); } if (idModel.Id == "0") { result.AddSystemError(Resources.ValidationResource.IDMustNotBeZero); } } } }
public static void CallCustomValidationRoutine(ValidationResult result, IValidateable entity, MethodInfo method, Actions action) { if (method.ReturnType != typeof(void)) { throw new InvalidOperationException("Custom Validation Method must not return a type, the return type must be [void]"); } var parameters = method.GetParameters(); if (parameters.Count() == 0) { throw new InvalidOperationException("Custom Validation Method must accept at a minimum one parameter, [ValidationResult result]"); } if (parameters[0].ParameterType != typeof(ValidationResult)) { throw new InvalidOperationException("Custom Validation Method must accept the first parameter of [ValidationResult result]"); } if (parameters.Count() > 2) { throw new InvalidOperationException("Custom Validation Method most not accept more than two parameters, it must accept at minimum [ValidationResult result] and optionally [Actions action]."); } if (parameters.Count() == 2 && parameters[1].ParameterType != typeof(Actions)) { throw new InvalidOperationException("Custom Validation Method most optionally accept only a second parameter of [Actions action]."); } if (parameters.Count() == 2) { method.Invoke(entity, new object[] { result, action }); } else { method.Invoke(entity, new object[] { result }); } }
public static bool TryValidateValue(IValidateable o, string propName, object value, ICollection <ValidationResult> errors) // throws ArgumentNullException and System.ComponentModel.DataAnnotations.ValidationException!! { bool isDefined = Attribute.IsDefined(o.GetType().GetProperty(propName), typeof(RegularExpressionAttribute)); ValidationContext vc = new ValidationContext(o, null, null); var attrList = new List <ValidationAttribute>(); ValidationAttribute att = GetAttribute <RegularExpressionAttribute>(o, propName); if (att != null) { attrList.Add(att); } ; //if (( att = GetAttribute<RequiredAttribute>(o, propName)) != null) attrList.Add(att); if ((att = GetAttribute <StringLengthAttribute>(o, propName)) != null) { attrList.Add(att); } return(isDefined ? System.ComponentModel.DataAnnotations.Validator.TryValidateValue(value, vc, errors, attrList) : true); }
private static void ValidateProperty(FormFieldAttribute attr, ValidationResult result, IValidateable entity, PropertyInfo prop, Actions action) { var value = prop.GetValue(entity); if (prop.PropertyType == typeof(string)) { ValidateString(result, prop, attr, value as String); } /// TODO: Find better approeach for detecting generic type entity headers. else if (prop.PropertyType.Name.StartsWith(nameof(EntityHeader))) /* YUCK! KDW 5/12/2017 */ { ValidateEntityHeader(result, prop, attr, value as EntityHeader); } ValidateNumber(result, prop, attr, value); }
public static A GetAttribute <A>(IValidateable o, string prop) where A : Attribute { return(o.GetType().GetProperty(prop).GetCustomAttributes(typeof(A), false).Cast <A>().Single()); }
private static void ValidateString(ValidationResult result, PropertyInfo propertyInfo, FormFieldAttribute attr, String value, IValidateable entity) { var propertyLabel = GetLabel(attr); if (String.IsNullOrEmpty(propertyLabel)) { propertyLabel = propertyInfo.Name; } if (String.IsNullOrEmpty(value) && attr.IsRequired) { var validationMessage = String.Empty; if (attr.FieldType == FieldTypes.Hidden) { result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name), entity.GetType().Name); } else { if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null) { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource); result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null), entity.GetType().Name); } else if (!String.IsNullOrEmpty(attr.LabelDisplayResource)) { validationMessage = Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel); result.AddUserError(validationMessage, entity.GetType().Name); } else { result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name), entity.GetType().Name); } } } if (!String.IsNullOrEmpty(value)) { if (attr.FieldType == FieldTypes.Key) { var reEx = new Regex("^[a-z0-9]{3,30}$"); if (!reEx.Match(value).Success) { if (attr.ResourceType == null) { throw new Exception($"Validating String - Reg Ex Validation has a resource text, but no resource type for field [{attr.LabelDisplayResource}]"); } result.AddUserError(ValidationResource.Common_Key_Validation, entity.GetType().Name); } } if (!String.IsNullOrEmpty(attr.RegExValidation)) { var reEx = new Regex(attr.RegExValidation); if (!reEx.Match(value).Success) { if (attr.ResourceType == null) { throw new Exception($"Validating String - Reg Ex Validation was invalid, but no resource type for field [{attr.LabelDisplayResource}]"); } if (String.IsNullOrEmpty(attr.RegExValidationMessageResource)) { throw new Exception($"Validating String - Reg Ex Validation was invalid, [RegExValidationMessageResource] was null or empty and could not lookup error message for invalid field [{attr.LabelDisplayResource}]."); } else { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RegExValidationMessageResource); if (validationProperty == null) { throw new Exception($"Validating String - Reg Ex Validation was invalid, but could not find validation message resource for field [{attr.LabelDisplayResource}]"); } else { result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null), entity.GetType().Name); } } } } if (attr.MinLength.HasValue && attr.MaxLength.HasValue) { if (value.Length < attr.MinLength || value.Length > attr.MaxLength) { result.AddUserError(Resources.ValidationResource.ValueLength_Between.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()).Replace("[MAX]", attr.MaxLength.ToString()), entity.GetType().Name); } } else if (attr.MaxLength.HasValue) { if (value.Length > attr.MaxLength) { result.AddUserError(Resources.ValidationResource.ValueLength_TooLong.Replace("[PROPERTY]", propertyLabel).Replace("[MAX]", attr.MaxLength.ToString()), entity.GetType().Name); } } else if (attr.MinLength.HasValue) { if (value.Length < attr.MinLength) { result.AddUserError(Resources.ValidationResource.ValueLength_TooShort.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()), entity.GetType().Name); } } } }
private static void ValidateEntityHeader(ValidationResult result, PropertyInfo prop, FormFieldAttribute attr, EntityHeader value, IValidateable entity) { if (value != null && String.IsNullOrEmpty(value.Id) && !String.IsNullOrEmpty(value.Text)) { result.AddSystemError(Resources.ValidationResource.Entity_Header_MissingId_System.Replace("[NAME]", prop.Name)); } else if (value != null && String.IsNullOrEmpty(value.Text) && !String.IsNullOrEmpty(value.Id)) { result.AddSystemError(Resources.ValidationResource.Entity_Header_MissingText_System.Replace("[NAME]", prop.Name)); } else if (attr.IsRequired) { if (value == null || value.IsEmpty()) { AddRequiredFieldMissingMessage(result, attr, prop.Name, entity); } } }
/// <summary>Регистрирует валидируемый объект в контексте валидации</summary> /// <param name="Validateable">Регистрируемый валидируемый объект</param> public void RegisterValidateableElement(IValidateable Validateable) { _validateableElements.Add(Validateable); }
public string ValidateProperty(IValidateable validationObject, string propertyName) { var match = validationObject as TValidationObject; return(match == null ? string.Empty : this.ValidateProperty(match, propertyName)); }
public void AssertInvalidWithAtLeastOneErrorOnProperty(IValidateable entity, string propertyName) { Assert.IsFalse(entity.IsValid); Assert.IsTrue(entity.Errors.Any(e => e.PropertyName.Equals(propertyName))); }
public void AssertIsValid(IValidateable entity) { Assert.IsTrue(entity.IsValid); Assert.AreEqual(0, entity.Errors.Count); }
/// <summary> /// Validate an IValidateable object. /// </summary> /// <param name="entity">Object to validate</param> /// <param name="action">Action to execute: if not specified, use Any, this is normally used for custom validation routines</param> /// <param name="requirePopulatedEHValues">If this is set to true it will require that the entire object graphs, including traversing through EntityHeader<T>.Value will be required if the parameter is required.</param> /// <returns></returns> public static ValidationResult Validate(IValidateable entity, Actions action = Actions.Any, bool requirePopulatedEHValues = false) { var result = new ValidationResult(); if (entity == null) { if (SLWIOC.Contains(typeof(ILogger))) { var logger = SLWIOC.Get <ILogger>(); logger.AddException("Validator_Validate", new Exception("NULL Value Passed to Validate Method")); } result.AddSystemError("Null Value Provided for model on upload."); return(result); } ValidateAuditInfo(result, entity); ValidateId(result, entity); var properties = entity.GetType().GetTypeInfo().GetAllProperties(); foreach (var prop in properties) { var attr = prop.GetCustomAttributes(typeof(FormFieldAttribute), true).OfType <FormFieldAttribute>().FirstOrDefault(); if (attr != null) { ValidateProperty(attr, result, entity, prop, action); } } var methods = entity.GetType().GetTypeInfo().DeclaredMethods; foreach (var method in methods) { var attr = method.GetCustomAttributes(typeof(CustomValidatorAttribute), true).OfType <CustomValidatorAttribute>().FirstOrDefault(); if (attr != null) { CallCustomValidationRoutine(attr, result, entity, method, action); } } foreach (var prop in properties) { var attr = prop.GetCustomAttributes(typeof(FormFieldAttribute), true).OfType <FormFieldAttribute>().FirstOrDefault(); var propValue = prop.GetValue(entity); if (propValue != null) { if (propValue is IValidateable validateablePropValue) { var childResult = Validator.Validate(validateablePropValue, action); result.Concat(childResult); } if (propValue.GetType().GetTypeInfo().IsGenericType&& propValue.GetType().GetGenericTypeDefinition() == typeof(EntityHeader <>)) { var valueProperty = propValue.GetType().GetTypeInfo().GetDeclaredProperty("Value"); if (valueProperty.GetValue(propValue) is IValidateable validatableChild) { var childResult = Validator.Validate(validatableChild, action); result.Concat(childResult); } else { if (attr != null && attr.IsRequired && requirePopulatedEHValues) { AddRequiredFieldMissingMessage(result, attr, prop.Name); } } } if (prop.GetValue(entity) is System.Collections.IEnumerable listValues) { foreach (var listValue in listValues) { if (listValue is IValidateable validatableListValue) { var childResult = Validator.Validate(validatableListValue, action); result.Concat(childResult); } } } } } return(result); }
private static void ValidateAuditInfo(ValidationResult result, IValidateable entity) { if (entity is IAuditableEntity) { var auditableModel = entity as IAuditableEntity; if (String.IsNullOrEmpty(auditableModel.CreationDate)) { result.AddSystemError(Resources.ValidationResource.CreationDateRequired); } else if (!auditableModel.CreationDate.SuccessfulJSONDate()) { if (DateTime.TryParse(auditableModel.CreationDate, CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dateTime)) { auditableModel.CreationDate = dateTime.ToJSONString(); } else { result.AddSystemError(Resources.ValidationResource.CreationDateInvalidFormat + " " + auditableModel.CreationDate); } } if (String.IsNullOrEmpty(auditableModel.LastUpdatedDate)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedDateRequired); } else if (!auditableModel.LastUpdatedDate.SuccessfulJSONDate()) { if (DateTime.TryParse(auditableModel.LastUpdatedDate, CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dateTime)) { auditableModel.LastUpdatedDate = dateTime.ToJSONString(); } else { result.AddSystemError(Resources.ValidationResource.LastUpdateDateInvalidFormat + " " + auditableModel.LastUpdatedDate); } } if (auditableModel.LastUpdatedBy == null) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByNotNull); } else { if (String.IsNullOrEmpty(auditableModel.LastUpdatedBy.Id)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByIdNotNullOrEmpty); } else if (!auditableModel.LastUpdatedBy.Id.SuccessfulId()) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByIdInvalidFormat); } if (String.IsNullOrEmpty(auditableModel.LastUpdatedBy.Text)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByTextNotNullOrEmpty); } } if (auditableModel.CreatedBy == null) { result.AddSystemError(Resources.ValidationResource.CreatedByNotNull); } else { if (String.IsNullOrEmpty(auditableModel.CreatedBy.Id)) { result.AddSystemError(Resources.ValidationResource.CreatedByIdNotNullOrEmpty); } else if (!auditableModel.CreatedBy.Id.SuccessfulId()) { result.AddSystemError(Resources.ValidationResource.CreatedByIdInvalidFormat); } if (String.IsNullOrEmpty(auditableModel.CreatedBy.Text)) { result.AddSystemError(Resources.ValidationResource.CreatedByTextNotNullOrEmpty); } } } }
private static void AddRequiredFieldMissingMessage(ValidationResult result, FormFieldAttribute attr, string propertyName, IValidateable entity) { if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null) { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource); var validationMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null); result.AddUserError(validationMessage, entity.GetType().Name); } else { var propertyLabel = GetLabel(attr); if (String.IsNullOrEmpty(propertyLabel)) { result.AddSystemError(Resources.ValidationResource.Entity_Header_Null_System.Replace("[NAME]", propertyName), entity.GetType().Name); } else { result.AddUserError(Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel), entity.GetType().Name); } } }