コード例 #1
0
        public StringLengthAttributeAdapter(
            ModelMetadata metadata,
            ControllerContext context,
            StringLengthAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (string.IsNullOrWhiteSpace(Attribute.ErrorMessage))
            {
                if (Attribute.ErrorMessageResourceType == null)
                {
                    Attribute.ErrorMessageResourceType = typeof(Resources);
                }

                if (string.IsNullOrWhiteSpace(Attribute.ErrorMessageResourceName))
                {
                    if (Attribute.MinimumLength == 0)
                    {
                        Attribute.ErrorMessageResourceName = "PropertyMaxStringLength";
                    }
                    else
                    {
                        Attribute.ErrorMessageResourceName = "PropertyMinMaxStringLength";
                    }
                }
            }
        }
コード例 #2
0
        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(8);
            attribute.ErrorMessage = "Property must not be longer than '{1}' characters.";

            var expectedMessage = "Property must not be longer than '8' characters.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            var expectedProperties = new object[] { "Length", 0, 8 };

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

            var adapter = new StringLengthAttributeAdapter(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("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal(expectedMessage, rule.ErrorMessage);
        }
コード例 #3
0
 public static void Validation_throws_ValidationException_for_invalid_strings()
 {
     var attribute = new StringLengthAttribute(12);
     Assert.Throws<ValidationException>(() => attribute.Validate("Invalid string", s_testValidationContext)); // string too long
     attribute.MinimumLength = 8;
     Assert.Throws<ValidationException>(() => attribute.Validate("Invalid", s_testValidationContext)); // string too short
 }
コード例 #4
0
 public static void Validation_throws_InvalidOperationException_for_maximum_less_than_zero()
 {
     var attribute = new StringLengthAttribute(-1);
     Assert.Equal(-1, attribute.MaximumLength);
     Assert.Throws<InvalidOperationException>(
         () => attribute.Validate("Does not matter - MaximumLength < 0", s_testValidationContext));
 }
コード例 #5
0
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(10) { MinimumLength = 3 };
            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null);

            var expectedMessage = attribute.FormatErrorMessage("Length");

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

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-length", "original");
            context.Attributes.Add("data-val-length-max", "original");
            context.Attributes.Add("data-val-length-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-length", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-length-min", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
コード例 #6
0
 public static void ValidationThrowsIf_minimum_is_greater_than_maximum()
 {
     var attribute = new StringLengthAttribute(42);
     attribute.MinimumLength = 43;
     Assert.Throws<InvalidOperationException>(
         () => attribute.Validate("Does not matter - MinimumLength > MaximumLength", s_testValidationContext));
 }
コード例 #7
0
        public static StringFieldOptions Create(TextFieldAttribute textFieldAttribute, StringLengthAttribute stringLengthAttr, RichTextAttribute richTextAttr)
        {
            var result = new StringFieldOptions();
            if (textFieldAttribute != null)
            {
                result.Mask = textFieldAttribute.Mask;
                result.MaskType = textFieldAttribute.MaskType;
                result.NumberOfCharacters = textFieldAttribute.NumberOfCharacters;
                result.NumberOfRows = textFieldAttribute.NumberOfRows;
            }

            if (stringLengthAttr == null)
            {
                result.MinimumLength = 0;
                result.MinimumLength = 999999999;
            }
            else
            {
                result.MaximumLength = stringLengthAttr.MaximumLength;
                result.MinimumLength = stringLengthAttr.MinimumLength;
                result.ErrorMessage = stringLengthAttr.ErrorMessage;
            }

            if (richTextAttr != null)
            {
                result.IsRichText = true;
            }

            return result;
        }
コード例 #8
0
		/// <summary>
		/// 获取错误消息
		/// </summary>
		private string ErrorMessage(FormField field, StringLengthAttribute attribute) {
			if (attribute.MaximumLength == attribute.MinimumLength) {
				return string.Format(new T("Length of {0} must be {1}"),
					new T(field.Attribute.Name), attribute.MinimumLength);
			}
			return string.Format(new T("Length of {0} must between {1} and {2}"),
				new T(field.Attribute.Name), attribute.MinimumLength, attribute.MaximumLength);
		}
コード例 #9
0
 public StringLengthAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (Attribute.MinimumLength == 0)
         Attribute.ErrorMessage = Validations.StringLength;
     else
         Attribute.ErrorMessage = Validations.StringLengthRange;
 }
