Example #1
1
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            attribute.ErrorMessage = "The field Length must be between {1} and {2}.";

            var adapter = new RangeAttributeAdapter(attribute, stringLocalizer: null);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-range", "original");
            context.Attributes.Add("data-val-range-max", "original");
            context.Attributes.Add("data-val-range-min", "original");

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-max", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-min", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
Example #2
0
 private static IRangeFacet Create(RangeAttribute attribute, bool isDate, IFacetHolder holder) {
     if (attribute != null && attribute.OperandType != typeof (int) && attribute.OperandType != typeof (double)) {
         Log.WarnFormat("Unsupported use of range attribute with explicit type on {0}", holder);
         return null;
     }
     return attribute == null ? null : new RangeFacetAnnotation(attribute.Minimum, attribute.Maximum, isDate, holder);
 }
        public LocalizedRangeAttribute(RangeAttribute attribute, Localizer t)
            : base(attribute.OperandType, new FormatterConverter().ToString(attribute.Minimum), new FormatterConverter().ToString(attribute.Maximum)) {
            if ( !String.IsNullOrEmpty(attribute.ErrorMessage) )
                ErrorMessage = attribute.ErrorMessage;

            T = t;
        }
 public static void Can_construct_and_get_minimum_and_maximum_for_double_constructor()
 {
     var attribute = new RangeAttribute(1.0, 3.0);
     Assert.Equal(1.0, attribute.Minimum);
     Assert.Equal(3.0, attribute.Maximum);
     Assert.Equal(typeof(double), attribute.OperandType);
 }
Example #5
0
 public static void SetRange(this UISlider slider, RangeAttribute range)
 {
     slider.InvokeOnMainThread(() =>
         {
             if (range.OperandType == typeof(int))
             {
                 slider.SetRange((int)range.Minimum, (int)range.Maximum);
             }
             else if (range.OperandType == typeof(long))
             {
                 slider.SetRange((long)range.Minimum, (long)range.Maximum);
             }
             else if (range.OperandType == typeof(decimal))
             {
                 slider.SetRange((decimal)range.Minimum, (decimal)range.Maximum);
             }
             else if (range.OperandType == typeof(float))
             {
                 slider.SetRange((float)range.Minimum, (float)range.Maximum);
             }
             else if (range.OperandType == typeof(double))
             {
                 slider.SetRange((double)range.Minimum, (double)range.Maximum);
             }
         });
 }
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            attribute.ErrorMessage = "The field Length must be between {1} and {2}.";

            var expectedProperties = new object[] { "Length", 0m, 100m };
            var expectedMessage = "The field Length must be between 0 and 100.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RangeAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("range", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(0m, rule.ValidationParameters["min"]);
            Assert.Equal(100m, rule.ValidationParameters["max"]);
            Assert.Equal(expectedMessage, rule.ErrorMessage);
        }
 public static void Can_construct_and_get_minimum_and_maximum_for_int_constructor()
 {
     var attribute = new RangeAttribute(1, 3);
     Assert.Equal(1, attribute.Minimum);
     Assert.Equal(3, attribute.Maximum);
     Assert.Equal(typeof(int), attribute.OperandType);
 }
        public RangeAttributeAdapter(ModelMetadata metadata, ControllerContext context, RangeAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (!string.IsNullOrWhiteSpace(Attribute.ErrorMessage)) return;

            if (Attribute.ErrorMessageResourceType == null)
            {
                Attribute.ErrorMessageResourceType = typeof(Message);
            }

            if (string.IsNullOrWhiteSpace(Attribute.ErrorMessageResourceName))
            {
                if (metadata.ModelType == typeof(short) || metadata.ModelType == typeof(int) || metadata.ModelType == typeof(long))
                {
                    Attribute.ErrorMessageResourceName = "PropertyValueRangeNumber";
                }
                else if (metadata.ModelType == typeof(decimal))
                {
                    Attribute.ErrorMessageResourceName = "PropertyValueRangeDecimal";
                }
                else
                {
                    Attribute.ErrorMessageResourceName = "PropertyValueRequired";
                }

            }
        }
Example #9
0
        public void AddValidation_WithLocalization()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            attribute.ErrorMessage = "The field Length must be between {1} and {2}.";

            var expectedProperties = new object[] { "Length", 0m, 100m };
            var expectedMessage = "The field Length must be between 0 and 100.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer
                .Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RangeAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-range", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-range-max", kvp.Key); Assert.Equal("100", kvp.Value); },
                kvp => { Assert.Equal("data-val-range-min", kvp.Key); Assert.Equal("0", kvp.Value); });
        }
