i18N localized version of System.ComponentModel.DataAnnotations.RequiredAttribute class.

Specifies that a data field value is required.

Inheritance: System.ComponentModel.DataAnnotations.RequiredAttribute
Exemplo n.º 1
0
 public void RequiredNotThereTest()
 {
     RequiredAttribute attribute = new RequiredAttribute();
     ValidationErrorCollection errors = new ValidationErrorCollection();
     attribute.Validate(requiredNode, valueInfo1, errors);
     Assert.AreEqual(1, errors.Count);
 }
Exemplo n.º 2
0
 public void RequiredNotThereTest()
 {
     RequiredAttribute attribute = new RequiredAttribute();
     List<ValidationError> errors = new List<ValidationError>();
     attribute.Validate(requiredNode, valueInfo1, errors, ServiceProvider);
     Assert.AreEqual(1, errors.Count);
 }
Exemplo n.º 3
0
 public void RequiredValueTest()
 {
     RequiredAttribute attribute = new RequiredAttribute();
     requiredNode.Value2 = "MyTest";
     List<ValidationError> errors = new List<ValidationError>();
     attribute.Validate(requiredNode, valueInfo2, errors, ServiceProvider);
     Assert.AreEqual(0, ValidationAttributeHelper.GetValidationErrorsCount(serviceProvider));
 }
Exemplo n.º 4
0
 public void RequiredValueTest()
 {
     RequiredAttribute attribute = new RequiredAttribute();
     requiredNode.Value2 = "MyTest";
     ValidationErrorCollection errors = new ValidationErrorCollection();
     attribute.Validate(requiredNode, valueInfo2, errors);
     Assert.AreEqual(0, ValidationErrorsCount);
 }
Exemplo n.º 5
0
 public static void AllowEmptyStrings_GetSet_ReturnsExpectected()
 {
     var attribute = new RequiredAttribute();
     Assert.False(attribute.AllowEmptyStrings);
     attribute.AllowEmptyStrings = true;
     Assert.True(attribute.AllowEmptyStrings);
     attribute.AllowEmptyStrings = false;
     Assert.False(attribute.AllowEmptyStrings);
 }
        public void IsValid_AllowEmptyStrings() {
            RequiredAttribute attribute = new RequiredAttribute() { AllowEmptyStrings = true };

            Assert.IsTrue(attribute.IsValid(String.Empty));
            Assert.IsTrue(attribute.IsValid(1));
            Assert.IsTrue(attribute.IsValid("abc"));
            Assert.IsTrue(attribute.IsValid("   "));
            Assert.IsTrue(attribute.IsValid("\t"));

            Assert.IsFalse(attribute.IsValid(null));
        }
        public void IsValid() {
            RequiredAttribute required = new RequiredAttribute();

            Assert.AreEqual(true, required.IsValid("abcd"));
            Assert.AreEqual(true, required.IsValid("  ab  "));
            Assert.AreEqual(true, required.IsValid(10));

            Assert.AreEqual(false, required.IsValid(""));
            Assert.AreEqual(false, required.IsValid("   "));
            Assert.AreEqual(false, required.IsValid("\t"));
            Assert.AreEqual(false, required.IsValid(null));
        }
