Beispiel #1
0
 public ValidationResults(IValidatable target)
 {
     foreach (var result in target.Validate())
     {
         validationResults.Add(result);
     }
 }
Beispiel #2
0
        public async Task <EventBusinessResponseVO> ProcessEvent(DeviceEventDTO dvcEvtDTO)
        {
            int    value;
            string valueType = string.Empty;

            int.TryParse(dvcEvtDTO.Valor, out value);
            if (value != 0)
            {
                valueType = "INT";
            }
            else
            {
                valueType = "STR";
            }

            ValidationResultList validatonResultList = _validator.Validate(dvcEvtDTO);

            //Seria mais elegante ter feito por filters, mas fiz assim para deixar explicito o processo
            if (validatonResultList.items.Count > 0)
            {
                return(new EventBusinessResponseVO("error",
                                                   "The request provided contain errors",
                                                   DeviceEventBusinessStatusResponse.ERROR,
                                                   validatonResultList));
            }

            DeviceEvent dvcEvt = DeviceEvent.CreateFromDTOParameters(dvcEvtDTO.Timestamp, dvcEvtDTO.Tag, dvcEvtDTO.Valor, valueType);
            await _dvcEvtRepository.Add(dvcEvt);

            return(new EventBusinessResponseVO("success",
                                               "The request was processed successfully",
                                               DeviceEventBusinessStatusResponse.SUCCESS,
                                               validatonResultList));
        }
 public ValidationResults(IValidatable target)
 {
     foreach (var result in target.Validate())
     {
         validationResults.Add(result);
     }
 }
        static private void FlushBlock(ref ParseState ioState, TagData inEndData)
        {
            ioState.ContentBuilder.TrimEnd(BlockParser.TrimCharsWithSpace);
            if (ioState.ContentBuilder.Length > 0)
            {
                BlockMetaCache.ContentInfo contentSetter;
                if (ioState.Cache.TryGetContent(ioState.CurrentBlock, out contentSetter))
                {
                    if (contentSetter.Mode == BlockContentMode.BatchContent)
                    {
                        string contentString = ioState.ContentBuilder.Flush();
                        if (contentString.IndexOf('\\') >= 0)
                        {
                            contentString = StringUtils.Unescape(contentString);
                        }
                        ioState.BlockError |= contentSetter.Invoke(ioState.CurrentBlock, contentString, ioState.Cache.SharedResources);
                        ioState.Error      |= ioState.BlockError;
                    }
                }

                ioState.ContentBuilder.Length = 0;
            }

            IValidatable validatable = ioState.CurrentBlock as IValidatable;

            if (validatable != null)
            {
                validatable.Validate();
            }

            ioState.Generator.CompleteBlock(ioState, ioState.Package, ioState.CurrentBlock, inEndData, ioState.BlockError);
        }
        protected IActionResult ValidateParentAndRedirect(IValidatable parent, FormSection section, string actionName)
        {
            parent.Validate();
            var nextActionName = FormDefinition.GetNextPage(section, actionName).ActionName;

            return(parent.IsValid ? RedirectToLastActionForNewSection(section) : RedirectToAction(section, nextActionName));
        }
Beispiel #6
0
        /// <summary>
        /// Checks if the specified property of the specified validation source is valid.
        /// </summary>
        /// <param name="validationSource">The validation source.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>
        ///   <c>true</c> if the specified property name is valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValid(this IValidatable validationSource, string propertyName)
        {
            propertyName.CannotBeNull();
            validationSource.CannotBeNull();

            return(!validationSource.Validate(propertyName).Any(x => x.ValidationLevel == ValidationLevel.Error));
        }
