Beispiel #1
0
        public void ValidateMethodShouldRaiseErrorsChangedEvent()
        {
            int                  countInvoke     = 0;
            ValidatorBase        validator       = GetValidator();
            INotifyDataErrorInfo notifyDataError = validator;

            notifyDataError.ErrorsChanged += (sender, args) =>
            {
                args.PropertyName.ShouldEqual(PropertyToValidate);
                countInvoke++;
            };

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            notifyDataError.HasErrors.ShouldBeFalse();
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            countInvoke.ShouldEqual(1);
            notifyDataError.HasErrors.ShouldBeTrue();

            if (validator is ManualValidator)
            {
                validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            }
            else
            {
                validator.ValidateAsync(PropertyToValidate);
            }
            countInvoke.ShouldEqual(2);
        }
Beispiel #2
0
        public void GetValidationMessage()
        {
            ValidatorBase validator         = CreateValidator();
            string        validationMessage = validator.GetValidationMessage("Name");

            Assert.AreEqual(GetExpectedValidationMessage(), validationMessage);
        }
        public static string TryLoadCertificateCollection(string certificatePath,
                                                          ref string fingerprintText,
                                                          ref string message)
        {
            var certificates = new X509Certificate2Collection();

            try
            {
                // If this certificate needs a password, it will throw an exception.
                certificates.Import(certificatePath);
                var    thumbprints = new List <string>();
                string state       = nameof(ValidationState.NoMatch);
                foreach (X509Certificate2 certificate in certificates)
                {
                    thumbprints.Add(certificate.Thumbprint);
                    if (certificate.HasPrivateKey)
                    {
                        // Private key detected.
                        state = nameof(ValidationState.Authorized);
                    }
                }

                fingerprintText = string.Join(";", thumbprints);
                message         = "which contains private keys.";
                return(state);
            }
            catch (Exception e)
            {
                string fileName = Path.GetFileName(certificatePath);
                return(ValidatorBase.ReturnUnhandledException(ref message, e, fileName));
            }
        }
    public static void UnilateralTest(string input, ValidatorBase validator)
    {
        var inStream     = new MemoryStream();
        var outBuilder   = new StringBuilder();
        var errorBuilder = new StringBuilder();

        Console.SetIn(new StreamReader(inStream));
        Console.SetOut(new StringWriter(outBuilder));
        Trace.Listeners.Add(new TextWriterTraceListener(new StringWriter(errorBuilder)));
        Console.SetError(new StringWriter(errorBuilder));
        var bytes = Encoding.UTF8.GetBytes(input);

        inStream.Write(bytes, 0, bytes.Length);
        inStream.Position = 0;
        SetStreamToReader(inStream);

        RunProgram();

        var res = outBuilder.ToString();

        try
        {
            validator.Validate(res);
        }
        catch (WrongAnswerException waException)
        {
            waException.Input = input;
            waException.Debug = errorBuilder.ToString();
            throw waException;
        }
    }
Beispiel #5
0
        public void ValidatorShouldUsePropertyMappings()
        {
            ValidatorBase validator  = GetValidator();
            var           dictionary = new Dictionary <string, ICollection <string> >
            {
                {
                    PropertyToValidate,
                    new List <string> {
                        PropertyToMap
                    }
                }
            };

            validator.Initialize(new ValidatorContext(new object(), dictionary, null, null, GetServiceProvider()));
            validator.IsValid.ShouldBeTrue();
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.IsValid.ShouldBeFalse();
            validator.GetErrors(PropertyToValidate).ShouldBeEmpty();

            string[] errors = validator.GetErrors(PropertyToMap).OfType <string>().ToArray();
            errors.Length.ShouldEqual(1);
            errors.Contains(ValidatorError).ShouldBeTrue();

            validator.UpdateErrors(PropertyToMap, null, false);
            validator.GetErrors(PropertyToMap).ShouldBeEmpty();
            validator.IsValid.ShouldBeTrue();
        }
Beispiel #6
0
        public void TestValidationOfANullableShortReturnsCorrectValidator(ValidatorBase validatorBase)
        {
            "Given a new ValidatorBase created from a nullable long"
            .x(() => validatorBase = Validate.That("foo", (short?)3));

            "Test that the type of ValidatorBase returned is a NullableNumericValidator of type short"
            .x(() => validatorBase.Should().BeOfType(typeof(NullableNumericValidator <short>)));
        }