Exemplo n.º 8
0
        private void CreateComboboxControl(NameAttribute displayNameAttribute, RequiredAttribute requiredAttribute, ConfigEditorAttribute editorTypeAttribute, Binding b)
        {
            var dropDownControl = new ConfigComboBoxControl();
            dropDownControl.ConfigItemDisplayName = _localController.GetLocalString(displayNameAttribute.LocalType, displayNameAttribute.DisplayName);
            dropDownControl.SourceList = (ComboBoxList)Activator.CreateInstance(editorTypeAttribute.SourceListType);
            dropDownControl.SetBinding(ConfigComboBoxControl.SelectedValueProperty, b);
            dropDownControl.WaterMarkText = requiredAttribute != null ? _localController.GetLocalStrings<SDGuiStrings>().Mandatory : _localController.GetLocalStrings<SDGuiStrings>().Optional;
            dropDownControl.WaterMarkColor = requiredAttribute != null ? (SolidColorBrush)TryFindResource("Color_FadedRed") : (SolidColorBrush)TryFindResource("Color_FadedGray");

            configItemPanel.Children.Add(dropDownControl);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Enregistre les domaines.
        /// </summary>
        /// <param name="domainMetadataType">Type de la classe portant les métadonnées des domaines.</param>
        /// <returns>Liste des domaines créés.</returns>
        public ICollection <IDomain> RegisterDomainMetadataType(Type domainMetadataType)
        {
            if (domainMetadataType == null)
            {
                throw new ArgumentNullException("domainMetadataType");
            }

            List <IDomain> list = new List <IDomain>();

            foreach (PropertyInfo property in domainMetadataType.GetProperties())
            {
                object[] attrDomainArray = property.GetCustomAttributes(typeof(DomainAttribute), false);
                if (attrDomainArray.Length > 0)
                {
                    DomainAttribute domainAttr = (DomainAttribute)attrDomainArray[0];

                    List <ValidationAttribute> validationAttributes = new List <ValidationAttribute>();
                    object[] attrValidationArray = property.GetCustomAttributes(typeof(ValidationAttribute), false);
                    foreach (ValidationAttribute validationAttribute in attrValidationArray)
                    {
                        validationAttributes.Add(validationAttribute);
                        RequiredAttribute     requiredAttr = validationAttribute as RequiredAttribute;
                        StringLengthAttribute strLenAttr   = validationAttribute as StringLengthAttribute;
                        RangeAttribute        rangeAttr    = validationAttribute as RangeAttribute;
                        if (requiredAttr != null)
                        {
                            requiredAttr.ErrorMessageResourceName = "ConstraintNotNull";
                            requiredAttr.ErrorMessageResourceType = typeof(SR);
                        }
                        else if (strLenAttr != null)
                        {
                            strLenAttr.ErrorMessageResourceName = "ErrorConstraintStringLength";
                            strLenAttr.ErrorMessageResourceType = typeof(SR);
                        }
                        else if (rangeAttr != null)
                        {
                            rangeAttr.ErrorMessageResourceName = "ConstraintIntervalBornes";
                            rangeAttr.ErrorMessageResourceType = typeof(SR);
                        }
                    }

                    TypeConverter formatter          = null;
                    object[]      attrConverterArray = property.GetCustomAttributes(typeof(CustomTypeConverterAttribute), false);
                    if (attrConverterArray.Length > 0)
                    {
                        CustomTypeConverterAttribute converterAttribute = (CustomTypeConverterAttribute)attrConverterArray[0];
                        Type converterType = Type.GetType(converterAttribute.ConverterTypeName, false);
                        if (converterType == null)
                        {
                            string simpleTypeName = converterAttribute.ConverterTypeName.Split(',').First();
                            converterType = domainMetadataType.Assembly.GetType(simpleTypeName);
                        }

                        formatter = (TypeConverter)Activator.CreateInstance(converterType);
                        IFormatter iFormatter = (IFormatter)formatter;
                        if (!string.IsNullOrEmpty(converterAttribute.FormatString))
                        {
                            iFormatter.FormatString = converterAttribute.FormatString;
                        }

                        if (!string.IsNullOrEmpty(converterAttribute.Unit))
                        {
                            iFormatter.Unit = converterAttribute.Unit;
                        }
                    }

                    List <Attribute> decorationAttributes = new List <Attribute>();
                    foreach (object attribute in property.GetCustomAttributes(false))
                    {
                        if (attribute is DomainAttribute || attribute is TypeConverterAttribute || attribute is ValidationAttribute)
                        {
                            continue;
                        }

                        Attribute extraAttribute = attribute as Attribute;
                        decorationAttributes.Add(extraAttribute);
                    }

                    IDomainChecker domain = (IDomainChecker)Activator.CreateInstance(
                        typeof(Domain <>).MakeGenericType(property.PropertyType),
                        domainAttr.Name,
                        validationAttributes,
                        formatter,
                        decorationAttributes,
                        false,
                        domainAttr.ErrorMessageResourceType,
                        domainAttr.ErrorMessageResourceName,
                        domainAttr.MetadataPropertySuffix);

                    this.RegisterDomain(domain);
                    list.Add(domain);
                }
            }

            return(list);
        }
Exemplo n.º 10
0
 protected void HandleRequiredAttribute(TagBuilder tb, RequiredAttribute requiredAttribute)
 {
     tb.AddCssClass("required");
     tb.MergeAttribute("data-val-required", string.Empty);
 }
Exemplo n.º 11
0
        /// <summary>
        /// 验证必须输入
        /// </summary>
        /// <param name="box">验证框</param>
        /// <returns></returns>
        public static ValidBox Required(this ValidBox box)
        {
            var newBox = new RequiredAttribute().ToValidBox();

            return(ValidBox.Merge(box, newBox));
        }
        private static string WriteExtenders(PropertyInfo p, out bool isValidatable)
        {
            isValidatable = false;
            StringBuilder sb = new StringBuilder();

            sb.Append(".extend({ editState : false, disableValidation : false, empty : true })");

            RequiredAttribute requiredAttribute = p.GetCustomAttribute <RequiredAttribute>();

            if (requiredAttribute != null)
            {
                sb.Append(".extend({ required: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })".FormatString(requiredAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            MinLengthAttribute minLengthAttribute = p.GetCustomAttribute <MinLengthAttribute>();

            if (minLengthAttribute != null)
            {
                sb.Append(".extend({ minLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(minLengthAttribute.FormatErrorMessage(p.Name), minLengthAttribute.Length, p.Name));
                isValidatable = true;
            }

            MaxLengthAttribute maxLengthAttribute = p.GetCustomAttribute <MaxLengthAttribute>();

            if (maxLengthAttribute != null)
            {
                sb.Append(".extend({ maxLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(maxLengthAttribute.FormatErrorMessage(p.Name), maxLengthAttribute.Length, p.Name));
                isValidatable = true;
            }

            RegularExpressionAttribute regularExpressionAttribute = p.GetCustomAttribute <RegularExpressionAttribute>();

            if (regularExpressionAttribute != null)
            {
                sb.Append(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(regularExpressionAttribute.FormatErrorMessage(p.Name), regularExpressionAttribute.Pattern, p.Name));
                isValidatable = true;
            }

            UrlAttribute urlAttribute = p.GetCustomAttribute <UrlAttribute>();

            if (urlAttribute != null)
            {
                sb.Append(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(urlAttribute.FormatErrorMessage(p.Name), urlAttribute.Regex, p.Name));
                isValidatable = true;
            }

            DateAttribute dateAttribute = p.GetCustomAttribute <DateAttribute>();

            if (dateAttribute != null)
            {
                sb.Append(".extend({ date: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })".FormatString(dateAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            NumericAttribute numericAttribute = p.GetCustomAttribute <NumericAttribute>();

            if (numericAttribute != null)
            {
                sb.Append(
                    ".extend({ number: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: {2} })".FormatString(
                        numericAttribute.FormatErrorMessage(p.Name), p.Name, numericAttribute.Precision));
                isValidatable = true;
            }

            EmailAttribute emailAttribute = p.GetCustomAttribute <EmailAttribute>();

            if (emailAttribute != null)
            {
                sb.Append(".extend({ email: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })".FormatString(emailAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            DigitsAttribute digitsAttribute = p.GetCustomAttribute <DigitsAttribute>();

            if (digitsAttribute != null)
            {
                sb.Append(".extend({ digit: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: 0 })".FormatString(digitsAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            MinAttribute minAttribute = p.GetCustomAttribute <MinAttribute>();

            if (minAttribute != null)
            {
                sb.Append(".extend({ min: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(minAttribute.FormatErrorMessage(p.Name), minAttribute.Min, p.Name));
                isValidatable = true;
            }

            MaxAttribute maxAttribute = p.GetCustomAttribute <MaxAttribute>();

            if (maxAttribute != null)
            {
                sb.Append(".extend({ max: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(maxAttribute.FormatErrorMessage(p.Name), maxAttribute.Max, p.Name));
                isValidatable = true;
            }

            EqualToAttribute equalToAttribute = p.GetCustomAttribute <EqualToAttribute>();

            if (equalToAttribute != null)
            {
                sb.Append(".extend({ equal: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(equalToAttribute.FormatErrorMessage(p.Name), equalToAttribute.OtherProperty, p.Name));
                isValidatable = true;
            }

            CompareAttribute compareAttribute = p.GetCustomAttribute <CompareAttribute>();

            if (compareAttribute != null)
            {
                sb.Append(".extend({ equal: { message: \"{0}\", params: \"{1}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })".FormatString(compareAttribute.FormatErrorMessage(p.Name), compareAttribute.OtherProperty, p.Name));
                isValidatable = true;
            }

            FormatterAttribute formatterAttribute = p.GetCustomAttribute <FormatterAttribute>();

            if (formatterAttribute != null)
            {
                IJsonSerializer serializer = Container.Get <IJsonSerializer>();
                sb.Append(".formatted({0}, {1})".FormatString(formatterAttribute.Formatter, serializer.Serialize(formatterAttribute.Arguments)));
            }

            return(sb.ToString());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Parse metadata given a binding path and entity object.
        /// </summary>
        /// <param name="bindingPath">The bindingPath is the name of the property on the entity from which to pull metadata from.  This supports dot notation.</param>
        /// <param name="entity">The entity object from which to pull metadata from.</param>
        /// <returns>The validation metadata associated with the entity and binding path.  This will return null if none exists.</returns>
        internal static ValidationMetadata ParseMetadata(string bindingPath, object entity)
        {
            if (entity != null && !String.IsNullOrEmpty(bindingPath))
            {
                Type         entityType = entity.GetType();
                PropertyInfo prop       = GetProperty(entityType, bindingPath);
                if (prop != null)
                {
                    ValidationMetadata newVMD     = new ValidationMetadata();
                    object[]           attributes = prop.GetCustomAttributes(false);
                    foreach (object propertyAttribute in attributes)
                    {
                        // Loop through each attribute and update the VMD as appropriate

                        // RequiredField
#if NETSTANDARD
                        RequiredAttribute reqAttribute = propertyAttribute as RequiredAttribute;
                        if (reqAttribute != null)
                        {
                            newVMD.IsRequired = true;
                            continue;
                        }
#else // BRIDGE
                        Type attrType = propertyAttribute.GetType();
                        if (attrType.Name == "RequiredAttribute" &&
                            attrType.Namespace == "System.ComponentModel.DataAnnotations")
                        {
                            newVMD.IsRequired = true;
                            continue;
                        }
#endif

                        // Display attribute parsing
#if NETSTANDARD
                        DisplayAttribute displayAttribute = propertyAttribute as DisplayAttribute;
                        if (displayAttribute != null)
                        {
                            newVMD.Description = displayAttribute.GetDescription();
                            newVMD.Caption     = displayAttribute.GetName();
                            continue;
                        }
#else // BRIDGE
                        attrType = propertyAttribute.GetType();
                        if (attrType.Name == "DisplayAttribute" &&
                            attrType.Namespace == "System.ComponentModel.DataAnnotations")
                        {
                            newVMD.Description = (string)attrType.GetMethod("GetDescription",
                                                                            BindingFlags.Public | BindingFlags.Instance)
                                                 .Invoke(propertyAttribute, new object[0]);
                            newVMD.Caption = (string)attrType.GetMethod("GetName",
                                                                        BindingFlags.Public | BindingFlags.Instance)
                                             .Invoke(propertyAttribute, new object[0]);
                            continue;
                        }
#endif
                    }
                    if (newVMD.Caption == null)
                    {
                        // If the name is not defined via the DisplayAttribute, use the property name.
                        newVMD.Caption = prop.Name;

                        // Caption can be set to empty string to have an empty Caption and not default
                        // to the property name.
                    }

                    return(newVMD);
                }
            }
            return(null);
        }
Exemplo n.º 14
0
 public RequiredAttributeRewriter(RequiredAttribute requiredAttribute)
 {
     this.attribute = requiredAttribute;
 }
 public static bool IsRequired(PropertyInfo propertyInfo)
 {
     return(RequiredAttribute.IsDefined(propertyInfo, typeof(RequiredAttribute)));
 }
Exemplo n.º 16
0
    protected void gvCategories_RowValidating(object sender, ASPxDataValidationEventArgs e)
    {
        try
        {
            // Checks for null values.
            foreach (GridViewColumn column in gvCategories.Columns)
            {
                if (column is GridViewDataColumn)
                {
                    GridViewDataColumn dataColumn = column as GridViewDataColumn;
                    if (dataColumn.Visible)
                    {
                        //Validations in model
                        StringLengthAttribute strLenAttr   = Utils.GetLengthAttribute(typeof(Category), dataColumn.FieldName);
                        RequiredAttribute     requiredAttr = Utils.GetRequiredAttribute(typeof(Category), dataColumn.FieldName);

                        if (requiredAttr != null)
                        {
                            if (e.NewValues[dataColumn.FieldName] == null)
                            {
                                e.Errors[dataColumn] = requiredAttr.ErrorMessage;
                            }
                            else
                            {
                                if (strLenAttr != null)
                                {
                                    int maxLen = strLenAttr.MaximumLength;
                                    int minLen = strLenAttr.MinimumLength;

                                    if (e.NewValues[dataColumn.FieldName].ToString().Length > maxLen || e.NewValues[dataColumn.FieldName].ToString().Length < minLen)
                                    {
                                        e.Errors[dataColumn] = strLenAttr.ErrorMessage;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Displays the error row if there is at least one error.
            if (e.Errors.Count > 0)
            {
                if (e.IsNewRow)
                {
                    e.RowError = "Error al crear el registro";
                }
                else
                {
                    e.RowError = "Error al actualizar el registro";
                }
                return;
            }
        }
        catch (Exception)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Respuesta", string.Format("alert('{0}');", "Error. Por favor intente más tarde"), true);
        }


        //CtrlCategories ctrlCategories = new CtrlCategories();
        //List<Category> categoryList = ctrlCategories.GetAllCategories();

        //if (e.IsNewRow)
        //{
        //    string name = e.NewValues["name"].ToString();
        //    if (categoryList.FindAll(c => (c.name.ToUpperInvariant().Equals(name.ToUpperInvariant()))).Count > 0)
        //    {
        //        e.RowError = "Error al crear el registro, ya existe una categoría con el mismo Nombre";
        //    }
        //}
        //else
        //{
        //    int id = ((Category)((DevExpress.Web.ASPxGridView)sender).GetRow(e.VisibleIndex)).id;
        //    string name = e.NewValues["name"].ToString();
        //    if (categoryList.FindAll(c => (c.name.ToUpperInvariant().Equals(name.ToUpperInvariant())) && (c.id != id)).Count > 0)
        //    {
        //        e.RowError = "Error al actualizar el registro, ya existe una categoría con el mismo Nombre";
        //    }
        //}

        //if (e.NewValues["ContactName"] != null &&
        //    e.NewValues["ContactName"].ToString().Length < 2)
        //{
        //    AddError(e.Errors, gvCategories.Columns["ContactName"],
        //    "Contact Name must be at least two characters long.");
        //}
        //if (e.NewValues["CompanyName"] != null &&
        //e.NewValues["CompanyName"].ToString().Length < 2)
        //{
        //    AddError(e.Errors, gvCategories.Columns["CompanyName"],
        //    "Company Name must be at least two characters long.");
        //}
        //if (string.IsNullOrEmpty(e.RowError) && e.Errors.Count > 0)
        //    e.RowError = "Please, correct all errors.";
    }
Exemplo n.º 17
0
 private static object[] GetArgs(RequiredAttribute attribute)
 {
     return(new object[] { });
 }
        /// <inheritdoc />
        public void CreateValidationMetadata(ValidationMetadataProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Read interface .Count once rather than per iteration
            var contextAttributes      = context.Attributes;
            var contextAttributesCount = contextAttributes.Count;
            var attributes             = new List <object>(contextAttributesCount);

            for (var i = 0; i < contextAttributesCount; i++)
            {
                var attribute = contextAttributes[i];
                if (attribute is ValidationProviderAttribute validationProviderAttribute)
                {
                    attributes.AddRange(validationProviderAttribute.GetValidationAttributes());
                }
                else
                {
                    attributes.Add(attribute);
                }
            }

            // RequiredAttribute marks a property as required by validation - this means that it
            // must have a non-null value on the model during validation.
            var requiredAttribute = attributes.OfType <RequiredAttribute>().FirstOrDefault();

            // For non-nullable reference types, treat them as-if they had an implicit [Required].
            // This allows the developer to specify [Required] to customize the error message, so
            // if they already have [Required] then there's no need for us to do this check.
            if (!_options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes &&
                requiredAttribute == null &&
                !context.Key.ModelType.IsValueType &&
                context.Key.MetadataKind != ModelMetadataKind.Type)
            {
                var addInferredRequiredAttribute = false;
                if (context.Key.MetadataKind == ModelMetadataKind.Type)
                {
                    // Do nothing.
                }
                else if (context.Key.MetadataKind == ModelMetadataKind.Property)
                {
                    addInferredRequiredAttribute = IsNullableReferenceType(
                        context.Key.ContainerType,
                        member: null,
                        context.PropertyAttributes);
                }
                else if (context.Key.MetadataKind == ModelMetadataKind.Parameter)
                {
                    addInferredRequiredAttribute = IsNullableReferenceType(
                        context.Key.ParameterInfo?.Member.ReflectedType,
                        context.Key.ParameterInfo.Member,
                        context.ParameterAttributes);
                }
                else
                {
                    throw new InvalidOperationException("Unsupported ModelMetadataKind: " + context.Key.MetadataKind);
                }

                if (addInferredRequiredAttribute)
                {
                    // Since this behavior specifically relates to non-null-ness, we will use the non-default
                    // option to tolerate empty/whitespace strings. empty/whitespace INPUT will still result in
                    // a validation error by default because we convert empty/whitespace strings to null
                    // unless you say otherwise.
                    requiredAttribute = new RequiredAttribute()
                    {
                        AllowEmptyStrings = true,
                    };
                    attributes.Add(requiredAttribute);
                }
            }

            if (requiredAttribute != null)
            {
                context.ValidationMetadata.IsRequired = true;
            }

            foreach (var attribute in attributes.OfType <ValidationAttribute>())
            {
                // If another provider has already added this attribute, do not repeat it.
                // This will prevent attributes like RemoteAttribute (which implement ValidationAttribute and
                // IClientModelValidator) to be added to the ValidationMetadata twice.
                // This is to ensure we do not end up with duplication validation rules on the client side.
                if (!context.ValidationMetadata.ValidatorMetadata.Contains(attribute))
                {
                    context.ValidationMetadata.ValidatorMetadata.Add(attribute);
                }
            }
        }
Exemplo n.º 19
0
 public RequiredAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
     Attribute.ErrorMessage = Validations.Required;
 }
Exemplo n.º 20
0
        public void DefaultErrorMessage()
        {
            RequiredAttribute required = new RequiredAttribute();

            Assert.AreEqual(String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.RequiredAttribute_ValidationError, "SOME_NAME"), required.FormatErrorMessage("SOME_NAME"));
        }
Exemplo n.º 21
0
 public WeeeRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage) &&
         !string.IsNullOrEmpty(metadata.DisplayName))
     {
         attribute.ErrorMessage = string.Format("Enter {0}", metadata.DisplayName.ToLower());
     }
 }
Exemplo n.º 22
0
        private static TagBuilder TextBoxTagFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, bool readOnly = false, bool required = false)
        {
            TagBuilder       tag  = null;
            ModelMetadata    meta = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            MemberExpression body = expression.Body as MemberExpression;

            if (body != null)
            {
                RequiredAttribute requiredAttribute = (body.Member.GetCustomAttributes(typeof(RequiredAttribute), false)).FirstOrDefault() as RequiredAttribute;
                required = required || requiredAttribute != null;

                var value = GetModelValue(meta);

                tag = TextBoxTag(html, meta.DisplayName, meta.PropertyName, meta.PropertyName,
                                 new ViewModels.FieldProperties {
                    ReadOnly = readOnly, Required = required, Value = value
                });

                MaxLengthAttribute maxLengthAttribute = (body.Member.GetCustomAttributes(typeof(MaxLengthAttribute), false)).FirstOrDefault() as MaxLengthAttribute;
                if (maxLengthAttribute != null)
                {
                    tag.Attributes.Add("data-rule-maxlength", maxLengthAttribute.Length.ToString());
                }

                MinLengthAttribute minLengthAttribute = (body.Member.GetCustomAttributes(typeof(MinLengthAttribute), false)).FirstOrDefault() as MinLengthAttribute;
                if (minLengthAttribute != null)
                {
                    tag.Attributes.Add("data-rule-minlength", minLengthAttribute.Length.ToString());
                }

                RangeAttribute rangeAttribute = (body.Member.GetCustomAttributes(typeof(RangeAttribute), false)).FirstOrDefault() as RangeAttribute;
                if (rangeAttribute != null)
                {
                    tag.Attributes.Add("data-rule-range", "[" + rangeAttribute.Minimum + "," + rangeAttribute.Maximum + "]");
                }

                EmailAddressAttribute email = (body.Member.GetCustomAttributes(typeof(EmailAddressAttribute), false)).FirstOrDefault() as EmailAddressAttribute;
                if (email != null)
                {
                    tag.Attributes.Add("data-rule-email", "true");
                }

                UrlAttribute url = (body.Member.GetCustomAttributes(typeof(UrlAttribute), false)).FirstOrDefault() as UrlAttribute;
                if (url != null)
                {
                    tag.Attributes.Add("data-rule-url", "true");
                }

                System.ComponentModel.DataAnnotations.CompareAttribute compare =
                    (body.Member.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.CompareAttribute), false))
                    .FirstOrDefault() as System.ComponentModel.DataAnnotations.CompareAttribute;
                if (compare != null)
                {
                    tag.Attributes.Add("data-rule-equalTo", "#" + compare.OtherProperty.ToLower());
                }


                var type = meta.ModelType;
                if (type == typeof(int) || type == typeof(float) || type == typeof(long) || type == typeof(byte) ||
                    type == typeof(short) || type == typeof(decimal) || type == typeof(double) ||
                    type == typeof(int?) || type == typeof(float?) || type == typeof(long?) || type == typeof(byte?) ||
                    type == typeof(short?) || type == typeof(decimal?) || type == typeof(double?))
                {
                    if (!tag.Attributes.ContainsKey("value"))
                    {
                        tag.Attributes.Add("value", "");
                    }
                    tag.Attributes.Add("data-rule-number", "true");
                }
            }
            return(tag);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="InfrastructureRequiredAttributeAdapter" /> class.
 /// </summary>
 /// <param name="metadata">The model metadata.</param>
 /// <param name="context">The controller context.</param>
 /// <param name="attribute">The attribute.</param>
 public InfrastructureRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) : base(metadata, context, attribute) { }
            public TypePropertyMetadata(PropertyDescriptor descriptor)
            {
                Name = descriptor.Name;

                Type elementType = TypeUtility.GetElementType(descriptor.PropertyType);

                IsArray = !elementType.Equals(descriptor.PropertyType);
                // TODO: What should we do with nullable types here?
                TypeName      = elementType.Name;
                TypeNamespace = elementType.Namespace;

                AttributeCollection propertyAttributes = TypeDescriptorExtensions.ExplicitAttributes(descriptor);

                // TODO, 336102, ReadOnlyAttribute for editability?  RIA used EditableAttribute?
                ReadOnlyAttribute readonlyAttr = (ReadOnlyAttribute)propertyAttributes[typeof(ReadOnlyAttribute)];

                IsReadOnly = (readonlyAttr != null) ? readonlyAttr.IsReadOnly : false;

                AssociationAttribute associationAttr = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)];

                if (associationAttr != null)
                {
                    Association = new TypePropertyAssociationMetadata(associationAttr);
                }

                RequiredAttribute requiredAttribute = (RequiredAttribute)propertyAttributes[typeof(RequiredAttribute)];

                if (requiredAttribute != null)
                {
                    _validationRules.Add(new TypePropertyValidationRuleMetadata(requiredAttribute));
                }

                RangeAttribute rangeAttribute = (RangeAttribute)propertyAttributes[typeof(RangeAttribute)];

                if (rangeAttribute != null)
                {
                    Type operandType = rangeAttribute.OperandType;
                    operandType = Nullable.GetUnderlyingType(operandType) ?? operandType;
                    if (operandType.Equals(typeof(Double)) ||
                        operandType.Equals(typeof(Int16)) ||
                        operandType.Equals(typeof(Int32)) ||
                        operandType.Equals(typeof(Int64)) ||
                        operandType.Equals(typeof(Single)))
                    {
                        _validationRules.Add(new TypePropertyValidationRuleMetadata(rangeAttribute));
                    }
                }

                StringLengthAttribute stringLengthAttribute = (StringLengthAttribute)propertyAttributes[typeof(StringLengthAttribute)];

                if (stringLengthAttribute != null)
                {
                    _validationRules.Add(new TypePropertyValidationRuleMetadata(stringLengthAttribute));
                }

                DataTypeAttribute dataTypeAttribute = (DataTypeAttribute)propertyAttributes[typeof(DataTypeAttribute)];

                if (dataTypeAttribute != null)
                {
                    if (dataTypeAttribute.DataType.Equals(DataType.EmailAddress) ||
                        dataTypeAttribute.DataType.Equals(DataType.Url))
                    {
                        _validationRules.Add(new TypePropertyValidationRuleMetadata(dataTypeAttribute));
                    }
                }
            }
Exemplo n.º 25
0
    protected void gvProducts_RowValidating(object sender, ASPxDataValidationEventArgs e)
    {
        try
        {
            // Checks for null values.
            foreach (GridViewColumn column in gvProducts.Columns)
            {
                if (column is GridViewDataColumn)
                {
                    GridViewDataColumn dataColumn = column as GridViewDataColumn;
                    if (dataColumn.Visible)
                    {
                        //In editMode is not valid to change the ProductType
                        if ((dataColumn.FieldName.ToUpper() == "productTypeId".ToUpper()) && (!e.IsNewRow))
                        {
                            continue;
                        }

                        //Validations in model
                        StringLengthAttribute strLenAttr   = Utils.GetLengthAttribute(typeof(Product), dataColumn.FieldName);
                        RequiredAttribute     requiredAttr = Utils.GetRequiredAttribute(typeof(Product), dataColumn.FieldName);

                        bool isNewRow = e.IsNewRow;

                        if (requiredAttr != null)
                        {
                            if (e.NewValues[dataColumn.FieldName] == null)
                            {
                                e.Errors[dataColumn] = requiredAttr.ErrorMessage;
                            }
                            else
                            {
                                if (strLenAttr != null)
                                {
                                    int maxLen = strLenAttr.MaximumLength;
                                    int minLen = strLenAttr.MinimumLength;

                                    if (e.NewValues[dataColumn.FieldName].ToString().Length > maxLen || e.NewValues[dataColumn.FieldName].ToString().Length < minLen)
                                    {
                                        e.Errors[dataColumn] = strLenAttr.ErrorMessage;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Displays the error row if there is at least one error.
            if (e.Errors.Count > 0)
            {
                if (e.IsNewRow)
                {
                    e.RowError = "Error al crear el registro";
                }
                else
                {
                    e.RowError = "Error al actualizar el registro";
                }
                return;
            }
        }
        catch (Exception)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Respuesta", string.Format("alert('{0}');", "Error. Por favor intente más tarde"), true);
        }
    }
Exemplo n.º 26
0
 public RequiredIfAttribute(string dependentProperty, object targetValue)
 {
     _innerAttribute   = new RequiredAttribute();
     DependentProperty = dependentProperty;
     TargetValue       = targetValue;
 }
    /// <inheritdoc />
    public void CreateValidationMetadata(ValidationMetadataProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        // Read interface .Count once rather than per iteration
        var contextAttributes      = context.Attributes;
        var contextAttributesCount = contextAttributes.Count;
        var attributes             = new List <object>(contextAttributesCount);

        for (var i = 0; i < contextAttributesCount; i++)
        {
            var attribute = contextAttributes[i];
            if (attribute is ValidationProviderAttribute validationProviderAttribute)
            {
                attributes.AddRange(validationProviderAttribute.GetValidationAttributes());
            }
            else
            {
                attributes.Add(attribute);
            }
        }

        // RequiredAttribute marks a property as required by validation - this means that it
        // must have a non-null value on the model during validation.
        var requiredAttribute = attributes.OfType <RequiredAttribute>().FirstOrDefault();

        // For non-nullable reference types, treat them as-if they had an implicit [Required].
        // This allows the developer to specify [Required] to customize the error message, so
        // if they already have [Required] then there's no need for us to do this check.
        if (!_options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes &&
            requiredAttribute == null &&
            !context.Key.ModelType.IsValueType &&
            context.Key.MetadataKind != ModelMetadataKind.Type)
        {
            var addInferredRequiredAttribute = false;
            if (context.Key.MetadataKind == ModelMetadataKind.Type)
            {
                // Do nothing.
            }
            else if (context.Key.MetadataKind == ModelMetadataKind.Property)
            {
                var property = context.Key.PropertyInfo;
                if (property is null)
                {
                    // PropertyInfo was unavailable on ModelIdentity prior to 3.1.
                    // Making a cogent argument about the nullability of the property requires inspecting the declared type,
                    // since looking at the runtime type may result in false positives: https://github.com/dotnet/aspnetcore/issues/14812
                    // The only way we could arrive here is if the ModelMetadata was constructed using the non-default provider.
                    // We'll cursorily examine the attributes on the property, but not the ContainerType to make a decision about it's nullability.

                    if (HasNullableAttribute(context.PropertyAttributes !, out var propertyHasNullableAttribute))
                    {
                        addInferredRequiredAttribute = propertyHasNullableAttribute;
                    }
                }
                else
                {
                    addInferredRequiredAttribute = IsNullableReferenceType(
                        property.DeclaringType !,
                        member: null,
                        context.PropertyAttributes !);
                }
            }
            else if (context.Key.MetadataKind == ModelMetadataKind.Parameter)
            {
                // If the default value is assigned we don't need to check the nullabilty
                // since the parameter will be optional.
                if (!context.Key.ParameterInfo !.HasDefaultValue)
                {
                    addInferredRequiredAttribute = IsNullableReferenceType(
                        context.Key.ParameterInfo !.Member.ReflectedType,
                        context.Key.ParameterInfo.Member,
                        context.ParameterAttributes !);
                }
            }
            else
            {
                throw new InvalidOperationException("Unsupported ModelMetadataKind: " + context.Key.MetadataKind);
            }

            if (addInferredRequiredAttribute)
            {
                // Since this behavior specifically relates to non-null-ness, we will use the non-default
                // option to tolerate empty/whitespace strings. empty/whitespace INPUT will still result in
                // a validation error by default because we convert empty/whitespace strings to null
                // unless you say otherwise.
                requiredAttribute = new RequiredAttribute()
                {
                    AllowEmptyStrings = true,
                };
                attributes.Add(requiredAttribute);
            }
        }

        if (requiredAttribute != null)
        {
            context.ValidationMetadata.IsRequired = true;
        }

        foreach (var attribute in attributes.OfType <ValidationAttribute>())
        {
            // If another provider has already added this attribute, do not repeat it.
            // This will prevent attributes like RemoteAttribute (which implement ValidationAttribute and
            // IClientModelValidator) to be added to the ValidationMetadata twice.
            // This is to ensure we do not end up with duplication validation rules on the client side.
            if (!context.ValidationMetadata.ValidatorMetadata.Contains(attribute))
            {
                context.ValidationMetadata.ValidatorMetadata.Add(attribute);
            }
        }
    }
Exemplo n.º 28
0
        public void CheckNothingRequired()
        {
            var tag = new Scope();

            RequiredAttribute.Check(tag);
        }
        protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName)
        {
            List <Attribute>             attributeList          = new List <Attribute>(attributes);
            DisplayColumnAttribute       displayColumnAttribute = attributeList.OfType <DisplayColumnAttribute>().FirstOrDefault();
            DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute);

            // Do [HiddenInput] before [UIHint], so you can override the template hint
            HiddenInputAttribute hiddenInputAttribute = attributeList.OfType <HiddenInputAttribute>().FirstOrDefault();

            if (hiddenInputAttribute != null)
            {
                result.TemplateHint        = "HiddenInput";
                result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue;
            }

            // We prefer [UIHint("...", PresentationLayer = "MVC")] but will fall back to [UIHint("...")]
            IEnumerable <UIHintAttribute> uiHintAttributes = attributeList.OfType <UIHintAttribute>();
            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
                                              ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));

            if (uiHintAttribute != null)
            {
                result.TemplateHint = uiHintAttribute.UIHint;
            }

            DataTypeAttribute dataTypeAttribute = attributeList.OfType <DataTypeAttribute>().FirstOrDefault();

            if (dataTypeAttribute != null)
            {
                result.DataTypeName = dataTypeAttribute.ToDataTypeName();
            }

            EditableAttribute editable = attributes.OfType <EditableAttribute>().FirstOrDefault();

            if (editable != null)
            {
                result.IsReadOnly = !editable.AllowEdit;
            }
            else
            {
                ReadOnlyAttribute readOnlyAttribute = attributeList.OfType <ReadOnlyAttribute>().FirstOrDefault();
                if (readOnlyAttribute != null)
                {
                    result.IsReadOnly = readOnlyAttribute.IsReadOnly;
                }
            }

            DisplayFormatAttribute displayFormatAttribute = attributeList.OfType <DisplayFormatAttribute>().FirstOrDefault();

            if (displayFormatAttribute == null && dataTypeAttribute != null)
            {
                displayFormatAttribute = dataTypeAttribute.DisplayFormat;
            }
            if (displayFormatAttribute != null)
            {
                result.NullDisplayText          = displayFormatAttribute.NullDisplayText;
                result.DisplayFormatString      = displayFormatAttribute.DataFormatString;
                result.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull;

                if (displayFormatAttribute.ApplyFormatInEditMode)
                {
                    result.EditFormatString = displayFormatAttribute.DataFormatString;
                }

                if (!displayFormatAttribute.HtmlEncode && String.IsNullOrWhiteSpace(result.DataTypeName))
                {
                    result.DataTypeName = DataTypeUtil.HtmlTypeName;
                }
            }

            ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType <ScaffoldColumnAttribute>().FirstOrDefault();

            if (scaffoldColumnAttribute != null)
            {
                result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold;
            }

            DisplayAttribute display = attributes.OfType <DisplayAttribute>().FirstOrDefault();
            string           name    = null;

            if (display != null)
            {
                result.Description      = display.GetDescription();
                result.ShortDisplayName = display.GetShortName();
                result.Watermark        = display.GetPrompt();
                result.Order            = display.GetOrder() ?? ModelMetadata.DefaultOrder;

                name = display.GetName();
            }

            if (name != null)
            {
                result.DisplayName = name;
            }
            else
            {
                DisplayNameAttribute displayNameAttribute = attributeList.OfType <DisplayNameAttribute>().FirstOrDefault();
                if (displayNameAttribute != null)
                {
                    result.DisplayName = displayNameAttribute.DisplayName;
                }
            }

            RequiredAttribute requiredAttribute = attributeList.OfType <RequiredAttribute>().FirstOrDefault();

            if (requiredAttribute != null)
            {
                result.IsRequired = true;
            }

            return(result);
        }
Exemplo n.º 30
0
        private Control GetControl(PropertyInfo pi)
        {
            object[] attributes = pi.GetCustomAttributes(true);
            Control _Controls = new Control();

            //finding out control attribue
            int ControlAttributesCount = (from a in attributes where a.GetType().BaseType == typeof(ControlAttribute) || a.GetType().BaseType.BaseType == typeof(ControlAttribute) select a).Count();

            if (ControlAttributesCount == 0)
            {
                //adding default attributes
                ArrayList defaultAttributes = new ArrayList(attributes);
                TextBoxAttribute textbox = new TextBoxAttribute();
                defaultAttributes.Add(textbox);
                string controlName = pi.Name; //String.Format("{0}_TextBoxAttribute", pi.Name);

                RequiredAttribute vrAtt = new RequiredAttribute();
                defaultAttributes.Add(vrAtt);

                switch (pi.PropertyType.Name)
                {
                    case "Int32":
                        RegExpAttribute veAtt = new RegExpAttribute();
                        veAtt.ValidationExpression = @"\d";
                        defaultAttributes.Add(veAtt);
                        break;
                    case "String":
                        break;
                    default:
                        break;
                }
                attributes = defaultAttributes.ToArray();
            }

            foreach (Attribute att in attributes)
            {
                //checking validation
                bool isValidation = false;
                if (att.GetType().BaseType == typeof(ValidationAttribute))
                    isValidation = true;
                /* Begin Validation Controls Geneation */
                if (isValidation)
                {
                    //General Validator Control
                    string ControlType = att.GetType().GetProperty("ControlType").GetValue(att, null).ToString();
                    Control ValidationControl = (Control)System.Activator.CreateInstance(Type.GetType(ControlType));

                    //binding
                    BindAttributeFieldsToProperties(ValidationControl, att);

                    if (att.GetType() == typeof(CustomValidatorAttribute))
                    {
                        string ServerValidationEventName = GetFieldValue(att, "ServerValidationEventName").ToString();
                        ValidationControl.GetType().GetEvent(ServerValidationEventName).AddEventHandler(ValidationControl, new ServerValidateEventHandler(ServerValidation));
                    }
                    //Assigning ControlToValidate Property with the propertyName
                    string ControlToValidatePropertyName = GetFieldValue(att, "ControlToValidatePropertyName").ToString();
                    ValidationControl.GetType().GetProperty(ControlToValidatePropertyName).SetValue(ValidationControl, pi.Name, null);

                    //firing the event
                    OnValidationCreated(ValidationControl, new FieldEventArgs(pi.Name, pi.PropertyType));
                    _Controls.Controls.Add(ValidationControl);
                }
                /* Finish Validation Controls Geneation */
                else
                {   // generic control
                    PropertyInfo typePropertyInfo = att.GetType().GetProperty("ControlTypeName");
                    if (typePropertyInfo != null)
                    {
                        string typeName = typePropertyInfo.GetValue(att, null).ToString();
                        Control control = (Control)System.Activator.CreateInstance(Type.GetType(typeName));
                        control.ID = pi.Name;//+ "_" + att.GetType().Name;

                        //binding fields
                        BindAttributeFieldsToProperties(control, att);

                        string bindingPropertyName = att.GetType().GetProperty("BindingProperty").GetValue(att, null).ToString();
                        PropertyInfo controlBindingProperty = control.GetType().GetProperty(bindingPropertyName);
                        //DataControls
                        bool isDataControl = (bool)att.GetType().GetField("IsDataControl").GetValue(att);
                        if (isDataControl)
                        {
                            bool AutoPostBack = (bool)control.GetType().GetProperty("AutoPostBack").GetValue(control, null);
                            if (AutoPostBack)
                            {
                                string IndexChangeEventName = att.GetType().GetField("IndexChangeEventName").GetValue(att).ToString();
                                control.GetType().GetEvent(IndexChangeEventName).AddEventHandler(control, new EventHandler(LookupPostback));
                            }

                            //firing event
                            OnLookupControlCreated(control, new FieldEventArgs(pi.Name, pi.PropertyType));

                            //seting select value after event
                            if (Mode == Opertion.update)
                                controlBindingProperty.SetValue(control, Convert.ChangeType(pi.GetValue(DataSource, null), control.GetType().GetProperty(bindingPropertyName).PropertyType), null);

                            _Controls.Controls.Add(control);
                        }
                        else
                        {
                            //DirectBinding Property
                            controlBindingProperty.SetValue(control, Convert.ChangeType(pi.GetValue(DataSource, null), control.GetType().GetProperty(bindingPropertyName).PropertyType), null);

                            //firing the event
                            OnControlCreated(control, new FieldEventArgs(pi.Name, pi.PropertyType));
                            _Controls.Controls.Add(control);
                        }
                    }
                }
            }

            return _Controls;
        }
        private static JqGridColumnModel SetEditOptions(JqGridColumnModel columnModel, IUrlHelper urlHelper, Type modelType, JqGridColumnEditableAttribute jqGridColumnEditableAttribute, RangeAttribute rangeAttribute, RequiredAttribute requiredAttribute)
        {
            if (jqGridColumnEditableAttribute != null)
            {
                columnModel.DateFormat           = jqGridColumnEditableAttribute.DateFormat;
                columnModel.Editable             = jqGridColumnEditableAttribute.Editable;
                columnModel.EditOptions          = GetElementOptions(jqGridColumnEditableAttribute.EditOptions, urlHelper, jqGridColumnEditableAttribute);
                columnModel.EditOptions.PostData = jqGridColumnEditableAttribute.PostData;
                columnModel.EditRules            = GetRules(modelType, jqGridColumnEditableAttribute, rangeAttribute, requiredAttribute);
                columnModel.EditType             = jqGridColumnEditableAttribute.EditType;
                columnModel.FormOptions          = jqGridColumnEditableAttribute.FormOptions;
            }

            return(columnModel);
        }
Exemplo n.º 32
0
 private static void ApplyRequiredAttribute(OpenApiSchema schema, RequiredAttribute requiredAttribute)
 {
     schema.Nullable = false;
 }
 public void DefaultErrorMessage() {
     RequiredAttribute required = new RequiredAttribute();
     Assert.AreEqual(String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.RequiredAttribute_ValidationError, "SOME_NAME"), required.FormatErrorMessage("SOME_NAME"));
 }
        private static JqGridColumnRules GetRules(Type modelType, JqGridColumnElementAttribute jqGridColumnElementAttribute, RangeAttribute rangeAttribute, RequiredAttribute requiredAttribute)
        {
            JqGridColumnRules rules = jqGridColumnElementAttribute.Rules;

            if (rules != null)
            {
                if (requiredAttribute != null)
                {
                    rules.Required = true;
                }

                if (rangeAttribute != null)
                {
                    rules.MaxValue = Convert.ToDouble(rangeAttribute.Maximum);
                    rules.MinValue = Convert.ToDouble(rangeAttribute.Minimum);
                }

                if ((modelType == typeof(Int16)) || (modelType == typeof(Int32)) || (modelType == typeof(Int64)) || (modelType == typeof(UInt16)) || (modelType == typeof(UInt32)) || (modelType == typeof(UInt32)))
                {
                    rules.Integer = true;
                }
                else if ((modelType == typeof(Decimal)) || (modelType == typeof(Double)) || (modelType == typeof(Single)))
                {
                    rules.Number = true;
                }
            }

            return(rules);
        }
Exemplo n.º 35
0
        private void CreateTextboxControl(NameAttribute displayNameAttribute, RequiredAttribute requiredAttribute, Binding b)
        {
            var textItemControl = new ConfigTextControl();
            textItemControl.ConfigItemDisplayName = _localController.GetLocalString(displayNameAttribute.LocalType, displayNameAttribute.DisplayName);
            textItemControl.SetBinding(ConfigTextControl.ConfigItemValueProperty, b);
            textItemControl.WaterMarkText = requiredAttribute != null ? _localController.GetLocalStrings<SDGuiStrings>().Mandatory : _localController.GetLocalStrings<SDGuiStrings>().Optional;
            textItemControl.WaterMarkColor = requiredAttribute != null ? (SolidColorBrush)TryFindResource("Color_FadedRed") : (SolidColorBrush)TryFindResource("Color_FadedGray");

            configItemPanel.Children.Add(textItemControl);
        }
 private static IMandatoryFacet Create(RequiredAttribute attribute, ISpecification holder) => attribute != null ? new MandatoryFacet(holder) : null;
Exemplo n.º 37
0
        private void CreateFilesystemControl(NameAttribute displayNameAttribute, RequiredAttribute requiredAttribute, ConfigEditorAttribute editorTypeAttribute, Binding b)
        {
            var fileSystemControl = new ConfigFileSystemControl();
            fileSystemControl.ConfigItemDisplayName = _localController.GetLocalString(displayNameAttribute.LocalType, displayNameAttribute.DisplayName);
            fileSystemControl.SetBinding(ConfigFileSystemControl.ConfigItemValueProperty, b);
            fileSystemControl.WaterMarkText = requiredAttribute != null ? _localController.GetLocalStrings<SDGuiStrings>().Mandatory : _localController.GetLocalStrings<SDGuiStrings>().Optional;
            fileSystemControl.WaterMarkColor = requiredAttribute != null ? (SolidColorBrush)TryFindResource("Color_FadedRed") : (SolidColorBrush)TryFindResource("Color_FadedGray");
            fileSystemControl.IsFileSelector = editorTypeAttribute.Editor == EditorType.Filepicker;
            fileSystemControl.OpenFileFilter = editorTypeAttribute.OpenFileFilter;

            configItemPanel.Children.Add(fileSystemControl);
        }
 public RequiredValidator(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
 }
Exemplo n.º 39
0
        /// <summary>
        /// Loads all content from a folder hierarchy (overlaying anything already existing)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="path"></param>
        public static void Load(DocProject project, string path)
        {
            // get all files within folder hierarchy
            string pathSchema         = path + @"\schemas";
            IEnumerable <string> en   = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories);
            List <string>        list = new List <string>();

            foreach (string s in en)
            {
                list.Add(s);
            }
            string[] files = list.ToArray();

            Dictionary <string, string> options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };

            Microsoft.CSharp.CSharpCodeProvider        prov  = new Microsoft.CSharp.CSharpCodeProvider(options);
            System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters();
            parms.GenerateInMemory   = true;
            parms.GenerateExecutable = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Core.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");
            parms.ReferencedAssemblies.Add("System.Xml.dll");

            System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files);
            System.Reflection.Assembly assem = results.CompiledAssembly;

            // look through classes of assembly
            foreach (Type t in assem.GetTypes())
            {
                string[]   namespaceparts = t.Namespace.Split('.');
                string     schema         = namespaceparts[namespaceparts.Length - 1];
                DocSection docSection     = null;
                if (t.Namespace.EndsWith("Resource"))
                {
                    docSection = project.Sections[7];
                }
                else if (t.Namespace.EndsWith("Domain"))
                {
                    docSection = project.Sections[6];
                }
                else if (t.Namespace.Contains("Shared"))
                {
                    docSection = project.Sections[5];
                }
                else
                {
                    docSection = project.Sections[4]; // kernel, extensions
                }

                // find schema
                DocSchema docSchema = null;
                foreach (DocSchema docEachSchema in docSection.Schemas)
                {
                    if (docEachSchema.Name.Equals(schema))
                    {
                        docSchema = docEachSchema;
                        break;
                    }
                }

                if (docSchema == null)
                {
                    docSchema      = new DocSchema();
                    docSchema.Name = schema;
                    docSection.Schemas.Add(docSchema);
                    docSection.SortSchemas();
                }

                DocDefinition docDef = null;
                if (t.IsEnum)
                {
                    DocEnumeration docEnum = new DocEnumeration();
                    docSchema.Types.Add(docEnum);
                    docDef = docEnum;

                    System.Reflection.FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.FieldInfo field in fields)
                    {
                        DocConstant docConst = new DocConstant();
                        docEnum.Constants.Add(docConst);
                        docConst.Name = field.Name;

                        DescriptionAttribute[] attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (attrs.Length == 1)
                        {
                            docConst.Documentation = attrs[0].Description;
                        }
                    }
                }
                else if (t.IsValueType)
                {
                    DocDefined docDefined = new DocDefined();
                    docSchema.Types.Add(docDefined);
                    docDef = docDefined;

                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    docDefined.DefinedType = fields[0].PropertyType.Name;
                }
                else if (t.IsInterface)
                {
                    DocSelect docSelect = new DocSelect();
                    docSchema.Types.Add(docSelect);
                    docDef = docSelect;
                }
                else if (t.IsClass)
                {
                    DocEntity docEntity = new DocEntity();
                    docSchema.Entities.Add(docEntity);
                    docDef = docEntity;

                    if (t.BaseType != typeof(object))
                    {
                        docEntity.BaseDefinition = t.BaseType.Name;
                    }

                    if (!t.IsAbstract)
                    {
                        docEntity.EntityFlags = 0x20;
                    }

                    Dictionary <int, DocAttribute> attrsDirect  = new Dictionary <int, DocAttribute>();
                    List <DocAttribute>            attrsInverse = new List <DocAttribute>();
                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                    foreach (PropertyInfo field in fields)
                    {
                        DocAttribute docAttr = new DocAttribute();
                        docAttr.Name = field.Name.Substring(1);

                        Type typeField = field.PropertyType;
                        if (typeField.IsGenericType)
                        {
                            Type typeGeneric = typeField.GetGenericTypeDefinition();
                            typeField = typeField.GetGenericArguments()[0];
                            if (typeGeneric == typeof(Nullable <>))
                            {
                                docAttr.IsOptional = true;
                            }
                            else if (typeGeneric == typeof(ISet <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.SET;
                            }
                            else if (typeGeneric == typeof(IList <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.LIST;
                            }
                        }

                        docAttr.DefinedType = typeField.Name;


                        MinLengthAttribute mla = (MinLengthAttribute)field.GetCustomAttribute(typeof(MinLengthAttribute));
                        if (mla != null)
                        {
                            docAttr.AggregationLower = mla.Length.ToString();
                        }

                        MaxLengthAttribute mxa = (MaxLengthAttribute)field.GetCustomAttribute(typeof(MaxLengthAttribute));
                        if (mxa != null)
                        {
                            docAttr.AggregationUpper = mxa.Length.ToString();
                        }

                        PropertyInfo propinfo = t.GetProperty(docAttr.Name);
                        if (propinfo != null)
                        {
                            DescriptionAttribute da = (DescriptionAttribute)propinfo.GetCustomAttribute(typeof(DescriptionAttribute));
                            if (da != null)
                            {
                                docAttr.Documentation = da.Description;
                            }
                        }

                        DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute));
                        if (dma != null)
                        {
                            attrsDirect.Add(dma.Order, docAttr);

                            RequiredAttribute rqa = (RequiredAttribute)field.GetCustomAttribute(typeof(RequiredAttribute));
                            if (rqa == null)
                            {
                                docAttr.IsOptional = true;
                            }

                            CustomValidationAttribute cva = (CustomValidationAttribute)field.GetCustomAttribute(typeof(CustomValidationAttribute));
                            if (cva != null)
                            {
                                docAttr.IsUnique = true;
                            }
                        }
                        else
                        {
                            InversePropertyAttribute ipa = (InversePropertyAttribute)field.GetCustomAttribute(typeof(InversePropertyAttribute));
                            if (ipa != null)
                            {
                                docAttr.Inverse = ipa.Property;
                                attrsInverse.Add(docAttr);
                            }
                        }

                        // xml
                        XmlIgnoreAttribute xia = (XmlIgnoreAttribute)field.GetCustomAttribute(typeof(XmlIgnoreAttribute));
                        if (xia != null)
                        {
                            docAttr.XsdFormat = DocXsdFormatEnum.Hidden;
                        }
                        else
                        {
                            XmlElementAttribute xea = (XmlElementAttribute)field.GetCustomAttribute(typeof(XmlElementAttribute));
                            if (xea != null)
                            {
                                if (!String.IsNullOrEmpty(xea.ElementName))
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Element;
                                }
                                else
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Attribute;
                                }
                            }
                        }
                    }

                    foreach (DocAttribute docAttr in attrsDirect.Values)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    foreach (DocAttribute docAttr in attrsInverse)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    // get derived attributes based on properties
                    PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
                    foreach (PropertyInfo prop in props)
                    {
                        // if no backing field, then derived
                        FieldInfo field = t.GetField("_" + prop.Name, BindingFlags.NonPublic | BindingFlags.Instance);
                        if (field == null)
                        {
                            DocAttribute docDerived = new DocAttribute();
                            docDerived.Name = prop.Name;
                            docEntity.Attributes.Add(docDerived);
                        }
                    }
                }

                if (docDef != null)
                {
                    docDef.Name = t.Name;
                    docDef.Uuid = t.GUID;
                }

                docSchema.SortTypes();
                docSchema.SortEntities();
            }

            // pass 2: hook up selects
            foreach (Type t in assem.GetTypes())
            {
                Type[] typeInterfaces = t.GetInterfaces();
                if (typeInterfaces.Length > 0)
                {
                    foreach (Type typeI in typeInterfaces)
                    {
                        DocSelect docSelect = project.GetDefinition(typeI.Name) as DocSelect;
                        if (docSelect != null)
                        {
                            DocSelectItem docItem = new DocSelectItem();
                            docItem.Name = t.Name;
                            docSelect.Selects.Add(docItem);
                        }
                    }
                }
            }

            // EXPRESS rules (eventually in C#, though .exp file snippets for now)
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                string expr = null;
                using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8))
                {
                    expr = readExpr.ReadToEnd();
                }

                if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocWhereRule docWhere = new DocWhereRule();
                        docWhere.Name       = parts[1];
                        docWhere.Expression = expr;

                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef == null)
                        {
                            //... global rule...
                        }
                    }
                }
                else
                {
                    // function
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetDirectoryName(schema);
                    schema = Path.GetFileName(schema);
                    DocSchema docSchema = project.GetSchema(schema);
                    if (docSchema != null)
                    {
                        DocFunction docFunction = new DocFunction();
                        docSchema.Functions.Add(docFunction);
                        docFunction.Name       = name;
                        docFunction.Expression = expr;
                    }
                }
            }

            // now, hook up html documentation
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string    name   = Path.GetFileNameWithoutExtension(file);
                DocObject docObj = null;
                if (name == "schema")
                {
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetFileName(schema);
                    docObj = project.GetSchema(schema);
                }
                else if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    docObj = project.GetDefinition(name);

                    if (docObj == null)
                    {
                        docObj = project.GetFunction(name);
                    }
                }

                if (docObj != null)
                {
                    using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8))
                    {
                        docObj.Documentation = readHtml.ReadToEnd();
                    }
                }
            }

            // load schema diagrams
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string schema = Path.GetDirectoryName(file);
                schema = Path.GetFileName(schema);

                DocSchema docSchema = project.GetSchema(schema);
                if (docSchema != null)
                {
                    using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project))
                    {
                        schemaSVG.Load();
                    }
                }
            }

            // psets, qsets
            //...

            // exchanges
            en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                IfcDoc.Schema.MVD.SchemaMVD.Load(project, file);
            }

            // examples
            string pathExamples = path + @"\examples";

            if (Directory.Exists(pathExamples))
            {
                en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly);
                foreach (string file in en)
                {
                    DocExample docExample = new DocExample();
                    docExample.Name = Path.GetFileNameWithoutExtension(file);
                    project.Examples.Add(docExample);

                    using (StreamReader reader = new StreamReader(file))
                    {
                        docExample.Documentation = reader.ReadToEnd();
                    }

                    string dirpath = file.Substring(0, file.Length - 4);
                    if (Directory.Exists(dirpath))
                    {
                        IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly);
                        foreach (string ex in suben)
                        {
                            DocExample docEx = new DocExample();
                            docEx.Name = Path.GetFileNameWithoutExtension(ex);
                            docExample.Examples.Add(docEx);

                            // read the content of the file
                            using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read))
                            {
                                docEx.File = new byte[fs.Length];
                                fs.Read(docEx.File, 0, docEx.File.Length);
                            }

                            // read documentation
                            string exdoc = ex.Substring(0, ex.Length - 4) + ".htm";
                            if (File.Exists(exdoc))
                            {
                                using (StreamReader reader = new StreamReader(exdoc))
                                {
                                    docEx.Documentation = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }

            // localization
            en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                using (FormatCSV format = new FormatCSV(file))
                {
                    try
                    {
                        format.Instance = project;
                        format.Load();
                    }
                    catch
                    {
                    }
                }
            }
        }