コード例 #10
0
 public StringLengthAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (Attribute.MinimumLength == 0)
         Attribute.ErrorMessage = Validations.FieldMustNotExceedLength;
     else
         Attribute.ErrorMessage = Validations.FieldMustBeInRangeOfLength;
 }
コード例 #11
0
        public static void ValidationThrowsIf_minimum_is_greater_than_maximum()
        {
            var attribute = new StringLengthAttribute(42);

            attribute.MinimumLength = 43;
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - MinimumLength > MaximumLength", s_testValidationContext));
        }
コード例 #12
0
        public static void Validation_throws_ValidationException_for_invalid_strings()
        {
            var attribute = new StringLengthAttribute(12);

            Assert.Throws <ValidationException>(() => attribute.Validate("Invalid string", s_testValidationContext)); // string too long
            attribute.MinimumLength = 8;
            Assert.Throws <ValidationException>(() => attribute.Validate("Invalid", s_testValidationContext));        // string too short
        }
コード例 #13
0
        public static void Validation_throws_InvalidOperationException_for_maximum_less_than_zero()
        {
            var attribute = new StringLengthAttribute(-1);

            Assert.Equal(-1, attribute.MaximumLength);
            Assert.Throws <InvalidOperationException>(
                () => attribute.Validate("Does not matter - MaximumLength < 0", s_testValidationContext));
        }
コード例 #14
0
 /// <summary>
 /// Creates the validator.
 /// </summary>
 /// <param name="modelMetadata">The model metadata.</param>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 protected override ModelValidator CreateValidatorCore(ExtendedModelMetadata modelMetadata, ControllerContext context)
 {
     var attribute = new StringLengthAttribute(Maximum)
                         {
                             MinimumLength = Minimum
                         };
     PopulateErrorMessage(attribute);
     return new StringLengthAttributeAdapter(modelMetadata, context, attribute);
 }
コード例 #15
0
        public LocalizedStringLengthAttribute(StringLengthAttribute attribute, Localizer t)
            : base(attribute.MaximumLength) {
            if ( !String.IsNullOrEmpty(attribute.ErrorMessage) )
                ErrorMessage = attribute.ErrorMessage;

            MinimumLength = attribute.MinimumLength;

            T = t;
        }
コード例 #16
0
        public static string GetStringLengthErrorMessage(int? minimumLength, int maximumLength, string field)
        {
            var attr = new StringLengthAttribute(maximumLength);
            if (minimumLength != null)
            {
                attr.MinimumLength = (int)minimumLength;
            }

            return attr.FormatErrorMessage(field);
        }
コード例 #17
0
        public static void Validation_successful_for_valid_strings()
        {
            var attribute = new StringLengthAttribute(12);
            AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid string", s_testValidationContext));

            attribute.MinimumLength = 5;
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid", s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid string", s_testValidationContext));
        }
コード例 #18
0
        public void StringLengthAdapter_SetsRangeErrorMessage()
        {
            StringLengthAttribute attribute = new StringLengthAttribute(128) { MinimumLength = 4 };
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "StringLength");
            new StringLengthAdapter(metadata, new ControllerContext(), attribute);

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

            Assert.Equal(expected, actual);
        }
コード例 #19
0
        public static void Validation_successful_for_valid_strings()
        {
            var attribute = new StringLengthAttribute(12);

            AssertEx.DoesNotThrow(() => attribute.Validate(null, s_testValidationContext)); // null is valid
            AssertEx.DoesNotThrow(() => attribute.Validate(string.Empty, s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid string", s_testValidationContext));

            attribute.MinimumLength = 5;
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid", s_testValidationContext));
            AssertEx.DoesNotThrow(() => attribute.Validate("Valid string", s_testValidationContext));
        }
コード例 #20
0
 public CustomStringLengthAttribute(
     System.Web.Mvc.ModelMetadata metadata,
     ControllerContext context,
     StringLengthAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage))
     {
         attribute.ErrorMessageResourceType = typeof(DefaultResource);
         attribute.ErrorMessageResourceName = "StringLength";
     }
 }