Beispiel #7
0
        public void TestValidationOfANullableDecimalReturnsCorrectValidator(ValidatorBase validatorBase)
        {
            "Given a new ValidatorBase created from a nullable decimal"
            .x(() => validatorBase = Validate.That("foo", (decimal?)3.302));

            "Test that the type of ValidatorBase returned is a NullableNumericValidator of type decimal"
            .x(() => validatorBase.Should().BeOfType(typeof(NullableNumericValidator <decimal>)));
        }
Beispiel #8
0
        public void TestValidationOfAGenericTypeReturnsCorrectValidator(ValidatorBase validatorBase)
        {
            "Given a new ValidatorBase created from a StringBuilder"
            .x(() => validatorBase = Validate.That("foo", new StringBuilder()));

            "Test that the type of ValidatorBase returned is a ClassValidator of type StringBuilder"
            .x(() => validatorBase.Should().BeOfType(typeof(ClassValidator <StringBuilder>)));
        }
Beispiel #9
0
        public void TestValidationOfANullableUnsignedLongReturnsCorrectValidator(ValidatorBase validatorBase)
        {
            "Given a new ValidatorBase created from a nullable unsigned long"
            .x(() => validatorBase = Validate.That("foo", (ulong?)3));

            "Test that the type of ValidatorBase returned is a NullableUnsignedNumericValidator of type unsigned long"
            .x(() => validatorBase.Should().BeOfType(typeof(NullableUnsignedNumericValidator <ulong>)));
        }
Beispiel #10
0
        public void DoubleInitializedValidatorShouldThrowErrorTest()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            ShouldThrow <InvalidOperationException>(
                () => validator.Initialize(new ValidatorContext(new object(), GetServiceProvider())));
        }
        private static ValidatorBase<bool> IsValid(ValidatorBase<bool> validator, bool expected)
        {
            if (validator.Value != expected)
            {
                validator.ArgumentOutRangeMessage();
            }

            return validator;
        }
        public virtual bool IsValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(DefaultValueValidator))
            {
                return(false);
            }
            var baseValidator = (DefaultValueValidator)basvalidator;

            return(!string.IsNullOrEmpty(inputdata));
        }
        public void WhenAddValidatorThenShouldSucceed()
        {
            // ARRANGE
            var validator = new ValidatorBase <Entity>();

            // ACT
            ValidatorsTable.Add(validator);

            // ASSERT
            Assert.IsTrue(true);
        }
        public virtual bool IsMinValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(LengthValidator))
            {
                return(false);
            }

            var baseValidator = (LengthValidator)basvalidator;

            return(baseValidator.MinDblength != null ? inputdata.Length > baseValidator.MinDblength : true);
        }
Beispiel #15
0
        public void IsValidShouldBeFalseIfValidatorHasErrors()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            validator.IsValid.ShouldBeTrue();
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.IsValid.ShouldBeFalse();
            validator.UpdateErrors(PropertyToValidate, null, false);
            validator.IsValid.ShouldBeTrue();
        }
Beispiel #16
0
        public virtual bool IsValid(ValidatorBase basvalidator, string inputdata)
        {
            bool IsNumbervalue = int.TryParse(inputdata, out int ignoreMe);

            if (basvalidator.GetType() != typeof(RangeValidator) && !IsNumbervalue)
            {
                return(false);
            }

            return(IsNumbervalue && Convert.ToInt32(inputdata) >= 0 && Convert.ToInt32(inputdata) <= 1000);
        }
Beispiel #17
0
        public void WhenValidateWithNoRulesThanShouldBeTrue()
        {
            //ARRANGE
            var validator = new ValidatorBase <Entity>();
            var e         = new Entity();

            //ACT
            var condition = validator.Validate(e);

            //ASSERT
            Assert.IsTrue(condition);
        }