Example #10
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="numericAttribute">
        /// The numeric attribute.
        /// </param>
        /// <param name="rangeAttribute">
        /// The range attribute.
        /// </param>
        /// <returns>
        /// The <see cref="NumericFieldOptions"/>.
        /// </returns>
        public static NumericFieldOptions Create(NumericAttribute numericAttribute, RangeAttribute rangeAttribute)
        {
            var result = new NumericFieldOptions();
            if (numericAttribute == null)
            {
                result.DisplayFormat = NumericTypes.Numeric;
                result.NumberOfDecimals = 0;
            }
            else
            {
                result.DisplayFormat = numericAttribute.NumericType;
                result.NumberOfDecimals = numericAttribute.NumberOfDigits;
            }

            if (rangeAttribute == null)
            {
                result.Min = 0;
                result.Max = 999999999;
            }
            else
            {
                result.Min = rangeAttribute.Minimum;
                result.Max = rangeAttribute.Maximum;
            }

            return result;
        }
        private static RangedNumberRequest Create(RangeAttribute rangeAttribute, object request)
        {
            Type conversionType = null;

            var pi = request as PropertyInfo;
            if (pi != null)
            {
                conversionType = pi.PropertyType;
            }
            else
            {
                var fi = request as FieldInfo;
                if (fi != null)
                {
                    conversionType = fi.FieldType;
                }
                else
                {
                    conversionType = rangeAttribute.OperandType;
                }
            }

            Type underlyingType = Nullable.GetUnderlyingType(conversionType);
            if (underlyingType != null)
            {
                conversionType = underlyingType;
            }

            return new RangedNumberRequest(
                conversionType,
                Convert.ChangeType(rangeAttribute.Minimum, conversionType, CultureInfo.CurrentCulture),
                Convert.ChangeType(rangeAttribute.Maximum, conversionType, CultureInfo.CurrentCulture)
                );
        }
 public static void Can_construct_and_get_minimum_and_maximum_for_type_with_strings_constructor()
 {
     var attribute = new RangeAttribute(null, "SomeMimumum", "SomeMaximum");
     Assert.Equal("SomeMimumum", attribute.Minimum);
     Assert.Equal("SomeMaximum", attribute.Maximum);
     Assert.Equal(null, attribute.OperandType);
 }
 public TypePropertyValidationRuleMetadata(RangeAttribute attribute)
     : this((ValidationAttribute) attribute)
 {
     Name = "range";
     Value1 = attribute.Minimum;
     Value2 = attribute.Maximum;
     _type = "array";
 }
 public ResourseBaseRangeAttributeAdapter(ModelMetadata metadata,
                                   ControllerContext context,
                                   RangeAttribute attribute)
     : base(metadata, context, attribute)
 {
     attribute.ErrorMessageResourceType = typeof(AvicolaGlobalResources);
     attribute.ErrorMessageResourceName = "Range";
 }
 public static void Can_validate_valid_values_for_double_constructor()
 {
     var attribute = new RangeAttribute(1.0, 3.0);
     AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid
     AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid
     AssertEx.DoesNotThrow(() => attribute.Validate(1.0, s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate(2.0, s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate(3.0, s_testValidationContext));
 }
 private void AddRangeValidation(HtmlTag tag, RangeAttribute range)
 {
     if (range.Minimum != null)
     {
         tag.Attr("min", range.Minimum);
     }
     if (range.Maximum != null)
     {
         tag.Attr("max", range.Maximum);
     }
 }
Example #17
0
        public override ModelValidator Create(
            IStorageValidator validator, Type defaultResourceType, ModelMetadata metadata, ControllerContext context)
        {
            StorageValidator<RangeValidatorData> vldtr = validator as StorageValidator<RangeValidatorData>;
            if (vldtr == null)
                throw new System.IO.InvalidDataException(
                    "Validator value must be of type StorageValidator<RangeValidatorData>.");

            //string minValue = null;
            //try
            //{
            //    minValue = validator.data.min;
            //}
            //catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            //{
            //    throw new System.IO.InvalidDataException(
            //        string.Format("Min value can't be null. Element: {0}.", validator.Name));
            //}

            //string maxValue = null;  //xmlElement.GetValueOrNull("max");
            //try
            //{
            //    maxValue = validator.data.max;
            //}
            //catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            //{
            //    throw new System.IO.InvalidDataException(
            //        string.Format("Max value can't be null. Element: {0}.", validator.Name));
            //}

            //string typeName = null; //xmlElement.GetValueOrNull("type");
            //try
            //{
            //    typeName = validator.data.typeName ?? "System.Int32";
            //}
            //catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            //{
            //    throw new System.IO.InvalidDataException(
            //        string.Format("Max value can't be null. Element: {0}.", validator.Name));
            //}

            Type rangeType = Type.GetType(vldtr.data.TypeName);
            if (rangeType == null)
            {
                throw new System.IO.InvalidDataException(
                    string.Format("Unknown type: {0}. Element: {1}.", vldtr.data.TypeName, validator.Name));
            }

            var attribute = new RangeAttribute(rangeType, vldtr.data.min,vldtr.data.max);
            this.BindErrorMessageToAttribte(attribute, validator, defaultResourceType);

            return new RangeAttributeAdapter(metadata, context, attribute);
        }
 public static void Can_validate_valid_values_for_integers_using_type_and_strings_constructor()
 {
     var attribute = new RangeAttribute(typeof(int), "1", "3");
     AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid
     AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid
     AssertEx.DoesNotThrow(() => attribute.Validate(1, s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate("1", s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate(2, s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate("2", s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate(3, s_testValidationContext));
     AssertEx.DoesNotThrow(() => attribute.Validate("3", s_testValidationContext));
 }
        public void RangeAdapter_SetsErrorMessage()
        {
            RangeAttribute attribute = new RangeAttribute(0, 128);
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "Range");
            new RangeAdapter(metadata, new ControllerContext(), attribute);

            String actual = attribute.ErrorMessage;
            String expected = Validations.Range;

            Assert.Equal(expected, actual);
        }
Example #20
0
        public void RangeAdapter_SetsRangeErrorMessage()
        {
            DataAnnotations.RangeAttribute attribute = new DataAnnotations.RangeAttribute(0, 128);
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                                     .GetMetadataForProperty(null, typeof(AdaptersModel), "Range");

            new RangeAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.FieldMustBeInRange;
            String actual   = attribute.ErrorMessage;

            Assert.AreEqual(expected, actual);
        }
Example #21
0
        public static void Can_validate_valid_values_for_doubles_using_type_and_strings_constructor()
        {
            var attribute = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1"));

            AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext));         // null is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(1.0, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate((1.0).ToString("F1"), s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate(2.0, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate((2.0).ToString("F1"), s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate(3.0, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate((3.0).ToString("F1"), s_testValidationContext));
        }
Example #22
0
        public static void Can_validate_valid_values_for_integers_using_type_and_strings_constructor()
        {
            var attribute = new RangeAttribute(typeof(int), "1", "3");

            AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext));         // null is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext)); // empty string is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(1, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("1", s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate(2, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("2", s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate(3, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("3", s_testValidationContext));
        }
        /// <summary>
        /// Determines whether the specified value of the object is valid.
        /// </summary>
        /// <param name="value">The value of the object to validate.</param>
        /// <param name="validationContext">The validation context.</param>
        /// <returns>true if the specified value is valid; otherwise, false.</returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string nines = new string('9', Precision);
            string decimalNines = nines.Insert(Precision - scale, ".");
            double minMaxValue = double.Parse(decimalNines);
            
            RangeAttribute range = new RangeAttribute(-minMaxValue, minMaxValue);

            if (range.IsValid(value))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(range.ErrorMessage);
            }
        }
        private ValidationAttribute CopyAttribute(ValidationAttribute attribute)
        {
            ValidationAttribute result = null;

            if (attribute is RangeAttribute)
            {
                var attr = (RangeAttribute)attribute;
                result = new RangeAttribute((double)attr.Minimum, (double)attr.Maximum);
            }

            if (attribute is RegularExpressionAttribute)
            {
                var attr = (RegularExpressionAttribute)attribute;
                result = new RegularExpressionAttribute(attr.Pattern);
            }

            if (attribute is RequiredAttribute)
                result = new RequiredAttribute();

            if (attribute is StringLengthAttribute)
            {
                var attr = (StringLengthAttribute)attribute;
                result = new StringLengthAttribute(attr.MaximumLength)
                {
                    MinimumLength = attr.MinimumLength
                };
            }

            if (attribute is CompareAttribute)
            {
                var attr = (CompareAttribute)attribute;
                result = new CompareAttribute(attr.OtherProperty);
            }

            if (attribute is DataTypeAttribute)
            {
                var attr = (DataTypeAttribute)attribute;
                result = new DataTypeAttribute(attr.DataType);
            }

            if (result == null && attribute.GetType().GetInterfaces().Contains(typeof(ICloneable)))
                result = ((ICloneable)attribute).Clone() as ValidationAttribute;

            return result;
        }
