/// <summary>
        /// Checks all properties for DataAnnotations attributes.
        /// 检查数据注释属性的所有属性
        /// </summary>
        protected virtual void SetDataAnnotationAttributeErrors(object validatingObject)
        {
            var properties = TypeDescriptor.GetProperties(validatingObject).Cast <PropertyDescriptor>();

            foreach (var property in properties)
            {
                var validationAttributes = property.Attributes.OfType <ValidationAttribute>().ToArray();
                if (validationAttributes.IsNullOrEmpty())
                {
                    continue;
                }

                var validationContext = new ValidationContext(validatingObject)
                {
                    DisplayName = property.DisplayName,
                    MemberName  = property.Name
                };

                foreach (var attribute in validationAttributes)
                {
                    var result = attribute.GetValidationResult(property.GetValue(validatingObject), validationContext);
                    if (result != null)
                    {
                        ValidationErrors.Add(result);
                    }
                }
            }

            //如果用户自己实现了IValidatableObject 则也自动拦截它
            if (validatingObject is IValidatableObject)
            {
                var results = (validatingObject as IValidatableObject).Validate(new ValidationContext(validatingObject));
                ValidationErrors.AddRange(results);
            }
        }
Пример #2
0
        /// <summary>
        /// Validates this instance.
        /// </summary>
        protected override void Validate()
        {
            if (string.IsNullOrEmpty(Question))
            {
                ValidationErrors.Add("Question");
            }

            if (string.IsNullOrEmpty(CompetitionKey))
            {
                ValidationErrors.Add("CompetitionKey");
            }

            if (ClosingDate == DateTime.MinValue)
            {
                ValidationErrors.Add("ClosingDate");
            }

            if (CreatedBy == null)
            {
                ValidationErrors.Add("CreatedBy");
            }

            if (!PossibleAnswers.IsValid)
            {
                ValidationErrors.AddRange(PossibleAnswers.ValidationErrors.Items);
            }
        }
Пример #3
0
        protected void Validate()
        {
            var results = new List <ValidationResult>();

            Validator.TryValidateObject(this, CreateValidateContext(), results);
            ValidationErrors.AddRange(results.Where(r => r != ValidationResult.Success));
        }
Пример #4
0
        }         // Validate

        public void RestoreValidationErrors(IEnumerable <string> errors)
        {
            ValidationErrors.Clear();

            if (errors != null)
            {
                ValidationErrors.AddRange(errors);
            }
        } // RestoreValidationErrors
        public void Validate(T input)
        {
            var sourceValue = Property.GetValue(input);

            TestOperand.Validate(sourceValue, TestValue);

            ValidationErrors.Clear();
            ValidationErrors.AddRange(TestOperand.GetValidationErrors());
        }
Пример #6
0
        public IEnumerable <ValidationError> Validate(IBusinessObject ObjectToValidate)
        {
            var errors = new ValidationErrors();

            if (ObjectToValidate is T validationTarget)
            {
                errors.AddRange(Validate(validationTarget));
            }
            return(errors);
        }
Пример #7
0
 protected virtual void SetValidationErrors(object validatingObject)
 {
     foreach (var validatorType in _configuration.Validators)
     {
         if (ShouldValidateUsingValidator(validatingObject, validatorType))
         {
             using (var validator = _iocResolver.ResolveAsDisposable <IMethodParameterValidator>(validatorType))
             {
                 var validationResults = validator.Object.Validate(validatingObject);
                 ValidationErrors.AddRange(validationResults);
             }
         }
     }
 }
Пример #8
0
        public bool Validate(T item)
        {
            if (_validate != null)
            {
                List <string> returnErrors = _validate.Validate(item);
                if (returnErrors.Count > 0)
                {
                    ValidationErrors.AddRange(returnErrors);
                    return(false);
                }
            }

            return(true);
        }
Пример #9
0
        /// <summary>
        /// Validates this instance.
        /// </summary>
        protected override void Validate()
        {
            if (Answer == CompetitionAnswer.NotSet)
            {
                ValidationErrors.Add("Answer");
            }

            if (Source == EntrantSource.NotSet)
            {
                ValidationErrors.Add("EntryDate");
            }

            if (!Contact.IsValid)
            {
                ValidationErrors.AddRange(Contact.ValidationErrors.Items);
            }
        }
Пример #10
0
        public virtual async Task <IList <ValidationFailure> > ValidateAsync(CartValidationContext validationContext, string ruleSet)
        {
            if (validationContext == null)
            {
                throw new ArgumentNullException(nameof(validationContext));
            }
            validationContext.CartAggregate = this;

            EnsureCartExists();
            var result = await AbstractTypeFactory <CartValidator> .TryCreateInstance().ValidateAsync(validationContext, options => options.IncludeRuleSets(ruleSet));

            if (!result.IsValid)
            {
                ValidationErrors.AddRange(result.Errors);
            }
            IsValidated = true;
            return(result.Errors);
        }
