Ejemplo n.º 1
0
        /// <summary>
        /// Method that checks if bindings are correct for the validation method of this Validation rule
        /// and then invokes teh validation method.
        /// </summary>
        /// <param name="binding"></param>
        /// <returns></returns>
        internal ValidationOperation <TResult> EvaluateAsync(RuleBinding <TResult> binding)
        {
            var bindings = MakeArgumentBindings(binding);
            var result   = ValidationMethod.Invoke(binding.ValidationRule, bindings);

            return((ValidationOperation <TResult>)result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Registrations the specified text box to valid.
        /// </summary>
        /// <param name="textBoxToValid">The text box to valid.</param>
        /// <param name="method">The method.</param>
        public void Registration(TextBox textBoxToValid, ValidationMethod method)
        {
            switch (method)
            {
            case ValidationMethod.Url:
                textBoxToValid.TextChanged += textBoxUrl_TextChanged;
                _registeredToValidationControls.Add(textBoxToValid, false);
                break;

            case ValidationMethod.CurrentDigits:
                textBoxToValid.TextChanged += textBoxCurrentDigits_TextChanged;
                _registeredToValidationControls.Add(textBoxToValid, false);
                break;

            case ValidationMethod.ThreadsCount:
                textBoxToValid.TextChanged += textBoxThreadsCount_TextChanged;
                _registeredToValidationControls.Add(textBoxToValid, false);
                break;

            case ValidationMethod.NotEmpty:
                textBoxToValid.TextChanged += textBoxNotEmpty_TextChanged;
                _registeredToValidationControls.Add(textBoxToValid, false);
                break;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a new instance of a ParameterText box which is validated between two specified values
        /// </summary>
        public ParameterTextBox(int driverIndex, int parameterIndex, float initialValue, float _lowerBound, float _upperBound)
        {
            validationMethod = ValidationMethod.Between;
            lowerBound       = _lowerBound;
            upperBound       = _upperBound;

            InitialiseComponent(driverIndex, parameterIndex, initialValue);
        }
Ejemplo n.º 4
0
        public AndConstraint <IbanNetOptionsBuilderStubAssertions <T> > HaveConfiguredValidationMethod
        (
            ValidationMethod method,
            string because = "",
            params object[] becauseArgs
        )
        {
            VerifyCalled(should => should.HaveValidationMethod(method, because, becauseArgs));

            return(new AndConstraint <IbanNetOptionsBuilderStubAssertions <T> >(this));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new instance of a ParameterTextBox which is validated either greater than or less than a specified boundary.
        /// </summary>
        /// <param name="initialValue">The initial value to display in the text box</param>
        /// <param name="bound">The limiting value for validation of the input</param>
        /// <param name="boundIsUpperBound">True if the control must be less than the specified bound; otherwise false</param>
        public ParameterTextBox(int driverIndex, int parameterIndex, float initialValue, float bound, bool boundIsUpperBound)
        {
            if (boundIsUpperBound)
            {
                upperBound = bound; validationMethod = ValidationMethod.LessThan;
            }
            else
            {
                lowerBound = bound; validationMethod = ValidationMethod.GreaterThan;
            }

            InitialiseComponent(driverIndex, parameterIndex, initialValue);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Base class for form fields
 /// </summary>
 /// <param name="Form">Form containing the field.</param>
 /// <param name="Var">Variable name</param>
 /// <param name="Label">Label</param>
 /// <param name="Required">If the field is required.</param>
 /// <param name="ValueStrings">Values for the field (string representations).</param>
 /// <param name="Options">Options, as (Label,Value) pairs.</param>
 /// <param name="Description">Description</param>
 /// <param name="DataType">Data Type</param>
 /// <param name="ValidationMethod">Validation Method</param>
 /// <param name="Error">Flags the field as having an error.</param>
 /// <param name="PostBack">Flags a field as requiring server post-back after having been edited.</param>
 /// <param name="ReadOnly">Flags a field as being read-only.</param>
 /// <param name="NotSame">Flags a field as having an undefined or uncertain value.</param>
 public Field(DataForm Form, string Var, string Label, bool Required, string[] ValueStrings, KeyValuePair <string, string>[] Options,
              string Description, DataType DataType, ValidationMethod ValidationMethod, string Error, bool PostBack, bool ReadOnly, bool NotSame)
 {
     this.form             = Form;
     this.var              = Var;
     this.label            = Label;
     this.required         = Required;
     this.valueStrings     = ValueStrings;
     this.options          = Options;
     this.description      = Description;
     this.dataType         = DataType;
     this.validationMethod = ValidationMethod;
     this.error            = Error;
     this.postBack         = PostBack;
     this.readOnly         = ReadOnly;
     this.notSame          = NotSame;
 }
        public AndConstraint <IbanValidatorOptionsAssertions> HaveValidationMethod
        (
            ValidationMethod method,
            string because = "",
            params object[] becauseArgs
        )
        {
            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .Given(() => Subject.Method)
            .ForCondition(vm => vm == method)
            .FailWith("Expected {context:options} to use {0}{reason}, but found {1}.",
                      _ => method,
                      m => m);

            return(new AndConstraint <IbanValidatorOptionsAssertions>(this));
        }
Ejemplo n.º 8
0
        private static IIbanNetOptionsBuilder UseValidationMethod(this IIbanNetOptionsBuilder builder, ValidationMethod validationMethod)
        {
            if (builder is null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            return(builder.Configure(options => options.Method = validationMethod));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Hidden form field.
 /// </summary>
 /// <param name="Form">Form containing the field.</param>
 /// <param name="Var">Variable name</param>
 /// <param name="Label">Label</param>
 /// <param name="Required">If the field is required.</param>
 /// <param name="ValueStrings">Values for the field (string representations).</param>
 /// <param name="Options">Options, as (Label,Value) pairs.</param>
 /// <param name="Description">Description</param>
 /// <param name="DataType">Data Type</param>
 /// <param name="ValidationMethod">Validation Method</param>
 /// <param name="Error">Flags the field as having an error.</param>
 /// <param name="PostBack">Flags a field as requiring server post-back after having been edited.</param>
 /// <param name="ReadOnly">Flags a field as being read-only.</param>
 /// <param name="NotSame">Flags a field as having an undefined or uncertain value.</param>
 public HiddenField(DataForm Form, string Var, string Label, bool Required, string[] ValueStrings, KeyValuePair <string, string>[] Options, string Description,
                    DataType DataType, ValidationMethod ValidationMethod, string Error, bool PostBack, bool ReadOnly, bool NotSame)
     : base(Form, Var, Label, Required, ValueStrings, Options, Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame)
 {
 }
Ejemplo n.º 10
0
        [InlineData(false, ValidationMethod.Loose)] // Loose mode.
        public void Given_validation_method_when_adding_it_should_use_correct_method(bool?strict, ValidationMethod expectedValidationMethod)
        {
            // Act
            Fixture.Configure(builder =>
            {
                switch (strict)
                {
                case null:
                    break;

                case true:
                    builder.UseStrictValidation();
                    break;

                case false:
                    builder.UseLooseValidation();
                    break;
                }
            });
            DependencyResolverAdapter adapter = Fixture.Build();

            // Assert
            IIbanValidator validator = adapter.GetRequiredService <IIbanValidator>();

            validator.Should()
            .BeOfType <IbanValidator>()
            .Which.Options.Method.Should()
            .Be(expectedValidationMethod);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sets parameters from a data form in an object.
        /// </summary>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be set.</param>
        /// <param name="Form">Data Form.</param>
        /// <param name="OnlySetChanged">If only changed parameters are to be set.</param>
        /// <returns>Any errors encountered, or null if parameters was set properly.</returns>
        public static async Task <SetEditableFormResult> SetEditableForm(IqEventArgs e, object EditableObject, DataForm Form, bool OnlySetChanged)
        {
            Type   T = EditableObject.GetType();
            string DefaultLanguageCode = GetDefaultLanguageCode(T);
            List <KeyValuePair <string, string> > Errors = null;
            PropertyInfo PropertyInfo;
            FieldInfo    FieldInfo;
            Language     Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace Namespace             = null;
            Namespace ConcentratorNamespace = await Language.GetNamespaceAsync(typeof(ConcentratorServer).Namespace);

            LinkedList <Tuple <PropertyInfo, FieldInfo, object> > ToSet = null;
            ValidationMethod           ValidationMethod;
            OptionAttribute            OptionAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            RangeAttribute             RangeAttribute;
            DataType DataType;
            Type     PropertyType;
            string   NamespaceStr;
            string   LastNamespaceStr = null;
            object   ValueToSet;
            object   ValueToSet2;

            object[] Parsed;
            bool     ReadOnly;
            bool     Alpha;
            bool     DateOnly;
            bool     HasHeader;
            bool     HasOptions;
            bool     ValidOption;
            bool     Nullable;

            if (Namespace is null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            if (ConcentratorNamespace is null)
            {
                ConcentratorNamespace = await Language.CreateNamespaceAsync(typeof(ConcentratorServer).Namespace);
            }

            foreach (Field Field in Form.Fields)
            {
                PropertyInfo = T.GetRuntimeProperty(Field.Var);
                FieldInfo    = PropertyInfo is null?T.GetRuntimeField(Field.Var) : null;

                if (PropertyInfo is null && FieldInfo is null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(1, "Property not found."));
                    continue;
                }

                if (PropertyInfo != null && (!PropertyInfo.CanRead || !PropertyInfo.CanWrite))
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                NamespaceStr = (PropertyInfo?.DeclaringType ?? FieldInfo.DeclaringType).Namespace;
                if (Namespace is null || NamespaceStr != LastNamespaceStr)
                {
                    Namespace = await Language.GetNamespaceAsync(NamespaceStr);

                    LastNamespaceStr = NamespaceStr;
                }

                ValidationMethod = null;
                ReadOnly         = Alpha = DateOnly = HasHeader = HasOptions = ValidOption = false;

                foreach (Attribute Attr in (PropertyInfo?.GetCustomAttributes() ?? FieldInfo.GetCustomAttributes()))
                {
                    if (Attr is HeaderAttribute)
                    {
                        HasHeader = true;
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        HasOptions = true;
                        if (Field.ValueString == OptionAttribute.Option.ToString())
                        {
                            ValidOption = true;
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (!HasHeader)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                if (ReadOnly)
                {
                    if (Field.ValueString != (PropertyInfo?.GetValue(EditableObject) ?? FieldInfo?.GetValue(EditableObject))?.ToString())
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(3, "Property is read-only."));
                    }

                    continue;
                }

                if (HasOptions && !ValidOption)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                    continue;
                }

                PropertyType = PropertyInfo?.PropertyType ?? FieldInfo.FieldType;
                ValueToSet   = null;
                ValueToSet2  = null;
                Parsed       = null;
                DataType     = null;
                Nullable     = false;

                if (PropertyType.GetTypeInfo().IsGenericType)
                {
                    Type GT = PropertyType.GetGenericTypeDefinition();
                    if (GT == typeof(Nullable <>))
                    {
                        Nullable     = true;
                        PropertyType = PropertyType.GenericTypeArguments[0];
                    }
                }

                if (Nullable && string.IsNullOrEmpty(Field.ValueString))
                {
                    ValueToSet2 = null;
                }
                else
                {
                    if (PropertyType == typeof(string[]))
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        ValueToSet = ValueToSet2 = Parsed = Field.ValueStrings;
                        DataType   = StringDataType.Instance;
                    }
                    else if (PropertyType.GetTypeInfo().IsEnum)
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        try
                        {
                            ValueToSet = ValueToSet2 = Enum.Parse(PropertyType, Field.ValueString);
                        }
                        catch (Exception)
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                            continue;
                        }
                    }
                    else if (PropertyType == typeof(bool))
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        if (!CommonTypes.TryParse(Field.ValueString, out bool b))
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(5, "Invalid boolean value."));
                            continue;
                        }

                        DataType   = BooleanDataType.Instance;
                        ValueToSet = ValueToSet2 = b;
                    }
                    else
                    {
                        if (PropertyType == typeof(string))
                        {
                            DataType = StringDataType.Instance;
                        }
                        else if (PropertyType == typeof(sbyte))
                        {
                            DataType = ByteDataType.Instance;
                        }
                        else if (PropertyType == typeof(short))
                        {
                            DataType = ShortDataType.Instance;
                        }
                        else if (PropertyType == typeof(int))
                        {
                            DataType = IntDataType.Instance;
                        }
                        else if (PropertyType == typeof(long))
                        {
                            DataType = LongDataType.Instance;
                        }
                        else if (PropertyType == typeof(byte))
                        {
                            DataType = ShortDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(byte.MinValue.ToString(), byte.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(ushort))
                        {
                            DataType = IntDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(uint))
                        {
                            DataType = LongDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(ulong))
                        {
                            DataType = IntegerDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(DateTime))
                        {
                            if (DateOnly)
                            {
                                DataType = DateDataType.Instance;
                            }
                            else
                            {
                                DataType = DateTimeDataType.Instance;
                            }
                        }
                        else if (PropertyType == typeof(decimal))
                        {
                            DataType = DecimalDataType.Instance;
                        }
                        else if (PropertyType == typeof(double))
                        {
                            DataType = DoubleDataType.Instance;
                        }
                        else if (PropertyType == typeof(float))
                        {
                            DataType = DoubleDataType.Instance;                                // Use xs:double anyway
                        }
                        else if (PropertyType == typeof(TimeSpan))
                        {
                            DataType = TimeDataType.Instance;
                        }
                        else if (PropertyType == typeof(Uri))
                        {
                            DataType = AnyUriDataType.Instance;
                        }
                        else if (PropertyType == typeof(SKColor))
                        {
                            if (Alpha)
                            {
                                DataType = ColorAlphaDataType.Instance;
                            }
                            else
                            {
                                DataType = ColorDataType.Instance;
                            }
                        }
                        else
                        {
                            DataType = null;
                        }

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        try
                        {
                            if (DataType is null)
                            {
                                ValueToSet  = Field.ValueString;
                                ValueToSet2 = Activator.CreateInstance(PropertyType, ValueToSet);
                            }
                            else
                            {
                                ValueToSet = DataType.Parse(Field.ValueString);

                                if (ValueToSet.GetType() == PropertyType)
                                {
                                    ValueToSet2 = ValueToSet;
                                }
                                else
                                {
                                    ValueToSet2 = Convert.ChangeType(ValueToSet, PropertyType);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(6, "Invalid value."));
                            continue;
                        }
                    }

                    if (Parsed is null)
                    {
                        Parsed = new object[] { ValueToSet }
                    }
                    ;

                    ValidationMethod.Validate(Field, DataType, Parsed, Field.ValueStrings);
                    if (Field.HasError)
                    {
                        AddError(ref Errors, Field.Var, Field.Error);
                        continue;
                    }
                }

                if (ToSet is null)
                {
                    ToSet = new LinkedList <Tuple <PropertyInfo, FieldInfo, object> >();
                }

                ToSet.AddLast(new Tuple <PropertyInfo, FieldInfo, object>(PropertyInfo, FieldInfo, ValueToSet2));
            }

            if (Errors is null)
            {
                SetEditableFormResult Result = new SetEditableFormResult()
                {
                    Errors = null,
                    Tags   = new List <KeyValuePair <string, object> >()
                };

                foreach (Tuple <PropertyInfo, FieldInfo, object> P in ToSet)
                {
                    try
                    {
                        if (OnlySetChanged)
                        {
                            object Current = P.Item1?.GetValue(EditableObject) ?? P.Item2?.GetValue(EditableObject);

                            if (Current is null)
                            {
                                if (P.Item3 is null)
                                {
                                    continue;
                                }
                            }
                            else if (P.Item3 != null && Current.Equals(P.Item3))
                            {
                                continue;
                            }
                        }

                        if (P.Item1 != null)
                        {
                            P.Item1.SetValue(EditableObject, P.Item3);
                            Result.Tags.Add(new KeyValuePair <string, object>(P.Item1.Name, P.Item3));
                        }
                        else
                        {
                            P.Item2.SetValue(EditableObject, P.Item3);
                            Result.Tags.Add(new KeyValuePair <string, object>(P.Item2.Name, P.Item3));
                        }
                    }
                    catch (Exception ex)
                    {
                        AddError(ref Errors, P.Item1?.Name ?? P.Item2.Name, ex.Message);
                    }
                }

                return(Result);
            }
            else
            {
                return(new SetEditableFormResult()
                {
                    Errors = Errors.ToArray(),
                    Tags = null
                });
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sets parameters from a data form in an object.
        /// </summary>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be set.</param>
        /// <param name="Form">Data Form.</param>
        /// <returns>Any errors encountered, or null if parameters was set properly.</returns>
        public static async Task <KeyValuePair <string, string>[]> SetEditableForm(IqEventArgs e, object EditableObject, DataForm Form)
        {
            Type   T = EditableObject.GetType();
            string DefaultLanguageCode = GetDefaultLanguageCode(T);
            List <KeyValuePair <string, string> > Errors = null;
            PropertyInfo PI;
            Language     Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace Namespace = await Language.GetNamespaceAsync(T.Namespace);

            Namespace ConcentratorNamespace = await Language.GetNamespaceAsync(typeof(ConcentratorServer).Namespace);

            LinkedList <KeyValuePair <PropertyInfo, object> > ToSet = null;
            ValidationMethod           ValidationMethod;
            OptionAttribute            OptionAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            RangeAttribute             RangeAttribute;
            DataType DataType;
            Type     PropertyType;
            string   Header;
            object   ValueToSet;

            object[] Parsed;
            bool     ReadOnly;
            bool     Alpha;
            bool     DateOnly;
            bool     HasHeader;
            bool     HasOptions;
            bool     ValidOption;

            if (Namespace == null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            if (ConcentratorNamespace == null)
            {
                ConcentratorNamespace = await Language.CreateNamespaceAsync(typeof(ConcentratorServer).Namespace);
            }

            foreach (Field Field in Form.Fields)
            {
                PI = T.GetRuntimeProperty(Field.Var);
                if (PI == null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(1, "Property not found."));
                    continue;
                }

                if (!PI.CanRead || !PI.CanWrite)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                Header           = null;
                ValidationMethod = null;
                ReadOnly         = Alpha = DateOnly = HasHeader = HasOptions = ValidOption = false;

                foreach (Attribute Attr in PI.GetCustomAttributes())
                {
                    if (Attr is HeaderAttribute)
                    {
                        HasHeader = true;
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        HasOptions = true;
                        if (Field.ValueString == OptionAttribute.Option.ToString())
                        {
                            ValidOption = true;
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (Header == null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                if (ReadOnly)
                {
                    if (Field.ValueString != PI.GetValue(EditableObject).ToString())
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(3, "Property is read-only."));
                    }

                    continue;
                }

                if (HasOptions && !ValidOption)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                    continue;
                }

                PropertyType = PI.PropertyType;
                ValueToSet   = null;
                Parsed       = null;
                DataType     = null;

                if (PropertyType == typeof(string[]))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    ValueToSet = Parsed = Field.ValueStrings;
                    DataType   = StringDataType.Instance;
                }
                else if (PropertyType == typeof(Enum))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    try
                    {
                        ValueToSet = Enum.Parse(PropertyType, Field.ValueString);
                    }
                    catch (Exception)
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                        continue;
                    }
                }
                else if (PropertyType == typeof(bool))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (!CommonTypes.TryParse(Field.ValueString, out bool b))
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(5, "Invalid boolean value."));
                        continue;
                    }

                    DataType = BooleanDataType.Instance;
                }
                else
                {
                    if (PropertyType == typeof(string))
                    {
                        DataType = StringDataType.Instance;
                    }
                    else if (PropertyType == typeof(byte))
                    {
                        DataType = ByteDataType.Instance;
                    }
                    else if (PropertyType == typeof(short))
                    {
                        DataType = ShortDataType.Instance;
                    }
                    else if (PropertyType == typeof(int))
                    {
                        DataType = IntDataType.Instance;
                    }
                    else if (PropertyType == typeof(long))
                    {
                        DataType = LongDataType.Instance;
                    }
                    else if (PropertyType == typeof(sbyte))
                    {
                        DataType = ShortDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(sbyte.MinValue.ToString(), sbyte.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ushort))
                    {
                        DataType = IntDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(uint))
                    {
                        DataType = LongDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ulong))
                    {
                        DataType = IntegerDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(DateTime))
                    {
                        if (DateOnly)
                        {
                            DataType = DateDataType.Instance;
                        }
                        else
                        {
                            DataType = DateTimeDataType.Instance;
                        }
                    }
                    else if (PropertyType == typeof(decimal))
                    {
                        DataType = DecimalDataType.Instance;
                    }
                    else if (PropertyType == typeof(double))
                    {
                        DataType = DoubleDataType.Instance;
                    }
                    else if (PropertyType == typeof(float))
                    {
                        DataType = DoubleDataType.Instance;                            // Use xs:double anyway
                    }
                    else if (PropertyType == typeof(TimeSpan))
                    {
                        DataType = TimeDataType.Instance;
                    }
                    else if (PropertyType == typeof(Uri))
                    {
                        DataType = AnyUriDataType.Instance;
                    }
                    else if (PropertyType == typeof(SKColor))
                    {
                        if (Alpha)
                        {
                            DataType = ColorAlphaDataType.Instance;
                        }
                        else
                        {
                            DataType = ColorDataType.Instance;
                        }
                    }
                    else
                    {
                        DataType = null;
                    }

                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    try
                    {
                        ValueToSet = DataType.Parse(Field.ValueString);
                    }
                    catch (Exception)
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(6, "Invalid value."));
                        continue;
                    }
                }

                if (Parsed == null)
                {
                    Parsed = new object[] { ValueToSet }
                }
                ;

                ValidationMethod.Validate(Field, DataType, Parsed, Field.ValueStrings);
                if (Field.HasError)
                {
                    AddError(ref Errors, Field.Var, Field.Error);
                    continue;
                }

                if (ToSet == null)
                {
                    ToSet = new LinkedList <KeyValuePair <PropertyInfo, object> >();
                }

                ToSet.AddLast(new KeyValuePair <PropertyInfo, object>(PI, ValueToSet));
            }

            if (Errors == null)
            {
                foreach (KeyValuePair <PropertyInfo, object> P in ToSet)
                {
                    try
                    {
                        P.Key.SetValue(EditableObject, P.Value);
                    }
                    catch (Exception ex)
                    {
                        AddError(ref Errors, P.Key.Name, ex.Message);
                    }
                }
            }

            if (Errors == null)
            {
                return(null);
            }
            else
            {
                return(Errors.ToArray());
            }
        }
