public void TestAdd_1Result()
 {
     _results.Add(new ValidationResult("a"));
     Assert.Equal(1, _results.Count);
     Assert.Equal("a", _results.First().ErrorMessage);
     Assert.False(_results.IsValid);
 }
        public void ValidationResult_ToString_WithCorrectFormat()
        {
            ValidationResultCollection collection = new ValidationResultCollection();

            collection.Add(new ValidationResult("This is an error message", new string[] { "Property1", "Property2" }));
            collection.Add(new ValidationResult("This is an error message", new string[] { "Property1", "Property2" }));

            Assert.AreEqual("This is an error message (Property1, Property2)\nThis is an error message (Property1, Property2)\n", collection.ToString());
        }
Esempio n. 3
0
 /// <summary>
 /// 获取验证结果
 /// </summary>
 private ValidationResultCollection GetResult( IEnumerable<ValidationResult> results ) 
 {
     var result = new ValidationResultCollection();
     foreach ( var each in results )
         result.Add( new System.ComponentModel.DataAnnotations.ValidationResult( each.Message ) );
     return result;
 }
Esempio n. 4
0
 /// <summary>
 /// 验证
 /// </summary>
 protected override void Validate(ValidationResultCollection results)
 {
     if (Id == null || Id.Equals(default(TKey)))
     {
         results.Add(new ValidationResult("Id不能为空"));
     }
 }
Esempio n. 5
0
 private static IValidationResultCollection GetCompositeResultsPrivate(IResourceManager mgr, string rule, IValidator[] validators)
 {
     ValidationResultCollection results = new ValidationResultCollection(mgr, rule);
     foreach (IValidator validator in validators)
         results.Add(validator.Validate());
     return results;
 }
Esempio n. 6
0
 /// <summary>
 /// 验证
 /// </summary>
 protected override void Validate(ValidationResultCollection results)
 {
     if (Id == Guid.Empty)
     {
         results.Add(new ValidationResult("Id不能为空"));
     }
 }
        protected override void OnValidateObject(ValidationResultCollection results)
        {
            base.OnValidateObject(results);

            if (FirstName == LastName && FirstName != "")
            {
                results.Add(new ValidationResult("First and last names cannot match", new string[] { "FirstName", "LastName" }));
            }
        }
Esempio n. 8
0
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection result = new ValidationResultCollection(ResourceManager, "version");

            foreach (IICalendar calendar in Calendars)
            {
                result.Add(
                    ValidationResult.GetCompositeResults(
                        ResourceManager,
                        new PropertyCountValidation(ResourceManager, calendar, "VCALENDAR", "VERSION", 1, 1)
                    )
                );

                if (BoolUtil.IsTrue(result.Passed))
                {
                    try
                    {
                        // Ensure the "VERSION" property can be parsed as a version number.
                        Version v = new Version(calendar.Version);
                        Version req = new Version(2, 0);
                        if (req > v)
                        {
                            // Ensure the "VERSION" is at least version 2.0.
                            Error(result, "versionGE2_0Error");
                        }

                        // Ensure the VERSION property is the first property encountered on the calendar.
                        StringReader sr = new StringReader(iCalText);
                        string line = sr.ReadLine();
                        bool hasBegun = false;
                        while (line != null)
                        {
                            if (hasBegun)
                            {
                                if (!line.StartsWith("VERSION", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    Warning(result, "versionFirstError");
                                }
                                break;
                            }

                            if (line.StartsWith("BEGIN:VCALENDAR", StringComparison.InvariantCultureIgnoreCase))
                                hasBegun = true;

                            line = sr.ReadLine();
                        }
                    }
                    catch
                    {
                        Error(result, "versionNumberError");
                    }
                }
            }

            return result;
        }
Esempio n. 9
0
        /// <summary>
        /// 获取验证结果
        /// </summary>
        private ValidationResultCollection GetResult(IEnumerable <ValidationResult> results)
        {
            var result = new ValidationResultCollection();

            foreach (var each in results)
            {
                result.Add(new System.ComponentModel.DataAnnotations.ValidationResult(each.Message));
            }
            return(result);
        }