Пример #11
0
        }         // constructor

        public void Init(List <string> oValidationErrors)
        {
            if (oValidationErrors != null)
            {
                ValidationErrors.AddRange(oValidationErrors);
            }

            if (DecisionStatus == DecisionStatus.Affirmative)
            {
                Comment = string.Format("customer data has been fully loaded");
            }
            else
            {
                Comment = string.Format(
                    "customer data has not been fully loaded: {0}",
                    string.Join("; ", ValidationErrors)
                    );
            }     // if
        }         // Init
Пример #12
0
        public virtual async Task <CartAggregate> AddItemAsync(NewCartItem newCartItem)
        {
            EnsureCartExists();

            if (newCartItem == null)
            {
                throw new ArgumentNullException(nameof(newCartItem));
            }

            var validationResult = await AbstractTypeFactory <NewCartItemValidator> .TryCreateInstance().ValidateAsync(newCartItem, options => options.IncludeRuleSets(ValidationRuleSet));

            if (!validationResult.IsValid)
            {
                ValidationErrors.AddRange(validationResult.Errors);
            }
            else if (newCartItem.CartProduct != null)
            {
                var lineItem = _mapper.Map <LineItem>(newCartItem.CartProduct);
                lineItem.Quantity = newCartItem.Quantity;

                if (newCartItem.Price != null)
                {
                    lineItem.ListPrice = newCartItem.Price.Value;
                    lineItem.SalePrice = newCartItem.Price.Value;
                }
                else
                {
                    SetLineItemTierPrice(newCartItem.CartProduct.Price, newCartItem.Quantity, lineItem);
                }

                if (!string.IsNullOrEmpty(newCartItem.Comment))
                {
                    lineItem.Note = newCartItem.Comment;
                }

                CartProducts[newCartItem.CartProduct.Id] = newCartItem.CartProduct;
                await SetItemFulfillmentCenterAsync(lineItem, newCartItem.CartProduct);
                await InnerAddLineItemAsync(lineItem, newCartItem.CartProduct, newCartItem.DynamicProperties);
            }

            return(this);
        }
Пример #13
0
        protected override string Validate(string columnName)
        {
            var result = base.Validate(columnName);

            foreach (var ingredient in Ingredients)
            {
                ingredient.ValidationErrors.Clear();

                ingredient.ValidationOnSaving = true;
                ingredient.OnPropertyChanged(string.Empty);
                ingredient.ValidationOnSaving = false;

                var newErrors =
                    ingredient.ValidationErrors.Where(x => ValidationErrors.All(t => t.PropertyName != x.PropertyName));

                ValidationErrors.AddRange(newErrors);
            }

            return(result);
        }
Пример #14
0
        public virtual async Task <CartAggregate> ChangeItemQuantityAsync(ItemQtyAdjustment qtyAdjustment)
        {
            EnsureCartExists();

            var validationResult = await AbstractTypeFactory <ItemQtyAdjustmentValidator> .TryCreateInstance().ValidateAsync(qtyAdjustment, options => options.IncludeRuleSets(ValidationRuleSet));

            if (!validationResult.IsValid)
            {
                ValidationErrors.AddRange(validationResult.Errors);
            }

            var lineItem = Cart.Items.FirstOrDefault(i => i.Id == qtyAdjustment.LineItemId);

            if (lineItem != null)
            {
                SetLineItemTierPrice(qtyAdjustment.CartProduct.Price, qtyAdjustment.NewQuantity, lineItem);

                lineItem.Quantity = qtyAdjustment.NewQuantity;
            }

            return(this);
        }
Пример #15
0
        }         // constructor

        public void Init(decimal nOfferedCreditLine, IEnumerable <string> oValidationErrors = null)
        {
            if (oValidationErrors != null)
            {
                ValidationErrors.AddRange(oValidationErrors);
            }

            OfferedCreditLine = nOfferedCreditLine;

            var os = new StringBuilder();

            os.AppendFormat("system calculated sum is {0}", OfferedCreditLine);

            if (DecisionStatus == DecisionStatus.Affirmative)
            {
                os.Append("; data has been fully loaded");
            }
            else
            {
                os.AppendFormat("; data has not been fully loaded: {0}", string.Join("; ", ValidationErrors));
            }

            Comment = os.ToString();
        }         // Init
 public DataAnnotationsValidationResult AddRange(IEnumerable <ValidationError> validationErrors)
 {
     ValidationErrors.AddRange(validationErrors);
     return(this);
 }