Example #25
0
        public void testAddBookingWrongDistance()
        {
            var rangeCharge   = new System.ComponentModel.DataAnnotations.RangeAttribute(0, 100);
            var rangeDistance = new System.ComponentModel.DataAnnotations.RangeAttribute(0, 1000);


            Booking booking = new Booking
            {
                currentCharge    = 10,
                requiredDistance = 1500,
                plugType         = Plug.CCSCombo2Plug,
                start            = new DateTime(2020, 9, 7, 13, 0, 0),
                end = new DateTime(2020, 9, 7, 20, 0, 0)
            };

            Assert.IsTrue(rangeCharge.IsValid(booking.currentCharge));
            Assert.IsFalse(rangeDistance.IsValid(booking.requiredDistance));
        }
        private static IRangeFacet Create(RangeAttribute attribute, bool isDate, ISpecification holder) {
            if (attribute == null) {
                return null;
            }

            if (attribute.OperandType != typeof (int) && attribute.OperandType != typeof (double)) {
                Log.WarnFormat("Unsupported use of range attribute with explicit type on {0}", holder);
                return null;
            }

            var min = attribute.Minimum as IConvertible;
            var max = attribute.Maximum as IConvertible;

            if (min == null || max == null) {
                Log.WarnFormat("Min Max values must be IConvertible for Range on {0}", holder);
                return null;
            }

            return new RangeFacet(min, max, isDate, holder);
        }
