예제 #1
0
파일: ItemValidator.cs 프로젝트: rkm/RDMP
        private ValidationFailure ValidateSecondayConstraints(object columnValue, object[] otherColumns, string[] otherColumnNames)
        {
            foreach (ISecondaryConstraint secondaryConstraint in SecondaryConstraints)
            {
                ValidationFailure result = secondaryConstraint.Validate(columnValue, otherColumns, otherColumnNames);

                if (result != null)
                {
                    return(result);
                }
            }

            return(null);
        }
예제 #2
0
        private ValidationFailure ValidateAgainstDictionary()
        {
            var keys = new string[_domainObjectDictionary.Keys.Count];
            var vals = new object[_domainObjectDictionary.Values.Count];

            _domainObjectDictionary.Keys.CopyTo(keys, 0);
            _domainObjectDictionary.Values.CopyTo(vals, 0);


            var eList = new List <ValidationFailure>();

            //for all the columns we need to validate
            foreach (ItemValidator itemValidator in ItemValidators)
            {
                object o;
                if (_domainObjectDictionary.TryGetValue(itemValidator.TargetProperty, out o))
                {
                    //get the first validation failure for the given column (or null if it is valid)
                    ValidationFailure result = itemValidator.ValidateAll(o, vals, keys);

                    //if it wasn't valid then add it to the eList
                    if (result != null)
                    {
                        if (result.SourceItemValidator == null)
                        {
                            result.SourceItemValidator = itemValidator;
                            eList.Add(result);
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException("Validation failed: Target field [" + itemValidator.TargetProperty +
                                                        "] not found in dictionary.");
                }
            }

            if (eList.Count > 0)
            {
                return(new ValidationFailure("There are validation errors.", eList));
            }

            return(null);
        }
예제 #3
0
        private void ConfirmIntegrityOfValidationException(ValidationFailure v)
        {
            if (v.GetExceptionList() == null)
            {
                throw new NullReferenceException("Expected ValidationException to produce a List of broken validations, not just 1.  Validation message was:" + v.Message);
            }

            foreach (var validationException in v.GetExceptionList())
            {
                if (validationException.SourceItemValidator == null || validationException.SourceItemValidator.TargetProperty == null)
                {
                    throw new NullReferenceException("Column name referenced in ValidationException was null!, message in the exception was:" + validationException.Message);
                }

                if (validationException.GetExceptionList() != null)
                {
                    throw new Exception("Inception ValidationException detected! not only does the root Exception have a list of subexceptions (expected) but one of those has a sublist too! (unexpected).  This Exception message was:" + validationException.Message);
                }
            }
        }
예제 #4
0
        private ValidationFailure ValidateSecondayConstraints(object columnValue, object[] otherColumns, string[] otherColumnNames)
        {
            foreach (ISecondaryConstraint secondaryConstraint in SecondaryConstraints)
            {
                try
                {
                    ValidationFailure result = secondaryConstraint.Validate(columnValue, otherColumns, otherColumnNames);

                    if (result != null)
                    {
                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Error processing Secondary Constraint validator of Type {secondaryConstraint.GetType().Name} on column {TargetProperty}.  Value being validated was '{columnValue}'", ex);
                }
            }

            return(null);
        }
예제 #5
0
        /// <summary>
        /// Validate against the supplied domain object, which takes the form of a generic object with Properties matching TargetProperty or an SqlDataReader or a DataTable
        /// </summary>
        /// <param name="domainObject"></param>
        /// /// <param name="currentResults">It is expected that Validate is called multiple times (once per row) therefore you can store the Result of the last one and pass it back into the method the next time you call it in order to maintain a running total</param>
        /// <param name="worstConsequence"></param>
        public VerboseValidationResults ValidateVerboseAdditive(object domainObject, VerboseValidationResults currentResults, out Consequence?worstConsequence)
        {
            worstConsequence = null;

            _domainObject = domainObject;

            //first time initialize the results by calling it's constructor (with all the ivs)
            if (currentResults == null)
            {
                currentResults = new VerboseValidationResults(ItemValidators.ToArray());
            }

            ValidationFailure result = ValidateAgainstDomainObject();

            if (result != null)
            {
                worstConsequence = currentResults.ProcessException(result);
            }

            return(currentResults);
        }
예제 #6
0
        public ValidationFailure ValidateAll(object columnValue, object[] otherColumns, string[] otherColumnNames)
        {
            if (otherColumns == null)
            {
                throw new Exception("we were not passed any otherColumns");
            }

            if (otherColumns.Length != otherColumnNames.Length)
            {
                throw new Exception(
                          "there was a difference between the number of columns and the number of column names passed for validation");
            }

            ValidationFailure result = ValidatePrimaryConstraint(columnValue);

            if (result != null)
            {
                return(result);
            }

            return(ValidateSecondayConstraints(columnValue, otherColumns, otherColumnNames));
        }
예제 #7
0
        private ValidationFailure ValidateAgainstDomainObject()
        {
            var eList = new List <ValidationFailure>();

            #region work out other column values
            string[] names  = null;
            object[] values = null;

            object o = _domainObject;

            if (o is DbDataReader)
            {
                DbDataReader reader = (DbDataReader)o;

                names  = new string[reader.FieldCount];
                values = new object[reader.FieldCount];

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    names[i] = reader.GetName(i);

                    if (reader[i] == DBNull.Value)
                    {
                        values[i] = null;
                    }
                    else
                    {
                        values[i] = reader[i].ToString();
                    }
                }
            }

            if (o is DataRow)
            {
                DataRow row = (DataRow)o;

                names  = new string[row.Table.Columns.Count];
                values = new object[row.Table.Columns.Count];

                for (int i = 0; i < row.Table.Columns.Count; i++)
                {
                    names[i] = row.Table.Columns[i].ColumnName;

                    if (row[i] == DBNull.Value)
                    {
                        values[i] = null;
                    }
                    else
                    {
                        values[i] = row[i].ToString();
                    }
                }
            }
            #endregion


            foreach (ItemValidator itemValidator in ItemValidators)
            {
                if (itemValidator.TargetProperty == null)
                {
                    throw new NullReferenceException("Target property cannot be null");
                }

                object value = null;

                try
                {
                    ValidationFailure result = null;

                    //see if it has property with this name
                    if (o is DbDataReader)
                    {
                        value = ((DbDataReader)o)[itemValidator.TargetProperty];
                        if (value == DBNull.Value)
                        {
                            value = null;
                        }

                        result = itemValidator.ValidateAll(value, values, names);
                    }
                    else
                    if (o is DataRow)
                    {
                        result = itemValidator.ValidateAll(((DataRow)o)[itemValidator.TargetProperty], values, names);
                    }
                    else
                    {
                        Dictionary <string, object> propertiesDictionary = DomainObjectPropertiesToDictionary(o);

                        if (propertiesDictionary.ContainsKey(itemValidator.TargetProperty))
                        {
                            value = propertiesDictionary[itemValidator.TargetProperty];

                            result = itemValidator.ValidateAll(value, propertiesDictionary.Values.ToArray(), propertiesDictionary.Keys.ToArray());
                        }
                        else
                        {
                            throw new MissingFieldException("Validation failed: Target field [" +
                                                            itemValidator.TargetProperty +
                                                            "] not found in domain object.");
                        }
                    }
                    if (result != null)
                    {
                        if (result.SourceItemValidator == null)
                        {
                            result.SourceItemValidator = itemValidator;
                        }

                        eList.Add(result);
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    throw new IndexOutOfRangeException("Validation failed: Target field [" + itemValidator.TargetProperty + "] not found in domain object.");
                }
            }

            if (eList.Count > 0)
            {
                return(new ValidationFailure("There are validation errors.", eList));
            }

            return(null);
        }
예제 #8
0
        public Consequence ProcessException(ValidationFailure rootValidationFailure)
        {
            try
            {
                ConfirmIntegrityOfValidationException(rootValidationFailure);

                Dictionary <ItemValidator, Consequence> worstConsequences = new Dictionary <ItemValidator, Consequence>();

                foreach (var subException in rootValidationFailure.GetExceptionList())
                {
                    if (!subException.SourceConstraint.Consequence.HasValue)
                    {
                        throw new NullReferenceException("ItemValidator of type " + subException.SourceItemValidator.GetType().Name + " on column " + subException.SourceItemValidator.TargetProperty + " has not had it's Consequence configured");
                    }

                    //we have encountered a rule that will invalidate the entire row, it's a good idea to keep a track of each of these since it would be rubbish to get a report out the other side that simply says 100% of rows invalid!
                    if (subException.SourceConstraint.Consequence == Consequence.InvalidatesRow)
                    {
                        if (!ReasonsRowsInvalidated.Contains(subException.SourceItemValidator.TargetProperty + "|" + subException.SourceConstraint.GetType().Name))
                        {
                            ReasonsRowsInvalidated.Add(subException.SourceItemValidator.TargetProperty + "|" + subException.SourceConstraint.GetType().Name);
                        }
                    }

                    if (worstConsequences.Keys.Contains(subException.SourceItemValidator) == true)
                    {
                        //see if situation got worse
                        Consequence oldConsequence = worstConsequences[subException.SourceItemValidator];
                        Consequence newConsequence = subException.SourceConstraint.Consequence.Value;

                        if (newConsequence > oldConsequence)
                        {
                            worstConsequences[subException.SourceItemValidator] = newConsequence;
                        }
                    }
                    else
                    {
                        //new validation error for this column
                        worstConsequences.Add(subException.SourceItemValidator, (Consequence)subException.SourceConstraint.Consequence);
                    }
                }

                //now record the worst case event
                if (worstConsequences.Values.Contains(Consequence.InvalidatesRow))
                {
                    CountOfRowsInvalidated++;
                }

                foreach (var itemValidator in worstConsequences.Keys)
                {
                    string columnName = itemValidator.TargetProperty;

                    //increment the most damaging consequence count for this cell
                    DictionaryOfFailure[columnName][worstConsequences[itemValidator]]++;
                }

                return(worstConsequences.Max(key => key.Value));
            }
            catch (Exception e)
            {
                throw new Exception("An error occurred when trying to process a ValidationException into Verbose results:" + e.Message, e);
            }
        }