using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using log4net; using Sleis.Models; using Sleis.Utility; using Sleis.ViewModels; using Spring.Validation; using System.Text; using Spring.Expressions; using Spring.Objects; using System.Reflection; namespace Sleis.Validation.Spring { public class HundredPercentValidator : BaseSimpleValidator { public string ProviderFormat { get; set; } public string MessageId { get; set; } public string Select { get; set; } internal static ILog Log; public HundredPercentValidator() { Log = LogManager.GetLogger(this.GetType()); } public override string ToString() { return ReflectionUtility.GetPublicPropertiesString(this); } public override bool Validate(object validationContext, IDictionary contextParams, IValidationErrors errors) { Log.DebugFormat("Validate({0},{1},{2})", validationContext, contextParams, errors); if (String.IsNullOrEmpty(Select)) { throw new ArgumentNullException("Select"); } if (base.EvaluateWhen(validationContext, contextParams)) { object objectToValidate = base.EvaluateTest(validationContext, contextParams); IEnumerable objects = objectToValidate as IEnumerable; IEnumerator enumerator = objects.GetEnumerator(); int counter = 0; decimal runningTotal = 0; IValidationContextProvider contextProvider = null; while (enumerator.MoveNext()) { object candidateObject = enumerator.Current; Log.DebugFormat("Validating: {0}", candidateObject); ObjectWrapper wrapper = new ObjectWrapper(candidateObject); object decimalPropertyValue = wrapper.GetPropertyValue(Select); contextProvider = candidateObject as IValidationContextProvider; if (decimalPropertyValue != null) { runningTotal += Convert.ToDecimal(decimalPropertyValue); } counter++; } int runningTotalAsInt = Convert.ToInt32(runningTotal); if (runningTotalAsInt != 100) { string lastProvider = String.Format(ProviderFormat, counter -1) + Select; errors.AddError(lastProvider, new ErrorMessage(MessageId, (contextProvider == null) ? null : contextProvider.ValidationContxt)); } } return errors.IsEmpty; } protected override bool Validate(object objectToValidate) { return Validate(objectToValidate, null, new ValidationErrors()); } } }