コード例 #21
0
 public TypePropertyValidationRuleMetadata(StringLengthAttribute attribute)
     : this((ValidationAttribute) attribute)
 {
     if (attribute.MinimumLength != 0) {
         Name = "rangelength";
         Value1 = attribute.MinimumLength;
         Value2 = attribute.MaximumLength;
         _type = "array";
     }
     else {
         Name = "maxlength";
         Value1 = attribute.MaximumLength;
         _type = "number";
     }
 }
コード例 #22
0
        public StringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (!string.IsNullOrWhiteSpace(Attribute.ErrorMessage)) return;

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

            if (string.IsNullOrWhiteSpace(Attribute.ErrorMessageResourceName))
            {
                Attribute.ErrorMessageResourceName = "PropertyValueStringLength";
            }
        }
コード例 #23
0
        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

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

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal("The field Length must be a string with a maximum length of 8.",
                         rule.ErrorMessage);
        }
コード例 #24
0
        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(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("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
コード例 #25
0
        public void ClientRulesWithStringLengthAttribute() {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length");
            var context = new ControllerContext();
            var attribute = new StringLengthAttribute(10);
            var adapter = new StringLengthAttributeAdapter(metadata, context, attribute);

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

            // Assert
            Assert.AreEqual(1, rules.Length);

            Assert.AreEqual("stringLength", rules[0].ValidationType);
            Assert.AreEqual(2, rules[0].ValidationParameters.Count);
            Assert.AreEqual(0, rules[0].ValidationParameters["minimumLength"]);
            Assert.AreEqual(10, rules[0].ValidationParameters["maximumLength"]);
            Assert.AreEqual(@"The field Length must be a string with a maximum length of 10.", rules[0].ErrorMessage);
        }
コード例 #26
0
ファイル: StringLengthRule.cs プロジェクト: volodin/DataPress
        public override ModelValidator Create(IStorageValidator validator, Type defaultResourceType, ModelMetadata metadata, ControllerContext context)
        {
            StorageValidator<int> vldtr = validator as StorageValidator<int>;
            if (vldtr == null)
                throw new System.IO.InvalidDataException(
                    "Validator value must be of type StorageValidator<int>.");

            //int maxLength = -1;
            //try
            //{
            //    maxLength = validator.data.maxLenght;
            //}
            //catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            //{
            //    throw new System.IO.InvalidDataException(
            //        string.Format("The maximum string length was not set. Element: {0}", validator.Name));
            //}

            var attribute = new StringLengthAttribute(vldtr.data);
            this.BindErrorMessageToAttribte(attribute, validator, defaultResourceType);

            return new StringLengthAttributeAdapter(metadata, context, attribute);
        }
コード例 #27
0
        public void GetClientValidationRules_WithMinAndMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(10) { MinimumLength = 3 };
            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null);

            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("length", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(3, rule.ValidationParameters["min"]);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
コード例 #28
0
        public void AddValidation_WithMaxLength_AddsAttributes()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null);

            var expectedMessage = attribute.FormatErrorMessage("Length");

            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-length", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("8", kvp.Value); });
        }
コード例 #29
0
        public void CreateWithConstrainedStringRequestReturnsCorrectResult(int maximum)
        {
            // Fixture setup
            var stringLengthAttribute = new StringLengthAttribute(maximum);
            var providedAttribute = new ProvidedAttribute(stringLengthAttribute, true);
            ICustomAttributeProvider request = new FakeCustomAttributeProvider(providedAttribute);
            var expectedRequest = new ConstrainedStringRequest(stringLengthAttribute.MaximumLength);
            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 StringLengthAttributeRelay();
            // Exercise system
            var result = sut.Create(request, context);
            // Verify outcome
            Assert.Equal(expectedResult, result);
            // Teardown
        }