Beispiel #18
0
        public void ValidatorShouldUseIgnorePropertiesCollection()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), null, new List <string> {
                PropertyToValidate
            }, null,
                                                      GetServiceProvider()));
            validator.IsValid.ShouldBeTrue();
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.IsValid.ShouldBeTrue();
            validator.GetErrors(PropertyToValidate).ShouldBeEmpty();
        }
 public static string IsValidStatic(ref string matchedPattern,
                                    ref Dictionary <string, string> groups,
                                    ref string failureLevel,
                                    ref string fingerprint,
                                    ref string message)
 {
     return(ValidatorBase.IsValidStatic(Instance,
                                        ref matchedPattern,
                                        ref groups,
                                        ref failureLevel,
                                        ref fingerprint,
                                        ref message));
 }
Beispiel #20
0
        public void WhenValidateWithOneRuleInConstructorThanShouldBeTrue()
        {
            //ARRANGE
            var rule      = new Rule <Entity>(x => x.StringProperty != "some value");
            var validator = new ValidatorBase <Entity>(rule);
            var e         = new Entity();

            //ACT
            var condition = validator.Validate(e);

            //ASSERT
            Assert.IsTrue(condition);
        }
        public virtual bool IsLengthValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(LengthValidator))
            {
                return(false);
            }

            var baseValidator = (LengthValidator)basvalidator;

            return(baseValidator.Dblength != null ? inputdata.Length <= baseValidator.Dblength : true);

            //valid = baseValidator.Options.FirstOrDefault(s=>s.ControlType== ControlType.TextBox)!=null? true : false;
        }
Beispiel #22
0
 private void WriteValidator(string prefix, ValidatorBase validator, params string[] paras)
 {
     if (validator != null)
     {
         if (string.IsNullOrEmpty(validator.ErrorMessage))
         {
             Write(prefix + validator.ValidatorType.ToString(), paras);
         }
         else
         {
             Write(prefix + validator.ValidatorType.ToString(), paras.Union(new string[] { "ErrorMessage = @\"" + validator.ErrorMessage + "\"" }).ToArray());
         }
     }
 }
Beispiel #23
0
        public virtual bool IsValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(RegularExpression))
            {
                return(false);
            }


            var baseValidator = (RegularExpression)basvalidator;

            return(Regex.IsMatch(inputdata, "^4[0-9]{12}(?:[0-9]{3})?$"));

            //  valid = baseValidator.Options.FirstOrDefault(s => s.ControlType == ControlType.Checkbox) != null ? true : false;
        }
Beispiel #24
0
        public void GetAllErrorsShouldReturnAllValidatorErrors()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));

            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.UpdateErrors(PropertyToMap, ValidatorErrors, false);
            var allErrors = validator.GetErrors();

            allErrors.Count.ShouldEqual(2);
            allErrors[PropertyToValidate].Single().ShouldEqual(ValidatorError);
            allErrors[PropertyToMap].Single().ShouldEqual(ValidatorError);
        }
Beispiel #25
0
        public virtual bool IsValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(PercentValidator))
            {
                return(false);
            }


            var baseValidator = (PercentValidator)basvalidator;

            return(true);

            //  valid = baseValidator.Options.FirstOrDefault(s => s.ControlType == ControlType.Checkbox) != null ? true : false;
        }
Beispiel #26
0
        /// <summary>
        /// Sets the <see cref="TrailerRowType"/> (and optionally the <see cref="TrailerRecordIdentifier"/>).
        /// </summary>
        /// <typeparam name="TTrailer">The trailer <see cref="Type"/>.</typeparam>
        /// <param name="recordIdentifier">The record identifier for the trailer row (<c>null</c> indicates that there is no specific identifier).</param>
        /// <param name="trailerValidator">The trailer validator.</param>
        public void SetTrailerRowType <TTrailer>(string recordIdentifier = null, ValidatorBase <TTrailer> trailerValidator = null) where TTrailer : class, new()
        {
            if (TrailerRowType != null)
            {
                throw new InvalidOperationException("The TrailerRowType cannot be set more than once.");
            }

            TrailerRowType = typeof(TTrailer);
            var type = typeof(TTrailer);

            if (type == ContentRowType)
            {
                throw new InvalidOperationException("The TrailerRowType cannot be the same as the ContentRowType.");
            }

            if (type == HeaderRowType)
            {
                throw new InvalidOperationException("The TrailerRowType cannot be the same as the HeaderRowType.");
            }

            if (string.IsNullOrEmpty(recordIdentifier))
            {
                if (IsHierarchical)
                {
                    throw new ArgumentNullException(nameof(recordIdentifier), "The record identifier is required where the file is considered hierarchical.");
                }
            }
            else
            {
                if (!IsHierarchical)
                {
                    throw new ArgumentException("The record identifier can not be specified where the file is not considered hierarchical.", nameof(recordIdentifier));
                }

                if (ContentRecordIdentifier != null && recordIdentifier == ContentRecordIdentifier)
                {
                    throw new ArgumentException("The TrailerRecordIdentifier cannot be the same as the ContentRecordIdentifier.", nameof(recordIdentifier));
                }

                if (HeaderRecordIdentifier != null && recordIdentifier == HeaderRecordIdentifier)
                {
                    throw new ArgumentException("The TrailerRecordIdentifier cannot be the same as the HeaderRecordIdentifier.", nameof(recordIdentifier));
                }
            }

            TrailerRowType          = type;
            TrailerRecordIdentifier = string.IsNullOrEmpty(recordIdentifier) ? null : recordIdentifier;
            TrailerValidator        = trailerValidator;
        }