Beispiel #7
0
        /// <summary>
        /// Validates the specified property of the specified validation source.
        /// </summary>
        /// <param name="validationSource">The validation source.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>The collection of validation mesasges.</returns>
        public static ValidationMessageCollection Validate(this IValidatable validationSource, string propertyName)
        {
            validationSource.CannotBeNull();
            propertyName.CannotBeNullOrEmpty();

            ValidationMessageCollection messages = new ValidationMessageCollection();
            List <string> validationContexts;
            object        propertyValue;

            // get property value
            var properties = ReflectionExtensions.GetProperties(validationSource.GetType());

            if (properties.TryGetValue(propertyName, out PropertyData propertyData))
            {
                if (propertyData.PropertyInfo.CanRead &&
                    propertyData.PropertyInfo.CanWrite)
                {
                    propertyValue = propertyData.PropertyInfo.GetValue(validationSource);

                    // get validation context
                    validationContexts = new List <string>();
                    validationContexts.Add(ValidationContext.Default);                                                     // always add the default validation context
                    validationContexts.AddRange(validationSource.GetActiveValidationContexts() ?? Array.Empty <string>()); // add currently active validation context

                    foreach (var validationContext in validationContexts.Distinct())
                    {
                        messages.AddRange(validationSource.Validate(propertyName, propertyValue, validationContext));
                    }
                }
            }

            return(messages);
        }
Beispiel #8
0
        public static bool TryValidate <T>(this IValidatable validatable, out ValidationResult validationResult, IServiceProvider serviceProvider = null)
            where T : class, IValidator
        {
            validationResult = validatable.Validate <T>(serviceProvider);

            return(validationResult.IsValid);
        }
        public static IAsyncValidationRule AddChildValidatable([NotNull] this ValidationHelper validator,
                                                               [NotNull] Expression <Func <IValidatable> > childValidatableGetter)
        {
            Guard.NotNull(validator, nameof(validator));
            Guard.NotNull(childValidatableGetter, nameof(childValidatableGetter));

            Func <IValidatable> getter = childValidatableGetter.Compile();

            return(validator.AddAsyncRule(PropertyName.For(childValidatableGetter), () =>
            {
                IValidatable validatable = getter();

                if (validatable != null)
                {
                    return validatable.Validate().ContinueWith(r =>
                    {
                        ValidationResult result = r.Result;

                        var ruleResult = new RuleResult();

                        foreach (ValidationError error in result.ErrorList)
                        {
                            ruleResult.AddError(error.ErrorText);
                        }

                        return ruleResult;
                    });
                }

                return TaskEx.FromResult(RuleResult.Valid());
            }));
        }
Beispiel #10
0
        /// <summary>
        /// Extension point allowing the user to customize validation of an entity or filter out validation results.
        /// Called by <see cref="M:System.Data.Entity.DbContext.GetValidationErrors"/>.
        /// </summary>
        /// <param name="entityEntry">DbEntityEntry instance to be validated.</param>
        /// <param name="items">User defined dictionary containing additional info for custom validation.
        /// It will be passed to <see cref="T:System.ComponentModel.DataAnnotations.ValidationContext"/>
        /// and will be exposed as <see cref="P:System.ComponentModel.DataAnnotations.ValidationContext.Items"/>.
        /// This parameter is optional and can be null.</param>
        /// <returns>
        /// Entity validation result. Possibly null when overridden.
        /// </returns>
        /// <remarks>Note: validating each entity causes lazy loading of all related objects and this can get very expensive.</remarks>
        protected override DbEntityValidationResult ValidateEntity(
            DbEntityEntry entityEntry,
            IDictionary <object, object> items)
        {
            if (entityEntry == null)
            {
                throw new ArgumentNullException(nameof(entityEntry));
            }

            IValidatable validatable = entityEntry.Entity as IValidatable;

            if (validatable == null)
            {
                return(base.ValidateEntity(entityEntry, items));
            }

            var results = validatable.Validate();

            if (results.IsValid)
            {
                return(new DbEntityValidationResult(entityEntry, new DbValidationError[] { }));
            }

            return(new DbEntityValidationResult(
                       entityEntry,
                       ToValidationErrors(
                           results,
                           new List <DbValidationError>()).ToArray()));
        }
 public static void ValidateRequired(this IValidatable item, string arg)
 {
     if (item == null)
     {
         throw new ArgumentNullException(arg);
     }
     item.Validate();
 }
        protected IActionResult ValidateParentAndRedirectBack(IValidatable parent, FormSection section, int nextPageId, FormSection?parentSection = null)
        {
            parent.Validate();

            return(nextPageId > 0
                ? (parent.IsValid ? RedirectToLastAction(parentSection ?? section) : RedirectBackToAction(section, nextPageId))
                : RedirectToLastAction(section));
        }