コード例 #30
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="property"></param>
        public Column(PropertyInfo property, DataBaseType dbType)
        {
            if (property == null)
            {
                NotMapped = true;
                return;
            }
            Type type = property.PropertyType;

            if (type.IsClass && !type.FullName.StartsWith("System.", StringComparison.OrdinalIgnoreCase))
            {
                if (property.GetAccessors()[0].IsVirtual)
                {   //外键
                    IsForeginKey = true;
                }
                else
                {
                    NotMapped = true;
                    return;
                }
            }
            Property = property;

            object[] attrs = property.GetCustomAttributes(false);
            if (attrs.Length > 0)
            {
                foreach (object attr in attrs)
                {
                    if (attr is System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute)
                    {
                        NotMapped = true;
                        break;
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.KeyAttribute)
                    {
                        PrimaryKey = true;
                        NotNull    = true;
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute)
                    {
                        System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute generated = (System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute)attr;
                        if (generated.DatabaseGeneratedOption == System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)
                        {
                            AutoID = true;
                        }
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.RequiredAttribute)
                    {
                        NotNull = true;
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.StringLengthAttribute)
                    {
                        System.ComponentModel.DataAnnotations.StringLengthAttribute length = (System.ComponentModel.DataAnnotations.StringLengthAttribute)attr;
                        StringLenth = length.MaximumLength;
                    }
                    else if (attr is NumberRangeAttribute)
                    {
                        NumberRangeAttribute numberRange = (NumberRangeAttribute)attr;
                        IntergerLength = numberRange.Interger;
                        PointLength    = numberRange.Point;
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute)
                    {   //指定字段外键
                        dynamic foreignKey = (System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute)attr;

                        if (IsForeginKey)
                        {
                            Column fkCol = Tool.GetForeginKeyColmn(type, dbType, foreignKey.Name);
                            if (fkCol != null)
                            {
                                if (!string.IsNullOrWhiteSpace(foreignKey.Name))
                                {
                                    Column c = Tool.GetForeginKeyColmn(property.DeclaringType, dbType, foreignKey.Name);
                                    if (c != null)
                                    {
                                        Property = c.Property;
                                    }
                                    ColName = Tool.GetDbColName(foreignKey.Name, dbType);
                                    ColType = fkCol.ColType;
                                    FK      = $"references {type.Name}({fkCol.ColName})";
                                }
                                else
                                {
                                    Property = fkCol.Property;
                                    ColName  = $"{type.Name}_{fkCol.Name}";
                                    ColType  = fkCol.ColType;
                                    FK       = $"references {type.Name}({fkCol.ColName})";
                                }
                            }
                            else
                            {
                                NotMapped = true;
                            }
                        }
                        return;
                    }
                    else if (attr is System.ComponentModel.DataAnnotations.Schema.ColumnAttribute)
                    {
                        customColumn = (System.ComponentModel.DataAnnotations.Schema.ColumnAttribute)attr;
                    }
                }
            }

            if (IsForeginKey && string.IsNullOrWhiteSpace(FK))
            {   //匹配字段外键
                Column fkCol = Tool.GetForeginKeyColmn(type, dbType, null);
                if (fkCol != null)
                {
                    Property = fkCol.Property;
                    ColName  = $"{type.Name}_{fkCol.Name}";
                    ColType  = fkCol.ColType;
                    FK       = $"references {type.Name}({fkCol.ColName})";
                }
                else
                {
                    NotMapped = true;
                }
                return;
            }

            if (NotMapped)
            {
                return;
            }

            ColName = null;
            if (!string.IsNullOrEmpty(customColumn?.Name))
            {
                ColName = Tool.GetDbColName(customColumn.Name, dbType);
            }
            else
            {
                ColName = Tool.GetDbColName(property.Name, dbType);
            }

            if (!string.IsNullOrEmpty(customColumn?.TypeName))
            {
                ColType = customColumn.TypeName;
                return;
            }

            if (type == typeof(string))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    if (StringLenth != -1)
                    {
                        ColType = $"NVARCHAR({StringLenth})";
                    }
                    else
                    {
                        ColType = "TEXT";
                    }
                }
            }
            else if (type == typeof(int) || type == typeof(uint))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    if (AutoID)
                    {
                        ColType = "INTEGER";
                    }
                    else
                    {
                        ColType = "INT";
                    }
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(long))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType  = "INTEGER";
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(DateTime))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType = "DATETIME";
                }
            }
            else if (type == typeof(double))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType  = "DOUBLE";
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(float))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType  = "FLOAT";
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(byte))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType  = "TINYINT";
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(short) || type == typeof(ushort))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType  = "SMALLINT";
                    ColType += GetNumberLength();
                }
            }
            else if (type == typeof(bool))
            {
                if (dbType == DataBaseType.Sqlite)
                {
                    ColType = "BOOLEAN";
                }
            }

            if (!type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)))
            {
                NotNull = false;
            }
            else
            {
                NotNull = true;
            }
        }