Beispiel #27
0
        public void UpdateErrorsShouldRaiseEvent()
        {
            bool          isInvoked = false;
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            validator.ErrorsChanged += (sender, args) =>
            {
                sender.ShouldEqual(validator);
                args.PropertyName.ShouldEqual(PropertyToValidate);
                isInvoked = true;
            };
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            isInvoked.ShouldBeTrue();
        }
        public virtual bool IsValid(ValidatorBase basvalidator, string inputdata)
        {
            if (basvalidator.GetType() != typeof(EmailFormatValidator))
            {
                return(false);
            }

            // string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            //          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            //          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            var   baseValidator = (EmailFormatValidator)basvalidator;
            Regex re            = new Regex(baseValidator.RegexFormat);

            return(re.IsMatch(inputdata));
        }
Beispiel #29
0
        public void GetErrorsShouldReturnValidatorErrors()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            validator.GetErrors(PropertyToValidate).ShouldBeEmpty();

            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.GetErrors(PropertyToValidate).OfType <object>().Single().ShouldEqual(ValidatorError);

            validator.UpdateErrors(PropertyToValidate, new object[] { ValidatorError, ValidatorError }, false);
            var errors = validator.GetErrors(PropertyToValidate).OfType <object>().ToArray();

            errors.Length.ShouldEqual(2);
            errors.All(o => Equals(o, ValidatorError)).ShouldBeTrue();
        }
Beispiel #30
0
        public void ValidatorShouldUpdateErrors()
        {
            ValidatorBase validator = GetValidator();

            validator.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            validator.UpdateErrors(PropertyToValidate, ValidatorErrors, false);
            validator.UpdateErrors(PropertyToMap, ValidatorErrors, false);

            validator.GetErrors(PropertyToValidate).OfType <object>().Single().ShouldEqual(ValidatorError);
            validator.GetErrors(PropertyToMap).OfType <object>().Single().ShouldEqual(ValidatorError);

            validator.ClearErrors();
            validator.GetErrors(PropertyToValidate).OfType <object>().ShouldBeEmpty();
            validator.GetErrors(PropertyToMap).OfType <object>().ShouldBeEmpty();
            validator.IsValid.ShouldBeTrue();
        }
Beispiel #31
0
        public void CloneShouldCreateNewValidator()
        {
            ValidatorBase validator = GetValidator();

            validator.Context.ShouldBeNull();
            IValidator clone = validator.Clone();

            validator.ShouldNotEqual(clone);
            clone.Context.ShouldBeNull();

            clone.Initialize(new ValidatorContext(new object(), GetServiceProvider()));
            clone.Context.ShouldNotBeNull();
            IValidator clone2 = clone.Clone();

            clone.ShouldNotEqual(clone2);
            clone2.Context.ShouldBeNull();
        }
Beispiel #32
0
		public static void SetValidator(DependencyObject obj, ValidatorBase value)
		{
			obj.SetValue(ValidatorProperty, value);
		}
Beispiel #33
0
		public void Register(FrameworkElement elementToValidate, ValidatorBase v)
		{
			items.Add(new ManagerList() { Element = elementToValidate, Validator = v });
		}