Ejemplo n.º 13
0
 public ValidationRule(ValidationTarget targetName, ValidationMethod validationMethod)
 {
     TargetName = targetName;
     ValidationMethods.Add(validationMethod);
 }
Ejemplo n.º 14
0
        private Field ParseField(XmlElement E)
        {
            string        Label        = XML.Attribute(E, "label");
            string        Type         = XML.Attribute(E, "type");
            string        Var          = XML.Attribute(E, "var");
            List <string> ValueStrings = null;
            List <KeyValuePair <string, string> > OptionStrings = null;
            string           Description      = string.Empty;
            string           DataTypeName     = null;
            DataType         DataType         = null;
            ValidationMethod ValidationMethod = null;
            Media            Media            = null;
            Field            Field;
            string           Error    = null;
            bool             Required = false;
            bool             PostBack = false;
            bool             ReadOnly = false;
            bool             NotSame  = false;

            foreach (XmlNode N2 in E.ChildNodes)
            {
                switch (N2.LocalName)
                {
                case "desc":
                    Description = N2.InnerText;
                    break;

                case "required":
                    Required = true;
                    break;

                case "value":
                    if (ValueStrings == null)
                    {
                        ValueStrings = new List <string>();
                    }

                    ValueStrings.Add(N2.InnerText);
                    break;

                case "option":
                    if (OptionStrings == null)
                    {
                        OptionStrings = new List <KeyValuePair <string, string> >();
                    }

                    string OptionLabel = XML.Attribute((XmlElement)N2, "label");
                    string OptionValue = string.Empty;

                    foreach (XmlNode N3 in N2.ChildNodes)
                    {
                        if (N3.LocalName == "value")
                        {
                            OptionValue = N3.InnerText;
                            break;
                        }
                    }

                    OptionStrings.Add(new KeyValuePair <string, string>(OptionLabel, OptionValue));
                    break;

                case "validate":
                    DataTypeName = XML.Attribute((XmlElement)N2, "datatype");

                    foreach (XmlNode N3 in N2.ChildNodes)
                    {
                        switch (N3.LocalName)
                        {
                        case "basic":
                            ValidationMethod = new BasicValidation();
                            break;

                        case "open":
                            ValidationMethod = new OpenValidation();
                            break;

                        case "range":
                            XmlElement E3 = (XmlElement)N3;

                            ValidationMethod = new RangeValidation(
                                XML.Attribute(E3, "min"),
                                XML.Attribute(E3, "max"));
                            break;

                        case "regex":
                            ValidationMethod = new RegexValidation(N3.InnerText);
                            break;

                        case "list-range":
                            E3 = (XmlElement)N3;

                            ValidationMethod = new ListRangeValidation(ValidationMethod,
                                                                       XML.Attribute(E3, "min", 0),
                                                                       XML.Attribute(E3, "max", int.MaxValue));
                            break;
                        }
                    }
                    break;

                case "media":
                    Media = new Media((XmlElement)N2);
                    break;

                case "postBack":
                    PostBack = true;
                    break;

                case "readOnly":
                    ReadOnly = true;
                    break;

                case "notSame":
                    NotSame = true;
                    break;

                case "error":
                    Error = N2.InnerText;
                    break;
                }
            }

            if (string.IsNullOrEmpty(DataTypeName))
            {
                if (Type == "boolean")
                {
                    DataTypeName = "xs:boolean";
                }
                else
                {
                    DataTypeName = "xs:string";
                }
            }

            switch (DataTypeName.ToLower())
            {
            case "xs:boolean":
                DataType = BooleanDataType.Instance;
                break;

            case "xs:string":
            default:
                DataType = StringDataType.Instance;
                break;

            case "anyuri":
                DataType = AnyUriDataType.Instance;
                break;

            case "xs:byte":
                DataType = ByteDataType.Instance;
                break;

            case "xs:date":
                DataType = DateDataType.Instance;
                break;

            case "xs:datetime":
                DataType = DateTimeDataType.Instance;
                break;

            case "xs:decimal":
                DataType = DecimalDataType.Instance;
                break;

            case "xs:double":
                DataType = DoubleDataType.Instance;
                break;

            case "xs:int":
                DataType = IntDataType.Instance;
                break;

            case "xs:integer":
                DataType = IntegerDataType.Instance;
                break;

            case "xs:language":
                DataType = LanguageDataType.Instance;
                break;

            case "xs:long":
                DataType = LongDataType.Instance;
                break;

            case "xs:short":
                DataType = ShortDataType.Instance;
                break;

            case "xs:time":
                DataType = TimeDataType.Instance;
                break;

            case "xdc:Color":
                DataType = ColorDataType.Instance;
                break;

            case "xdc:ColorAlpha":
                DataType = ColorAlphaDataType.Instance;
                break;
            }

            if (ValidationMethod == null)
            {
                ValidationMethod = new BasicValidation();
            }

            switch (Type)
            {
            case "boolean":
                Field = new BooleanField(this, Var, Label, Required,
                                         ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                         Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "fixed":
                Field = new FixedField(this, Var, Label, Required,
                                       ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                       Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "hidden":
                Field = new HiddenField(this, Var, Label, Required,
                                        ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                        Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "jid-multi":
                Field = new JidMultiField(this, Var, Label, Required,
                                          ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                          Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "jid-single":
                Field = new JidSingleField(this, Var, Label, Required,
                                           ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                           Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "list-multi":
                Field = new ListMultiField(this, Var, Label, Required,
                                           ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                           Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "list-single":
                Field = new ListSingleField(this, Var, Label, Required,
                                            ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                            Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "text-multi":
                Field = new TextMultiField(this, Var, Label, Required,
                                           ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                           Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "text-private":
                Field = new TextPrivateField(this, Var, Label, Required,
                                             ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                             Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            case "text-single":
                Field = new TextSingleField(this, Var, Label, Required,
                                            ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                            Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                break;

            default:
                if (Media == null)
                {
                    Field = new TextSingleField(this, Var, Label, Required,
                                                ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                                Description, DataType, ValidationMethod, Error, PostBack, ReadOnly, NotSame);
                }
                else
                {
                    Field = new MediaField(this, Var, Label, Required,
                                           ValueStrings?.ToArray(), OptionStrings?.ToArray(),
                                           Description, DataType, ValidationMethod, Media, Error, PostBack, ReadOnly, NotSame);
                }
                break;
            }

            return(Field);
        }
Ejemplo n.º 15
0
        public void Given_custom_rules_for_any_method_when_getting_rules_it_should_append_custom_rules(ValidationMethod method)
        {
            _options.Method = method;
            IIbanValidationRule rule1 = Mock.Of <IIbanValidationRule>();
            IIbanValidationRule rule2 = Mock.Of <IIbanValidationRule>();

            _options.Rules.Add(rule1);
            _options.Rules.Add(rule2);

            // Act
            IEnumerable <IIbanValidationRule> rules = _sut.GetRules();

            // Assert
            rules.Should()
            .EndWith(new[] { rule1, rule2 });
        }