Beispiel #13
0
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="validater">验证器</param>
        public Validater AddCondition(IValidatable validater)
        {
            ValidateResult validateResult = validater.Validate();
            if (!validateResult.IsValidated)
                _ErrorMessageList.AddRange(validateResult.ErrorMessage);

            return this;
        }
        public static bool IsValid(this IValidatable validatableObject, out ValidationCollection validations)
        {
            validatableObject.ThrowIfNull(nameof(validatableObject));

            validations = new ValidationCollection();
            validatableObject.Validate(validations);
            return(validations.IsValid);
        }
Beispiel #15
0
 public bool Validate()
 {
     if (_validatableObject == null)
     {
         return(false);//-- or you can throw error here
     }
     return(_validatableObject.Validate());
 }
        protected IActionResult ValidateParentAndRedirectBack(IValidatable parent, FormSection section, string actionName, FormSection?parentSection = null)
        {
            parent.Validate();
            var prevPage = FormDefinition.GetPreviousPage(section, actionName);

            return(parent.IsValid
                ? RedirectToLastActionForNewSection(parentSection ?? section)
                : RedirectBackToAction(section, prevPage.ActionName));
        }
Beispiel #17
0
        public static void EnsureIsValid(this IValidatable validatable)
        {
            var errors = validatable.Validate().ToList();

            if (errors.Any())
            {
                throw new ValidationException(errors.ToNonEmptyList());
            }
        }
        public static void EnforceValidity(this IValidatable obj)
        {
            var results = obj.Validate().ToArray();

            if (results.Any())
            {
                throw new ValidationException(results.Select(v => v.ErrorMessage).Join(Environment.NewLine));
            }
        }
Beispiel #19
0
        public void Validate(IValidatable model)
        {
            var result = model.Validate();

            if (result.Count() > 0)
            {
                throw new PaySimpleException(result);
            }
        }
        public static void ValidateOptional(this IValidatable item)
        {
            if (item == null)
            {
                return;
            }

            item.Validate();
        }