Esempio n. 10
0
        private void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute)
        {
            bool isValid = attribute.IsValid(property.GetValue(_target));

            if (isValid)
            {
                return;
            }
            _results.Add(new ValidationResult(GetErrorMessage(attribute)));
        }
 public void ValidationResultCollection_Test1()
 {
     using (var verify = new Verify())
     {
         var collection = new ValidationResultCollection();
         var result     = collection.Add("Test", "FirstName", "LastName");
         verify.AreEqual("Test", result.ErrorMessage, "Error message");
         verify.AreEqual("FirstName", result.MemberNames.ToList()[0], "member 0");
         verify.AreEqual("LastName", result.MemberNames.ToList()[1], "member 1");
     }
 }
 public void ValidationResultCollection_Test1()
 {
     using (var verify = new Verify())
     {
         var collection = new ValidationResultCollection();
         var result = collection.Add("Test", "FirstName", "LastName");
         verify.AreEqual("Test", result.ErrorMessage, "Error message");
         verify.AreEqual("FirstName", result.MemberNames.ToList()[0], "member 0");
         verify.AreEqual("LastName", result.MemberNames.ToList()[1], "member 1");
     }
 }
        /// <summary>
        /// 获取验证结果
        /// </summary>
        private ValidationResultCollection GetResult(IEnumerable <ValidationResult> results)
        {
            ValidationResultCollection _result = new ValidationResultCollection();

            foreach (ValidationResult item in results)
            {
                _result.Add(new System.ComponentModel.DataAnnotations.ValidationResult(item.Message));
            }

            return(_result);
        }
Esempio n. 14
0
        public ValidationResultCollection ValidateAttributes(ExtractedAttributes extractedAttributes)
        {
            var attributes = (ExtractedAttributes)extractedAttributes;

            validationResult = new ValidationResultCollection();

            if (attributes.Text == "")
            {
                validationResult.Add(new MissingItem("No Interned Text"));
            }

            return(validationResult);
        }
Esempio n. 15
0
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection results = new ValidationResultCollection(ResourceManager);
            results.Add(
                new StringPropertyValidation(
                    ResourceManager,
                    Container,
                    PropertyName
                ).Validate()
            );

            return results;
        }
        protected override IValidationResultCollection ValidateProperty(ICalendarProperty p)
        {
            ValidationResultCollection result = new ValidationResultCollection(ResourceManager);
            if (p != null)
            {
                result.Passed = true;

                // Get the escaped value for this property.
                // This is stored during deserialization when
                // SerializationSettings.StoreExtraSerializationData is true.
                object escapedValue = p.GetService("EscapedValue");

                List<string> values = new List<string>();
                if (escapedValue is string)
                    values.Add((string)escapedValue);
                else if (escapedValue is IList<string>)
                    values.AddRange((IList<string>)escapedValue);

                // Validate the encoding
                EncodableDataType dt = new EncodableDataType();
                dt.AssociatedObject = p;
                EncodableDataTypeValidation validation = new EncodableDataTypeValidation(ResourceManager, dt);
                result.Add(validation.Validate());

                foreach (string value in values)
                {
                    // Find single commas
                    if (Regex.IsMatch(value, @"(?<!\\),"))
                    {
                        Error(result, "textEscapeCommasError", p.Line, p.Column, p.Name);
                    }

                    // Find single semicolons
                    if (Regex.IsMatch(value, @"(?<!\\);"))
                    {
                        Error(result, "textEscapeSemicolonsError", p.Line, p.Column, p.Name);
                    }

                    // Find backslashes that are not escaped
                    if (Regex.IsMatch(value, @"\\([^\\nN;,])"))
                    {
                        Error(result, "textEscapeBackslashesError", p.Line, p.Column, p.Name);
                    }
                }
            }

            return result;
        }
Esempio n. 17
0
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection result = new ValidationResultCollection(ResourceManager, Rule);
            result.Passed = true;

            if (Calendars != null)
            {
                foreach (IICalendar calendar in Calendars)
                {
                    foreach (IEvent evt in calendar.Events)
                        result.Add(ValidateEvent(evt));
                }
            }

            return result;
        }
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection result = new ValidationResultCollection(ResourceManager);
            result.Passed = true;

            if (Calendars != null)
            {
                foreach (IICalendar calendar in Calendars)
                {
                    foreach (ICalendarObject obj in calendar.Children)
                        result.Add(ValidateObject(obj));
                }
            }

            return result;
        }
Esempio n. 19
0
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection results = new ValidationResultCollection(ResourceManager);

            if (Container != null &&
                Container.Properties != null)
            {
                foreach (ICalendarProperty p in Container.Properties)
                {
                    if (p.Name.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase))
                        results.Add(ValidateProperty(p));
                }
            }

            return results;
        }
Esempio n. 20
0
        public override IValidationResultCollection Validate()
        {
            ValidationResultCollection results = new ValidationResultCollection(ResourceManager);
            results.Passed = true;

            if (Calendars != null)
            {
                foreach (IICalendar calendar in Calendars)
                {
                    results.Add(ValidationResult.GetCompositeResults(
                        ResourceManager,
                        "prodID",
                        new PropertyCountValidation(ResourceManager, calendar, "VCALENDAR", "PRODID", 1, 1)
                    ));
                }
            }

            return results;
        }