Example #27
0
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            var adapter = new RangeAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("range", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(0m, rule.ValidationParameters["min"]);
            Assert.Equal(100m, rule.ValidationParameters["max"]);
            Assert.Equal(@"The field Length must be between 0 and 100.", rule.ErrorMessage);
        }
        public void ClientRulesWithRangeAttribute()
        {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length");
            var context = new ControllerContext();
            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            var adapter = new RangeAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules()
                .OrderBy(r => r.ValidationType)
                .ToArray();

            // Assert
            ModelClientValidationRule rule = Assert.Single(rules);
            Assert.Equal("range", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(0m, rule.ValidationParameters["min"]);
            Assert.Equal(100m, rule.ValidationParameters["max"]);
            Assert.Equal(@"The field Length must be between 0 and 100.", rule.ErrorMessage);
        }
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            var adapter = new RangeAttributeAdapter(attribute);
            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();
            var context = new ClientModelValidationContext(metadata, provider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("range", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(0m, rule.ValidationParameters["min"]);
            Assert.Equal(100m, rule.ValidationParameters["max"]);
            Assert.Equal(@"The field Length must be between 0 and 100.", rule.ErrorMessage);
        }
Example #30
0
        public static void Validation_throws_InvalidOperationException_if_minimum_is_greater_than_maximum()
        {
            var attribute = new RangeAttribute(3, 1);

            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext));

            attribute = new RangeAttribute(3.0, 1.0);
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext));

            attribute = new RangeAttribute(typeof(int), "3", "1");
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext));

            attribute = new RangeAttribute(typeof(double), "3.0", "1.0");
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext));

            attribute = new RangeAttribute(typeof(string), "z", "a");
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - minimum > maximum", s_testValidationContext));
        }
 //: this(attribute)
 /// <summary>
 /// Initializes a new instance of the <see cref="TypePropertyValidationRuleMetadata" /> class.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 public TypePropertyValidationRuleMetadata(RangeAttribute attribute)
 {
     this.Name = "range";
     this.Value1 = attribute.Minimum;
     this.Value2 = attribute.Maximum;
     this.type = "array";
 }
 public RangeValidatorAttribute(Type type, string minimum, string maximum)
 {
     rangeAttribute = new RangeAttribute(type, minimum, maximum);
 }
 public RangeValidatorAttribute(double minimum, double maximum)
 {
     rangeAttribute = new RangeAttribute(minimum, maximum);
 }
 public RangeValidatorAttribute(int minimum, int maximum)
 {
     rangeAttribute = new RangeAttribute(minimum, maximum);
 }
        public void CreateWithRangeAttributeRequestReturnsCorrectResult(Type type, object minimum, object maximum)
        {
            // Fixture setup
            var rangeAttribute = new RangeAttribute(type, minimum.ToString(), maximum.ToString());
            var providedAttribute = new ProvidedAttribute(rangeAttribute, true);
            ICustomAttributeProvider request = new FakeCustomAttributeProvider(providedAttribute);
            Type conversionType = rangeAttribute.OperandType;
            var expectedRequest = new RangedNumberRequest(
                conversionType,
                Convert.ChangeType(rangeAttribute.Minimum, conversionType, CultureInfo.CurrentCulture),
                Convert.ChangeType(rangeAttribute.Maximum, conversionType, CultureInfo.CurrentCulture)
                );
            var expectedResult = new object();
            var context = new DelegatingSpecimenContext
            {
#pragma warning disable 618
                OnResolve = r => expectedRequest.Equals(r) ? expectedResult : new NoSpecimen(r)
#pragma warning restore 618
            };
            var sut = new RangeAttributeRelay();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
            Assert.Equal(expectedResult, result);
            // Teardown
        }