Beispiel #21
0
        internal static void Validate(IValidatable validatable, ValidationContext context)
        {
            IList <StoreObjectValidationError> list = new List <StoreObjectValidationError>();

            validatable.Validate(context, list);
            if (list.Count > 0)
            {
                throw new ObjectValidationException(ServerStrings.ExCannotSaveInvalidObject(list[0]), list);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Gets a value indicating whether this instance is valid according to the validation properties and methods.
        /// </summary>
        /// <param name="validatable">The object to which the method is applied.</param>
        /// <param name="ruleset">The ruleset to test validity against.</param>
        /// <returns><see langword="true" /> if the object is valid, otherwise <see langword="false" />.</returns>
        /// <remarks>Based upon the Validation Application Block from Microsoft Enterprise Library</remarks>
        public static bool IsValid(
            this IValidatable validatable,
            string ruleset = "")
        {
            if (validatable == null)
            {
                throw new ArgumentNullException(nameof(validatable));
            }

            return(validatable.Validate(ruleset).IsValid);
        }
        public static void Validate(this IValidatable target, Func <string> message)
        {
            var errors = new List <ValidationError>();

            target.Validate(errors);

            if (errors.Any())
            {
                throw new ValidationException(message(), errors);
            }
        }
Beispiel #24
0
    public static ValidationError[] Validate(object obj)
    {
        IValidatable validObj = obj as IValidatable;

        if (obj == null)
        {
            // not validatable
            return(new ValidationError[0]);
        }
        return(validObj.Validate(_rulesets));
    }
Beispiel #25
0
        /// <summary>
        ///     Will throw a <see cref="RuleException" /> if any errors are detected.
        /// </summary>
        /// <param name="validatable">The entity that is validatable.</param>
        /// <param name="getMessage">The function to construct the error message.</param>
        /// <exception cref="RuleException">Raised if any errors are detected in the validatable instance.</exception>
        public static void ThrowExceptionIfInvalid(this IValidatable validatable, Func <string> getMessage)
        {
            Guard.ArgumentNotNull(validatable, nameof(validatable));
            Guard.ArgumentNotNull(getMessage, nameof(getMessage));

            var errors = validatable.Validate().ToArray();

            if (errors.Any())
            {
                throw new RuleException(getMessage?.Invoke(), errors);
            }
        }
Beispiel #26
0
 protected void ExecBiz <TParam>(TParam model, Action <TParam> action)
 {
     using (new MetricLoggerHelper("性能日志")) // 套路2 成功转移
     {
         IValidatable m = model as IValidatable;
         if (m != null && !m.Validate())
         {
             throw new ArgumentException(); // 纠结的套路1 也成功转移
         }
         log.Write("我要记录参数……");             // 套路3 成功转移
         action(model);
         log.Write("我要记录执行结果……");           // 套路4 成功转移
     }
 }
Beispiel #27
0
        /// <summary>
        /// Validates the the specified validation source.
        /// </summary>
        /// <param name="validationSource">The validation source.</param>
        /// <returns>
        /// The collection of validation mesasges.
        /// </returns>
        public static ValidationMessageCollection Validate(this IValidatable validationSource)
        {
            validationSource.CannotBeNull();

            ValidationMessageCollection messages = new ValidationMessageCollection();
            var propertyNames = ReflectionExtensions.GetProperties(validationSource.GetType()).Keys;

            foreach (var propertyName in propertyNames)
            {
                messages.AddRange(validationSource.Validate(propertyName));
            }

            return(messages);
        }
Beispiel #28
0
        public bool Validate()
        {
            bool result = true;

            IValidatable validatable = _child as IValidatable;

            if (validatable != null)
            {
                result &= validatable.Validate();
            }


            return(result);
        }
Beispiel #29
0
 public static void RequireValidatedOrNull(IValidatable parameterValue, string parameterName, string customMessage = null)
 {
     if (parameterValue == null)
     {
         return;
     }
     try
     {
         parameterValue.Validate($"{Namespace}: F8A9DE78-28E2-4FC1-A1D7-88020E720525");
     }
     catch (FulcrumContractException e)
     {
         throw new FulcrumContractException($"Validation failed for {parameterName}: {e.Message}", e);
     }
 }
 /// <summary>
 /// If <paramref name="parameterValue"/> is not null, then call the FulcrumValidate() method of that type.
 /// </summary>
 public static void RequireValidatedOrNull(IValidatable parameterValue, string parameterName, string customMessage = null)
 {
     if (parameterValue == null)
     {
         return;
     }
     try
     {
         parameterValue.Validate($"{Namespace}: E1774ECE-78BC-40B4-B9FD-2293BBF4D944");
     }
     catch (FulcrumServiceContractException e)
     {
         throw new FulcrumServiceContractException($"Validation failed for {parameterName}: {e.Message}", e);
     }
 }
Beispiel #31
0
        /// <summary>
        /// Saves the or update the entity asynchronous.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public virtual Task <T> SaveOrUpdateAsync(T entity)
        {
            IValidatable validatable = entity as IValidatable;

            if (validatable != null)
            {
                ValidationSummary validationSummary = validatable.Validate();
                if (!validationSummary.IsValid)
                {
                    throw new ValidationException(validationSummary);
                }
            }

            return(Repository.SaveOrUpdateAsync(entity));
        }
Beispiel #32
0
        public bool Validate()
        {
            bool result = true;

            foreach (var control in _controls)
            {
                IValidatable validatable = control as IValidatable;
                if (validatable != null)
                {
                    result &= validatable.Validate();
                }
            }

            return(result);
        }
Beispiel #33
0
 private bool IsValid(IValidatable toValidate)
 {
     ModelStateDictionary state = new ModelStateDictionary();
       toValidate.Validate(state);
       return state.IsValid;
 }