コード例 #31
0
 protected void HandleStringLengthAttribute(TagBuilder tb, StringLengthAttribute stringLengthAttribute)
 {
     tb.MergeAttribute("data-val-maxlength-max", stringLengthAttribute.MaximumLength.ToString());
       tb.MergeAttribute("maxlength", stringLengthAttribute.MaximumLength.ToString());
 }
コード例 #32
0
 //: this(attribute)
 /// <summary>
 /// Initializes a new instance of the <see cref="TypePropertyValidationRuleMetadata" /> class.
 /// </summary>
 /// <param name="attribute">The attribute.</param>
 public TypePropertyValidationRuleMetadata(StringLengthAttribute attribute)
 {
     if (attribute.MinimumLength != 0)
     {
         this.Name = "rangelength";
         this.Value1 = attribute.MinimumLength;
         this.Value2 = attribute.MaximumLength;
         this.type = "array";
         return;
     }
     this.Name = "maxlength";
     this.Value1 = attribute.MaximumLength;
     this.type = "number";
 }
コード例 #33
0
        public static void ValidationThrowsIf_value_passed_is_non_null_non_string()
        {
            var attribute = new StringLengthAttribute(42);

            Assert.Throws <InvalidCastException>(() => attribute.Validate(new object(), s_testValidationContext));
        }