Пример #17
0
 public void AddErrors(List <ValidationError> errors)
 {
     ValidationErrors.AddRange(errors.Where(v => !ValidationErrors.Any(e => e.ErrorMessage == v.ErrorMessage)));
 }
Пример #18
0
        /// <summary>
        /// Saves the data record and all its child records, creating a new record if necessary
        /// </summary>
        public virtual bool Save(SqlTransaction trans, SqlConnection conn)
        {
            ReadOnly ro = (ReadOnly)Attribute.GetCustomAttribute(this.GetType(), typeof(ReadOnly));

            if (ro != null)
            {
                throw new DataException("Data is marked as ReadOnly");
            }

            if (!IsValid())
            {
                return(false);
            }

            if (!CanSave())
            {
                ValidationErrors.Add("Table " + SafeTableName + " must have either an identity field defined or a primary key field with valid data");
                return(false);
            }

            if (conn == null)
            {
                conn = new SqlConnection(SQLDMGlobal.ConnectionString());
            }
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            SqlCommand cmd = conn.CreateCommand();

            bool TransactionExists = true;

            if (trans == null)
            {
                TransactionExists = false;
                trans             = conn.BeginTransaction();
            }
            cmd.Transaction = trans;

            try
            {
                if (IsDirty)
                {
                    if (IsNew)
                    {
                        cmd.CommandText = SQLForCreate();
                        cmd.Parameters.AddRange(AllDirtyParameters(true).ToArray());
                    }
                    else
                    {
                        cmd.CommandText = SQLForUpdate(null);
                        cmd.Parameters.AddRange(AllDirtyParameters(false).ToArray());
                    }

                    SqlDataReader rs = cmd.ExecuteReader();
                    if (rs.Read() && IdentityField != null)
                    {
                        IdentityField.Value = rs.GetValue(0);
                    }
                    IsNew = false;
                    rs.Close();

                    cmd.Parameters.Clear();

                    foreach (DataField f in Fields)
                    {
                        f.OriginalValue = f.Value;
                    }
                }

                if (ChildRecords != null)
                {
                    foreach (DataRecord r in ChildRecords)
                    {
                        if (!r.Save(trans, conn))
                        {
                            ValidationErrors.AddRange(r.ValidationErrors);
                            throw new DataException("Validation error while saving to " + r.SafeTableName);
                        }
                    }
                }

                if (!TransactionExists)
                {
                    trans.Commit();
                    conn.Close();
                }

                if (Saved != null)
                {
                    Saved(this);
                }
            }
            catch (DataException ex)
            {
                if (!TransactionExists)
                {
                    ValidationErrors.Add(ex.Message);
                    trans.Rollback();
                }
                else
                {
                    throw;
                }
            }

            return(ValidationErrors.IsValid);
        }
Пример #19
0
        public bool Delete(SqlTransaction trans, SqlConnection conn)
        {
            ValidationErrors.Clear();

            if (IsDeleted)
            {
                return(true);
            }

            DataField idField = IdentityField;

            if (idField == null)
            {
                ValidationErrors.Add("Record does not exist");
                return(false);
            }

            if (conn == null)
            {
                conn = new SqlConnection(SQLDMGlobal.ConnectionString());
            }
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            SqlCommand cmd = conn.CreateCommand();

            bool TransactionExists = true;

            if (trans == null)
            {
                TransactionExists = false;
                trans             = conn.BeginTransaction();
            }
            cmd.Transaction = trans;

            try
            {
                foreach (DataRecord r in ChildRecords)
                {
                    if (!r.Delete(trans, conn))
                    {
                        ValidationErrors.AddRange(r.ValidationErrors);
                        throw new DataException("Validation error while saving to " + r.SafeTableName);
                    }
                }

                cmd.CommandText = SQLForDelete(idField);
                cmd.Parameters.Add(idField);
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();

                if (!TransactionExists)
                {
                    trans.Commit();
                    conn.Close();
                }

                IsDeleted = true;

                Deleted(this);
            }
            catch (DataException ex)
            {
                if (!TransactionExists)
                {
                    trans.Rollback();
                }

                ValidationErrors.Add(ex.Message);
            }

            return(ValidationErrors.IsValid);
        }
Пример #20
0
 public void AddError(IEnumerable <ValidationResult> validationResults)
 {
     ValidationErrors.AddRange(validationResults);
 }
Пример #21
0
 public void Merge <U>(Results <U> results) where U : new()
 {
     Exceptions.AddRange(results.Exceptions);
     ValidationErrors.AddRange(results.ValidationErrors);
 }