Example #36
0
        public void testAddBooking()
        {
            var range          = new System.ComponentModel.DataAnnotations.RangeAttribute(0, 100);
            var dateValidation = new DateAttribute();

            // Alle Attribute richtig
            Booking b1 = new Booking {
                currentCharge    = 30,
                requiredDistance = 150,
                connectorType    = ConnectorType.CCSCombo2Plug,
                start            = new DateTime(2020, 7, 8, 8, 0, 0),
                end = new DateTime(2020, 7, 8, 10, 0, 0)
            };

            Assert.IsTrue(range.IsValid(b1.currentCharge));
            Assert.IsTrue(b1.requiredDistance > 0 && b1.requiredDistance <= 1000);
            Assert.IsTrue(dateValidation.IsValid(b1.start));
            Assert.IsTrue(dateValidation.IsValid(b1.end));
            Assert.IsTrue(b1.end > b1.start);

            // currentCharge ungültig
            Booking b2 = new Booking
            {
                currentCharge    = -30,
                requiredDistance = 150,
                connectorType    = ConnectorType.CCSCombo2Plug,
                start            = new DateTime(2020, 7, 8, 8, 0, 0),
                end = new DateTime(2020, 7, 8, 10, 0, 0)
            };

            Assert.IsFalse(range.IsValid(b2.currentCharge));
            Assert.IsTrue(b2.requiredDistance > 0 && b2.requiredDistance <= 1000);
            Assert.IsTrue(dateValidation.IsValid(b2.start));
            Assert.IsTrue(dateValidation.IsValid(b2.end));
            Assert.IsTrue(b2.end > b2.start);

            // requiredDistance ungültig
            Booking b3 = new Booking
            {
                currentCharge    = 30,
                requiredDistance = -150,
                connectorType    = ConnectorType.CCSCombo2Plug,
                start            = new DateTime(2020, 7, 8, 8, 0, 0),
                end = new DateTime(2020, 7, 8, 10, 0, 0)
            };

            Assert.IsTrue(range.IsValid(b3.currentCharge));
            Assert.IsFalse(b3.requiredDistance > 0 && b3.requiredDistance <= 1000);
            Assert.IsTrue(dateValidation.IsValid(b3.start));
            Assert.IsTrue(dateValidation.IsValid(b3.end));
            Assert.IsTrue(b3.end > b3.start);

            // start ungültig
            Booking b4 = new Booking
            {
                currentCharge    = 30,
                requiredDistance = 150,
                connectorType    = ConnectorType.CCSCombo2Plug,
                start            = new DateTime(2020, 5, 5, 8, 0, 0),
                end = new DateTime(2020, 7, 8, 10, 0, 0)
            };

            Assert.IsTrue(range.IsValid(b4.currentCharge));
            Assert.IsTrue(b4.requiredDistance > 0 && b4.requiredDistance <= 1000);
            Assert.IsFalse(dateValidation.IsValid(b4.start));
            Assert.IsTrue(dateValidation.IsValid(b4.end));
            Assert.IsTrue(b4.end > b4.start);

            // end ungültig
            Booking b5 = new Booking
            {
                currentCharge    = 30,
                requiredDistance = 150,
                connectorType    = ConnectorType.CCSCombo2Plug,
                start            = new DateTime(2020, 7, 8, 8, 0, 0),
                end = new DateTime(2020, 7, 7, 10, 0, 0)
            };

            Assert.IsTrue(range.IsValid(b5.currentCharge));
            Assert.IsTrue(b5.requiredDistance > 0 && b3.requiredDistance <= 1000);
            Assert.IsTrue(dateValidation.IsValid(b5.start));
            Assert.IsTrue(dateValidation.IsValid(b5.end));
            Assert.IsFalse(b5.end > b5.start);
        }