コード例 #34
0
        /// <summary>A Type extension method that gets model definition.</summary>
        /// <param name="modelType">The modelType to act on.</param>
        /// <returns>The model definition.</returns>
        public static ModelDefinition GetModelDefinition(this Type modelType)
        {
            ModelDefinition modelDef;

            if (typeModelDefinitionMap.TryGetValue(modelType, out modelDef))
                return modelDef;

            if (modelType.IsValueType() || modelType == typeof(string))
                return null;

            var modelAliasAttr = modelType.FirstAttribute<AliasAttribute>();
            var schemaAttr = modelType.FirstAttribute<SchemaAttribute>();
            modelDef = new ModelDefinition {
                ModelType = modelType,
                Name = modelType.Name,
                Alias = modelAliasAttr != null ? modelAliasAttr.Name : null,
                Schema = schemaAttr != null ? schemaAttr.Name : null
            };

            modelDef.CompositeIndexes.AddRange(
                modelType.GetCustomAttributes(typeof(CompositeIndexAttribute), true).ToList()
                .ConvertAll(x => (CompositeIndexAttribute)x));

            var objProperties = modelType.GetProperties(
                BindingFlags.Public | BindingFlags.Instance).ToList();

            var hasIdField = CheckForIdField(objProperties);

            var i = 0;
            foreach (var propertyInfo in objProperties)
            {
                var sequenceAttr = propertyInfo.FirstAttribute<SequenceAttribute>();
                var computeAttr= propertyInfo.FirstAttribute<ComputeAttribute>();
                var pkAttribute = propertyInfo.FirstAttribute<PrimaryKeyAttribute>();
                var decimalAttribute = propertyInfo.FirstAttribute<DecimalLengthAttribute>();
                var belongToAttribute = propertyInfo.FirstAttribute<BelongToAttribute>();
                var isFirst = i++ == 0;

                var isPrimaryKey = propertyInfo.Name == OrmLiteConfig.IdField || (!hasIdField && isFirst)
                    || pkAttribute != null;

                var isNullableType = IsNullableType(propertyInfo.PropertyType);

                var isNullable = (!propertyInfo.PropertyType.IsValueType
                                   && propertyInfo.FirstAttribute<RequiredAttribute>() == null)
                                 || isNullableType;

                var propertyType = isNullableType
                    ? Nullable.GetUnderlyingType(propertyInfo.PropertyType)
                    : propertyInfo.PropertyType;

                var aliasAttr = propertyInfo.FirstAttribute<AliasAttribute>();

                var indexAttr = propertyInfo.FirstAttribute<IndexAttribute>();
                var isIndex = indexAttr != null;
                var isUnique = isIndex && indexAttr.Unique;

                var stringLengthAttr = propertyInfo.FirstAttribute<StringLengthAttribute>();

                var defaultValueAttr = propertyInfo.FirstAttribute<DefaultAttribute>();

                var referencesAttr = propertyInfo.FirstAttribute<ReferencesAttribute>();
                var foreignKeyAttr = propertyInfo.FirstAttribute<ForeignKeyAttribute>();

                if (decimalAttribute != null && stringLengthAttr == null)
                    stringLengthAttr = new StringLengthAttribute(decimalAttribute.Precision);

                var fieldDefinition = new FieldDefinition {
                    Name = propertyInfo.Name,
                    Alias = aliasAttr != null ? aliasAttr.Name : null,
                    FieldType = propertyType,
                    PropertyInfo = propertyInfo,
                    IsNullable = isNullable,
                    IsPrimaryKey = isPrimaryKey,
                    AutoIncrement =
                        isPrimaryKey &&
                        propertyInfo.FirstAttribute<AutoIncrementAttribute>() != null,
                    IsIndexed = isIndex,
                    IsUnique = isUnique,
                    FieldLength =
                        stringLengthAttr != null
                            ? stringLengthAttr.MaximumLength
                            : (int?)null,
                    DefaultValue =
                        defaultValueAttr != null ? defaultValueAttr.DefaultValue : null,
                    ForeignKey =
                        foreignKeyAttr == null
                            ? referencesAttr == null
                                  ? null
                                  : new ForeignKeyConstraint(referencesAttr.Type)
                            : new ForeignKeyConstraint(foreignKeyAttr.Type,
                                                       foreignKeyAttr.OnDelete,
                                                       foreignKeyAttr.OnUpdate,
                                                       foreignKeyAttr.ForeignKeyName),
                    GetValueFn = propertyInfo.GetPropertyGetterFn(),
                    SetValueFn = propertyInfo.GetPropertySetterFn(),
                    Sequence = sequenceAttr != null ? sequenceAttr.Name : string.Empty,
                    IsComputed = computeAttr != null,
                    ComputeExpression =
                        computeAttr != null ? computeAttr.Expression : string.Empty,
                    Scale = decimalAttribute != null ? decimalAttribute.Scale : (int?)null,
                    BelongToModelName = belongToAttribute != null ? belongToAttribute.BelongToTableType.GetModelDefinition().ModelName : null, 
                };

                if (propertyInfo.FirstAttribute<IgnoreAttribute>() != null)
                  modelDef.IgnoredFieldDefinitions.Add(fieldDefinition);
                else
                  modelDef.FieldDefinitions.Add(fieldDefinition);                
            }

            modelDef.SqlSelectAllFromTable = "SELECT {0} FROM {1} ".Fmt(OrmLiteConfig.DialectProvider.GetColumnNames(modelDef),
                                                                        OrmLiteConfig.DialectProvider.GetQuotedTableName(
                                                                            modelDef));
            Dictionary<Type, ModelDefinition> snapshot, newCache;
            do
            {
                snapshot = typeModelDefinitionMap;
                newCache = new Dictionary<Type, ModelDefinition>(typeModelDefinitionMap);
                newCache[modelType] = modelDef;

            } while (!ReferenceEquals(
                Interlocked.CompareExchange(ref typeModelDefinitionMap, newCache, snapshot), snapshot));

            return modelDef;
        }
コード例 #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedStringLengthAttributeAdapter"/> class.
        /// </summary>
        /// <param name="metadata">The model metadata.</param>
        /// <param name="context">The controller context.</param>
        /// <param name="attribute">The <see cref="StringLengthAttribute"/> attribute.</param>
        public LocalizedStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute) : base(metadata, context, attribute)
        {

        }
        public void Setup()
        {
            var attribute1 = new StringLengthAttribute(5);
            attribute1.ErrorMessage = "length";
            var attribute2 = new RegularExpressionAttribute("a*");
            attribute2.ErrorMessage = "regex";

            this.validator = new ValidationAttributeValidator(attribute1, attribute2);
        }