Esempio n. 21
0
        protected override IValidationResultCollection ValidateObject(ICalendarObject component)
        {
            ValidationResultCollection result = new ValidationResultCollection(ResourceManager, "component");

            if (component is ICalendarComponent)
            {
                switch (component.Name.ToUpper())
                {
                    case "VALARM": // FIXME: VALARM should only be valid within recurring components.
                    case "VEVENT":
                    case "VTODO":
                    case "VJOURNAL":
                    case "VTIMEZONE":
                    case "VFREEBUSY":
                    case "DAYLIGHT":
                    case "STANDARD":
                        break;
                    case "VNOTE":
                        {
                            Warning(result, "vnoteDeprecatedError", component.Line, component.Column);
                        } break;
                    default:
                        {
                            // FIXME: return an ERROR for nonstandard components without an "X-" prefix, and
                            // a WARNING for "X-" components.
                        } break;
                }

                // Validation of children of the component, for subcomponents.
                // This is necessary for DAYLIGHT, STANDARD, and VALARM.
                foreach (ICalendarObject child in component.Children)
                {
                    IValidationResultCollection childResult = ValidateObject(child);
                    if (childResult.Passed != null && childResult.Passed.HasValue && !childResult.Passed.Value)
                        result.Add(childResult);
                }
            }

            return result;
        }
Esempio n. 22
0
        protected override void OnValidateObject(ValidationResultCollection results)
        {
            base.OnValidateObject(results);

            if (FirstName == LastName && FirstName != "")
                results.Add(new ValidationResult("First and last names cannot match", new string[] { "FirstName", "LastName" }));
        }
Esempio n. 23
0
 private void ErrorInternal(
     ValidationResultCollection results, 
     string errorName, 
     ValidationResultInfoType type, 
     int line,
     int col,
     params object[] objects)
 {
     results.Passed = false;
     ValidationErrorWithLookup error = new ValidationErrorWithLookup(ResourceManager, errorName, type, line, col);
     error.Message = string.Format(error.Message, objects);
     if (error.Resolutions != null)
     {
         // Format each resolution as well.
         for (int i = 0; i < error.Resolutions.Length; i++)
             error.Resolutions[i] = string.Format(error.Resolutions[i], objects);
     }
     results.Add(error);
 }
Esempio n. 24
0
 public void TestAdd_Null()
 {
     _results.Add(null);
     Assert.Equal(0, _results.Count);
 }
Esempio n. 25
0
 /// <summary>
 /// The validate.
 /// </summary>
 /// <param name="results">
 /// The results.
 /// </param>
 protected override void Validate(ValidationResultCollection results)
 {
     results.Add(new MinLengthValidationRule(this.Name).Validate());
     base.Validate(results);
 }