Exemplo n.º 40
0
 public FixedRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
 }
Exemplo n.º 41
0
 public RequiredIfAttribute(String propertyName, Object desiredvalue)
 {
     PropertyName    = propertyName;
     DesiredValue    = desiredvalue;
     _innerAttribute = new RequiredAttribute();
 }
Exemplo n.º 42
0
        protected override IEnumerable <ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable <Attribute> attributes)
        {
            List <ModelValidator> vals = base.GetValidators(metadata, context, attributes).ToList();
            DataAnnotationsModelValidationFactory factory;

            // Inject our new validator.
            if (metadata.ContainerType != null)
            {
                // Check if we have validation for this class name.
                if (ValidationManager.Validators.ContainsKey(metadata.ContainerType.Name))
                {
                    var validator = ValidationManager.Validators[metadata.ContainerType.Name];

                    // Check if we have validation for this property name.
                    if (validator.ContainsKey(metadata.PropertyName))
                    {
                        var property = validator[metadata.PropertyName];

                        // Only add validation to visible properties.
                        if (property.Visible)
                        {
                            // Required attribute.
                            if (property.Required)
                            {
                                ValidationAttribute required;

                                if (metadata.ModelType == typeof(bool))
                                {
                                    // For required booleans, enforce true.
                                    required = new EnforceTrueAttribute {
                                        ErrorMessage = property.ErrorMessage
                                    };
                                }
                                else if (metadata.ModelType == typeof(int) || metadata.ModelType == typeof(long) || metadata.ModelType == typeof(double) || metadata.ModelType == typeof(float))
                                {
                                    // For required int, long, double, float (dropdownlists), enforce > 0.
                                    required = new GreaterThanZeroAttribute()
                                    {
                                        ErrorMessage = property.ErrorMessage
                                    };
                                }
                                else
                                {
                                    required = new RequiredAttribute {
                                        ErrorMessage = property.ErrorMessage
                                    };
                                }

                                if (!AttributeFactories.TryGetValue(required.GetType(), out factory))
                                {
                                    factory = DefaultAttributeFactory;
                                }

                                yield return(factory(metadata, context, required));
                            }

                            // Regular expression attribute.
                            if (!string.IsNullOrEmpty(property.RegularExpression))
                            {
                                RegularExpressionAttribute regEx = new RegularExpressionAttribute(property.RegularExpression)
                                {
                                    ErrorMessage = property.ErrorMessage
                                };

                                if (!AttributeFactories.TryGetValue(regEx.GetType(), out factory))
                                {
                                    factory = DefaultAttributeFactory;
                                }

                                yield return(factory(metadata, context, regEx));
                            }

                            // Compare attribute.
                            if (!string.IsNullOrEmpty(property.Compare))
                            {
                                CompareAttribute compare = new CompareAttribute(property.Compare)
                                {
                                    ErrorMessage = property.ErrorMessage
                                };

                                if (!AttributeFactories.TryGetValue(compare.GetType(), out factory))
                                {
                                    factory = DefaultAttributeFactory;
                                }

                                yield return(factory(metadata, context, compare));
                            }
                        }
                    }
                }
            }
        }