Esempio n. 26
0
        public ValidationResultList Validate(T input)
        {
            if (null == this.Source)
            {
                throw new InvalidOperationException("The Source property must be set before calling Validate");
            }
            ValidationResultCollection results = new ValidationResultCollection();

            this.Source.ValidationEventHandler = (e) =>
            {
                if (null == e)
                {
                    throw new ArgumentNullException("e");
                }
                if (null == e.Exception)
                {
                    throw new ArgumentException("The validation event args must contain an exception");
                }
                ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", e.Exception);
                if (null != r)
                {
                    ValidationInstance vi = null;
                    if (e.Exception is System.Xml.Schema.XmlSchemaException)
                    {
                        vi = new ValidationInstance()
                        {
                            LinePosition = (e.Exception as System.Xml.Schema.XmlSchemaException).LinePosition,
                            LineNumber   = (e.Exception as System.Xml.Schema.XmlSchemaException).LineNumber,
                            Status       = ValidationStatus.Exception
                        };
                    }
                    if (null != vi)
                    {
                        r.Instances.Add(vi);
                    }
                    results.Add(r.Message, r);
                }
                else
                {
                    results.Add(e.Message, new ValidationResult()
                    {
                        Exception = e.Exception,
                        Message   = e.Message
                    });
                }
            };
            System.Xml.Linq.XDocument doc = null;
            //doc.Schemas = xmlReader.Settings.Schemas;
            using (this.TimedLogs.Step("Loading and parsing XML file"))
            {
                DateTime start = DateTime.Now;
                try
                {
                    using (XmlReader xmlReader = this.Source.GetXmlReader(input))
                    {
                        doc = System.Xml.Linq.XDocument.Load(xmlReader, System.Xml.Linq.LoadOptions.SetLineInfo);
                    }
                }
                catch (System.Xml.XmlException e)
                {
                    ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", e);
                    r.Instances.Add(new ValidationInstance()
                    {
                        LineNumber   = e.LineNumber,
                        LinePosition = e.LinePosition,
                        Status       = ValidationStatus.Exception
                    });
                    if (null != r)
                    {
                        results.Add(r.Message, r);
                    }
                }
                // Check to see whether there was an xsi:schemaLocation
                if (
                    (null != doc)
                    &&
                    (results.Count != 0)
                    &&
                    this.AttemptSchemaLocationInjection
                    )
                {
                    XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(new NameTable());
                    xmlnsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                    if (((double)doc.XPathEvaluate("count(//@xsi:schemaLocation)", xmlnsmgr)) == 0)
                    {
                        results.Clear();
                        // Add in to say we're missing an xsi:schemaLocation attribute
                        ValidationResult r = this.XmlExceptionInterpreters.Interpret("Structure", new ValidationException("Missing xsi:schemaLocation attribute"));
                        r.Instances.Add(new ValidationInstance()
                        {
                            LineNumber   = (doc.Root as IXmlLineInfo).LineNumber,
                            LinePosition = (doc.Root as IXmlLineInfo).LinePosition,
                            Status       = ValidationStatus.Warning
                        });
                        if (null != r)
                        {
                            results.Add(r.Message, r);
                        }
                        // If we're missing an xsi:schemaLocation then it'll all go to pot.
                        // Be nice and try and add the data.
                        XmlSchemaSet schemaSet = new XmlSchemaSet(new NameTable());
                        schemaSet.XmlResolver = this.XmlCachingResolver as XmlResolver;
                        schemaSet.Add
                        (
                            "http://xcri.org/profiles/1.2/catalog",
                            "http://www.xcri.co.uk/bindings/xcri_cap_1_2.xsd"
                        );
                        schemaSet.Add
                        (
                            "http://xcri.org/profiles/1.2/catalog/terms",
                            "http://www.xcri.co.uk/bindings/xcri_cap_terms_1_2.xsd"
                        );
                        schemaSet.Add
                        (
                            "http://xcri.co.uk",
                            "http://www.xcri.co.uk/bindings/coursedataprogramme.xsd"
                        );
                        schemaSet.Compile();
                        doc.Validate(schemaSet, new ValidationEventHandler((o, e) =>
                        {
                            this.Source.ValidationEventHandler(e);
                        }));
                    }
                }
                if (null != doc)
                {
                    using (this.TimedLogs.Step("Executing content validators"))
                    {
                        if (null != this.XmlContentValidators)
                        {
                            foreach (var cv in this.XmlContentValidators)
                            {
                                var vrc = cv.Validate(doc.Root);
                                if (null != vrc)
                                {
                                    foreach (var vr in vrc)
                                    {
                                        if (null != vr)
                                        {
                                            results.Add(vr.Message, vr);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(new ValidationResultList(results.Values)
            {
                Document = doc
            });
        }
Esempio n. 27
0
        public override IValidationResultCollection Validate()
        {
            if (Ruleset != null)
            {
                Debug.WriteLineWithTimestamp("Validating...");
                ValidationResultCollection results = new ValidationResultCollection(ResourceManager, "all");
                int i = 0;
                foreach (IValidationRule rule in Ruleset.Rules)
                {
                    i++;
                    var status = ((i * 1.0) / Ruleset.Rules.Length) * 100;
                    Logger.SetStatus(String.Format("{0:0}", status));
                    Logger.LogMessage(rule.ValidatorType.FullName);

                    IValidator validator = null;

                    Type validatorType = rule.ValidatorType;
                    if (validatorType != null)
                        validator = ValidatorActivator.Create(validatorType, ResourceManager, Calendars, iCalendarText);

                    if (validator != null)
                    {
                        IValidationResultCollection currentResults = validator.Validate();
                        results.Add(currentResults);

                        // Determine if there were any fatal errors in the results.
                        // If there are, then we need to abort any further processing!
                        if (results.IsFatal)
                            break;
                    }
                }
                Debug.WriteLineWithTimestamp("Done.");

                // We at least gave the validators a chance to handle the error in
                // a different manner.  If they haven't produced a more specific
                // error, then we'll fall back to the basic "parsing" error.
                if (BoolUtil.IsTrue(results.Passed))
                {
                    if (_MissingValidators.Count > 0)
                    {
                        results.Passed = false;
                        foreach (IValidationResultInfo error in _MissingValidators)
                            results.Add(error);
                    }
                }

                Debug.Flush();
                return results;
            }
            else return null;
        }
Esempio n. 28
0
 public void TestAdd_Null()
 {
     _results.Add(null);
     _results.Add(ValidationResult.Success);
     Assert.AreEqual(0, _results.Count);
 }