public void ContextNarrowing() { Inventor context = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); ConditionValidator cv1 = new ConditionValidator("DOB.Year == 1856", null); ConditionValidator cv2 = new ConditionValidator("Year == 1856", null); StaticListableObjectFactory factory = new StaticListableObjectFactory(); factory.AddObject("cv1", cv1); factory.AddObject("cv2", cv2); ValidatorReference v1 = new ValidatorReference(); v1.ObjectFactory = factory; v1.Name = "cv1"; IValidationErrors errors = new ValidationErrors(); Assert.IsTrue(v1.Validate(context, null, errors)); Assert.IsTrue(v1.Validate(context, errors)); ValidatorReference v2 = new ValidatorReference(); v2.ObjectFactory = factory; v2.Name = "cv2"; v2.Context = Expression.Parse("DOB"); Assert.IsTrue(v2.Validate(context, null, errors)); Assert.IsTrue(v2.Validate(context, errors)); ValidatorReference v3 = new ValidatorReference("false"); v3.ObjectFactory = factory; v3.Name = "cv2"; v3.Context = Expression.Parse("DOB"); Assert.IsTrue(v3.Validate(null, errors)); }
public void ResolveErrorsWithoutMessageSource() { ValidationErrors errors = new ValidationErrors(); errors.AddError(string.Empty, ErrorMessageOne); IList<string> resolvedErrors = errors.GetResolvedErrors(string.Empty, null); Assert.AreEqual(ErrorMessageOne.Id, (string)resolvedErrors[0]); }
public void AddErrorSunnyDay() { IValidationErrors errors = new ValidationErrors(); errors.AddError(GoodErrorKey, ErrorMessageOne); Assert.IsFalse(errors.IsEmpty); Assert.IsNotNull(errors.GetErrors(GoodErrorKey)); Assert.AreEqual(1, errors.GetErrors(GoodErrorKey).Count); }
protected void ctlInsert_Click(object sender, ImageClickEventArgs e) { DbHoliday holiday; try { if (Mode.Equals(FlagEnum.EditFlag)) { holiday = ScgDbQueryProvider.DbHolidayQuery.FindByIdentity(HolidayId); } else { holiday = new DbHoliday(); } Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); try { if (!string.IsNullOrEmpty(ctlDate.DateValue)) { holiday.Date = UIHelper.ParseDate(ctlDate.DateValue).Value; } } catch { errors.AddError("HolidayProfile.Error", new Spring.Validation.ErrorMessage("UniqueHolidayProfile")); throw new ServiceValidationException(errors); } holiday.HolidayProfileId = Int32.Parse(ctlHolidayProfileIDHidden.Value); holiday.Description = ctlDescription.Text; holiday.CreBy = UserAccount.UserID; holiday.CreDate = DateTime.Now; holiday.UpdBy = UserAccount.UserID; holiday.UpdDate = DateTime.Now; holiday.UpdPgm = UserAccount.CurrentLanguageCode; if (Mode.Equals(FlagEnum.EditFlag)) { DbHolidayService.UpdateHoliday(holiday); } else { DbHolidayService.AddHoliday(holiday); } Notify_Ok(sender, e); } catch (ServiceValidationException ex) { this.ValidationErrors.MergeErrors(ex.ValidationErrors); } catch (NullReferenceException) { //Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); //errors.AddError("InternalOrder.Error", new ErrorMessage("CostCenter and Company Require.")); //ValidationErrors.MergeErrors(errors); //return; } }
public void FalseValidatorReferenceNotEvaluatedBecauseWhenExpressionReturnsFalse() { StaticListableObjectFactory factory = new StaticListableObjectFactory(); factory.AddObject("validator", new FalseValidator()); ValidatorReference v = new ValidatorReference("false"); v.ObjectFactory = factory; v.Name = "validator"; IValidationErrors errors = new ValidationErrors(); Assert.IsTrue(v.Validate(null, null, errors)); Assert.IsTrue(v.Validate(null, errors)); }
public void FalseValidatorReference() { StaticListableObjectFactory factory = new StaticListableObjectFactory(); factory.AddObject("validator", new FalseValidator()); ValidatorReference v = new ValidatorReference(); v.ObjectFactory = factory; v.Name = "validator"; IValidationErrors errors = new ValidationErrors(); Assert.IsFalse(v.Validate(null, null, errors)); Assert.IsFalse(v.Validate(null, errors)); }
public void WhenAllValidatorsReturnTrue() { ValidatorGroup vg = new ValidatorGroup("true"); vg.Validators.Add(new TrueValidator()); vg.Validators.Add(new TrueValidator()); vg.Validators.Add(new TrueValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsTrue(valid, "Validation should succeed when all inner validators return true."); Assert.AreEqual(0, errors.GetErrors("errors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); }
public void WhenAllValidatorsReturnFalse() { ValidatorGroup vg = new ValidatorGroup(); vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new FalseValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsFalse(valid, "Validation should fail when all inner validators return false."); Assert.AreEqual(3, errors.GetErrors("errors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); }
private void CheckDataValueUpdate(DbCostCenter costCenter) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); if (string.IsNullOrEmpty(costCenter.CostCenterCode)) { errors.AddError("CostCenter.Error", new Spring.Validation.ErrorMessage("RequiredCostCenterCode")); } if (string.IsNullOrEmpty(costCenter.CompanyCode)) { errors.AddError("CostCenter.Error", new Spring.Validation.ErrorMessage("RequiredCompanyCode")); } if ((CostCenterCode.ToString() != ctlTextBoxCostCenterCode.Text) && (ScgDbQueryProvider.DbCostCenterQuery.IsDuplicateCostCenterCode(costCenter))) { errors.AddError("CostCenter.Error", new Spring.Validation.ErrorMessage("DuplicationCostCenterCode")); } if (!errors.IsEmpty) { throw new ServiceValidationException(errors); } }
/// <summary> /// Intercepts method invocation and validates arguments. /// </summary> /// <param name="method"> /// Method invocation. /// </param> /// <param name="args"> /// Method arguments. /// </param> /// <param name="target"> /// Target object. /// </param> /// <exception cref="ValidationException"> /// If one or more method arguments fail validation. /// </exception> public void Before(MethodInfo method, object[] args, object target) { ValidationErrors errors = new ValidationErrors(); ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { ParameterInfo info = parameters[i]; ValidatedAttribute[] attributes = (ValidatedAttribute[]) info.GetCustomAttributes(typeof(ValidatedAttribute), true); foreach (ValidatedAttribute attribute in attributes) { // throws NoSuchObjectDefinitionException if validator cannot be found IValidator validator = (IValidator) applicationContext.GetObject(attribute.ValidatorName); validator.Validate(args[i], errors); } } if (!errors.IsEmpty) { throw new ValidationException(errors); } }
//protected void ctlCostCenterField_OnObjectLookUpReturn(object sender, ObjectLookUpReturnArgs e) //{ // DbCostCenter costCenter = (DbCostCenter)e.ObjectReturn; // if (costCenter != null) // { // DbCostCenter dbCost = ScgDbQueryProvider.DbCostCenterQuery.FindProxyByIdentity(costCenter.CostCenterID); // if (dbCost != null) // { // ctlCompanyCode.Text = dbCost.CompanyID.CompanyCode.ToString(); // ctlCompanyName.Text = dbCost.CompanyID.CompanyName; // } // } // ctlIOUpdatePanel.Update(); //} private void CheckDataValueUpdate(DbInternalOrder io) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); if (string.IsNullOrEmpty(io.IONumber)) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("RequiredIONumber")); } if (string.IsNullOrEmpty(io.IOType)) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("RequiredIOType")); } if (string.IsNullOrEmpty(io.IOText)) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("RequiredIOText")); } if (io.CompanyID == null || io.CompanyID <= 0) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("RequiredCompany")); } if (!(io.ExpireDate == null || io.EffectiveDate == null)) { if (io.ExpireDate < io.EffectiveDate) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("ExpireDateMustBeMoreThanEffectiveDate")); } } if (DbIOService.IsExistIO(io) && Mode.Equals(FlagEnum.NewFlag)) { errors.AddError("InternalOrder.Error", new Spring.Validation.ErrorMessage("Duplicate IO Code")); } if (!errors.IsEmpty) { throw new ServiceValidationException(errors); } }
public void HandledTypeConversionExceptionTargetToSource() { BaseBindingManager dbm = new BaseBindingManager(); IValidationErrors errors = new ValidationErrors(); Inventor st = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); st.Inventions = new string[] {"Invention One", "Invention Two"}; SimpleExpressionBinding binding = new SimpleExpressionBinding("pob", "DOB"); binding.SetErrorMessage("error", "errors"); dbm.AddBinding(binding); dbm.BindTargetToSource(st, st, errors); Assert.IsFalse(binding.IsValid(errors)); Assert.IsFalse(errors.IsEmpty); Assert.AreEqual(1, errors.GetErrors("errors").Count); // make sure that the old value doesn't override current invalid value dbm.BindSourceToTarget(st, st, errors); Assert.AreEqual(new DateTime(1856, 7, 9), st.DOB); }
public void ResolvesAndRendersValidationErrorsUsingExplicitlySpecifiedErrorsAndMessageSource() { TestValidationControl vc = new TestValidationControl(); vc.ID = "TestControl"; Page page = new Page(); page.Controls.Add(vc); ValidationErrors errors = new ValidationErrors(); errors.AddError(vc.Provider, new ErrorMessage("msgId")); vc.ValidationErrors = errors; StaticMessageSource msgSrc = new StaticMessageSource(); msgSrc.AddMessage("msgId", CultureInfo.CurrentUICulture, "Resolved Message Text"); vc.MessageSource = msgSrc; vc.TestRender(null); Assert.AreEqual("Resolved Message Text", vc.LastErrorsRendered[0]); }
public void HandledTypeConversionExceptionSourceToTarget() { BaseBindingManager dbm = new BaseBindingManager(); IValidationErrors errors = new ValidationErrors(); Hashtable source = new Hashtable(); source["boolValue"] = false; Inventor target = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); SimpleExpressionBinding binding = new SimpleExpressionBinding("['boolValue']", "DOB"); binding.SetErrorMessage("error", "errors"); dbm.AddBinding(binding); dbm.BindSourceToTarget(source, target, errors); Assert.IsFalse(binding.IsValid(errors)); Assert.IsFalse(errors.IsEmpty); Assert.AreEqual(1, errors.GetErrors("errors").Count); // make sure that the old value doesn't override current invalid value dbm.BindTargetToSource(source, target, errors); Assert.AreEqual(false, source["boolValue"]); }
protected void ctlButtonSave_Click(object sender, EventArgs e) { if (Mode == FlagEnum.EditFlag) { DbCostCenter costCenter = DbCostCenterService.FindByIdentity(CostCenterID); costCenter.ActualPrimaryCosts = ctlChkLock.Checked; costCenter.Active = ctlChkActive.Checked; costCenter.CompanyCode = ctlCompanyTextboxAutoComplete.Text; costCenter.Description = ctlTextBoxDescription.Text; //costCenter.CostCenterCode = ctlTextBoxCostCenterCode.Text; costCenter.BusinessArea = ctlBusinessArea.Text; costCenter.ProfitCenter = ctlProfitCenter.Text; try { costCenter.Valid = UIHelper.ParseDate(ctlCalendarValid.DateValue).Value; costCenter.Expire = UIHelper.ParseDate(ctlCalendarExpire.DateValue).Value; } catch (Exception) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); errors.AddError("CostCenter.Error", new ErrorMessage("Invalid or Null in Datetime fields.")); ValidationErrors.MergeErrors(errors); //return; } costCenter.UpdBy = UserAccount.UserID; costCenter.UpdDate = DateTime.Now.Date; costCenter.UpdPgm = ProgramCode; try { CheckDataValueUpdate(costCenter); DbCostCenterService.UpdateCostCenter(costCenter); DbCostCenterService.UpdateCostCenterToExp(costCenter); } catch (ServiceValidationException ex) { ValidationErrors.MergeErrors(ex.ValidationErrors); return; } } if (Mode == FlagEnum.NewFlag) { DbCostCenter costCenter = new DbCostCenter(); costCenter.CompanyID = new DbCompany(); costCenter.ActualPrimaryCosts = ctlChkLock.Checked; costCenter.Active = ctlChkActive.Checked; costCenter.CompanyCode = ctlCompanyTextboxAutoComplete.Text; costCenter.Description = ctlTextBoxDescription.Text; costCenter.CostCenterCode = ctlTextBoxCostCenterCode.Text; costCenter.BusinessArea = ctlBusinessArea.Text; costCenter.ProfitCenter = ctlProfitCenter.Text; try { costCenter.Valid = UIHelper.ParseDate(ctlCalendarValid.DateValue).Value; costCenter.Expire = UIHelper.ParseDate(ctlCalendarExpire.DateValue).Value; } catch (Exception) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); errors.AddError("CostCenter.Error", new ErrorMessage("Invalid or Null in Datetime fields.")); ValidationErrors.MergeErrors(errors); //return; } costCenter.UpdBy = UserAccount.UserID; costCenter.UpdDate = DateTime.Now.Date; costCenter.UpdPgm = ProgramCode; costCenter.CreBy = UserAccount.UserID; costCenter.CreDate = DateTime.Now.Date; try { CheckDataValueInsert(costCenter); DbCostCenterService.AddCostCenter(costCenter); } catch (ServiceValidationException ex) { ValidationErrors.MergeErrors(ex.ValidationErrors); return; } } HidePopUp(); Notify_Ok(sender, e); }
public void TestNestingCollectionValidatorWithXMLDescription() { const string xml = @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'> <v:group id='validatePerson' when='T(Spring.Objects.TestObject) == #this.GetType()'> <v:required id ='req' when='true' test='Name'/> <v:regex id ='reg' test='Name'> <v:property name='Expression' value='[a-z]*\s[a-z]*'/> <v:property name='Options' value='IgnoreCase'/> <v:message id='reg1' providers='regExpr' when='true'> <v:param value='#this.ToString()'/> </v:message> </v:regex> </v:group> <v:group id='validator'> <v:collection id='collectionValidator' validate-all='true' context='Members' include-element-errors='true'> <v:message id='coll1' providers='membersCollection' when='true'> <v:param value='#this.ToString()'/> </v:message> <v:ref name='validatePerson'/> </v:collection> </v:group> </objects>"; MemoryStream stream = new MemoryStream(new UTF8Encoding().GetBytes(xml)); IResource resource = new InputStreamResource(stream, "collection validator test"); XmlObjectFactory objectFactory = new XmlObjectFactory(resource, null); ValidatorGroup validator = (ValidatorGroup) objectFactory.GetObject("validator"); Society soc = new Society(); soc.Members.Add(new TestObject("Damjan Tomic", 24)); soc.Members.Add(new TestObject("Goran Milosavljevic", 24)); soc.Members.Add(new TestObject("Ivan Cikic", 28)); IValidationErrors err1 = new ValidationErrors(); Assert.IsTrue(validator.Validate(soc, err1)); soc.Members.Add(new TestObject("foo", 30)); soc.Members.Add(new TestObject("bar", 30)); Assert.IsFalse(validator.Validate(soc, err1)); }
private static void WhenSingleValidatorReturnsTrue(AnyValidatorGroup vg) { vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new TrueValidator()); vg.Validators.Add(new FalseValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsTrue(valid, "Validation should succeed when single inner validator returns true."); Assert.AreEqual(0, errors.GetErrors("errors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); }
public void WhenSingleValidatorReturnsTrue() { ExclusiveValidatorGroup vg = new ExclusiveValidatorGroup(Expression.Parse("true")); vg.Actions.Add(new ErrorMessageAction("exclusiveError", "exclusiveErrors")); vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new TrueValidator()); vg.Validators.Add(new FalseValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsTrue(valid, "Validation should succeed when single inner validator returns true."); Assert.AreEqual(0, errors.GetErrors("errors").Count); Assert.AreEqual(0, errors.GetErrors("exclusiveErrors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); // ALL validators are called Assert.IsTrue( ((BaseTestValidator)vg.Validators[0]).WasCalled ); Assert.IsTrue( ((BaseTestValidator)vg.Validators[1]).WasCalled ); Assert.IsTrue( ((BaseTestValidator)vg.Validators[2]).WasCalled ); }
public void AddErrorWithNullKey() { IValidationErrors errors = new ValidationErrors(); Assert.Throws<ArgumentNullException>(() => errors.AddError(null, ErrorMessageOne)); }
public void AddErrorWithNullKey() { IValidationErrors errors = new ValidationErrors(); errors.AddError(null, ErrorMessageOne); }
public void TestDifferentCollectionTypes() { const string xml = @"<?xml version='1.0' encoding='UTF-8' ?> <objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'> <v:group id='validatePerson' when='T(Spring.Objects.TestObject) == #this.GetType()'> <v:required id ='req' when='true' test='Name'/> <v:regex id ='reg' test='Name'> <v:property name='Expression' value='[a-z]*\s[a-z]*'/> <v:property name='Options' value='IgnoreCase'/> <v:message id='reg1' providers='regularni' when='true'> <v:param value='#this.ToString()'/> </v:message> </v:regex> </v:group> <v:collection id='collectionValidator' validate-all='true'> <v:ref name='validatePerson'/> </v:collection> </objects>"; MemoryStream stream = new MemoryStream(new UTF8Encoding().GetBytes(xml)); IResource resource = new InputStreamResource(stream, "collectionValidator"); XmlObjectFactory objectFactory = new XmlObjectFactory(resource, null); CollectionValidator validator = (CollectionValidator) objectFactory.GetObject("collectionValidator"); IList listPersons = new ArrayList(); IDictionary dictPersons = new Hashtable(); ISet setPersons = new ListSet(); listPersons.Add(new TestObject("DAMJAN Tomic", 24)); listPersons.Add(new TestObject("Goran Milosavljevic", 24)); listPersons.Add(new TestObject("Ivan CIKIC", 28)); dictPersons.Add(1, listPersons[0]); dictPersons.Add(2, listPersons[1]); dictPersons.Add(3, listPersons[2]); setPersons.AddAll(listPersons); IValidationErrors ve = new ValidationErrors(); Assert.IsTrue(validator.Validate(listPersons, ve)); Assert.IsTrue(ve.IsEmpty); Assert.IsTrue(validator.Validate(dictPersons, ve)); Assert.IsTrue(ve.IsEmpty); Assert.IsTrue(validator.Validate(setPersons, ve)); Assert.IsTrue(ve.IsEmpty); }
public void MergeErrors() { ValidationErrors otherErrors = new ValidationErrors(); const string anotherKey = "anotherKey"; otherErrors.AddError(anotherKey, ErrorMessageTwo); otherErrors.AddError(GoodErrorKey, ErrorMessageTwo); IValidationErrors errors = new ValidationErrors(); errors.AddError(GoodErrorKey, ErrorMessageOne); errors.MergeErrors(otherErrors); Assert.IsFalse(errors.IsEmpty); IList<ErrorMessage> mergedErrors = errors.GetErrors(GoodErrorKey); Assert.IsNotNull(mergedErrors); Assert.AreEqual(2, mergedErrors.Count); Assert.AreEqual(ErrorMessageOne, mergedErrors[0]); Assert.AreEqual(ErrorMessageTwo, mergedErrors[1]); IList<ErrorMessage> otherErrorsForKey = errors.GetErrors(anotherKey); Assert.IsNotNull(otherErrorsForKey); Assert.AreEqual(1, otherErrorsForKey.Count); Assert.AreEqual(ErrorMessageTwo, otherErrorsForKey[0]); }
/// <summary> /// Validates the specified object. /// </summary> /// <param name="contextParams">Additional context parameters.</param> /// <param name="errors"><see cref="ValidationErrors"/> instance to add error messages to.</param> /// <param name="validationContext">The object to validate.</param> /// <returns><c>True</c> if validation was successful, <c>False</c> otherwise.</returns> protected override bool ValidateGroup(IDictionary<string, object> contextParams, IValidationErrors errors, object validationContext) { // capture errors in separate collection to only add them to the error collector in case of errors ValidationErrors tmpErrors = new ValidationErrors(); bool valid = false; foreach (IValidator validator in Validators) { valid = validator.Validate(validationContext, contextParams, tmpErrors) || valid; if (valid && FastValidate) { break; } } if (!valid) { errors.MergeErrors(tmpErrors); } return valid; }
protected void ctlAdd_Click(object sender, ImageClickEventArgs e) { Dbpb pb = new Dbpb(); if (Mode.Equals(FlagEnum.EditFlag)) { pb.Pbid = PBID; } pb.PBCode = ctlPBCode.Text; pb.Supplementary = ctlSupplementary.Text; pb.Active = ctlActive.Checked; pb.UpdBy = UserAccount.UserID; pb.UpdDate = DateTime.Now; pb.UpdPgm = UserAccount.CurrentLanguageCode; pb.CreDate = DateTime.Now; pb.CreBy = UserAccount.UserID; pb.CurrencyID = UIHelper.ParseLong(ctlMainCurrencyDropdown.SelectedValue); pb.RepOffice = ctlRepOffice.Checked; if (!string.IsNullOrEmpty(ctlMainCurrencyDropdown.SelectedValue)) { pb.MainCurrencyID = UIHelper.ParseShort(ctlMainCurrencyDropdown.SelectedValue); } try { pb.PettyCashLimit = UIHelper.ParseDouble(ctlPettyCashLimit.Text); DbCompany com = ScgDbQueryProvider.DbCompanyQuery.FindByIdentity(UIHelper.ParseLong(ctlCompanyField.CompanyID)); pb.CompanyCode = com.CompanyCode; pb.CompanyID = com; } catch (Exception) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); errors.AddError("PB.Error", new ErrorMessage("Check For Petty Cash Limit or Company Code.")); ValidationErrors.MergeErrors(errors); return; } try { // save or update PB if (Mode.Equals(FlagEnum.EditFlag)) { DbPBService.UpdatePB(pb, PbDataSet); } else { long PBId = DbPBService.AddPB(pb, PbDataSet); pb.Pbid = PBId; } // save or update PBlang IList <DbpbLang> list = new List <DbpbLang>(); foreach (GridViewRow row in ctlPBEditorGrid.Rows) { short languageId = UIHelper.ParseShort(ctlPBEditorGrid.DataKeys[row.RowIndex]["LanguageID"].ToString()); TextBox Description = row.FindControl("ctrDescription") as TextBox; TextBox Comment = (TextBox)row.FindControl("ctrComment") as TextBox; CheckBox Active = (CheckBox)row.FindControl("ctlActive") as CheckBox; //comment by oum 02/06/2009 //ไม่ต้อง check description is null or empty เพราะว่าไม่ใช่ require field //if ((!string.IsNullOrEmpty(Description.Text))) //{ DbpbLang pbLang = new DbpbLang(); pbLang.Active = Active.Checked; pbLang.CreBy = UserAccount.UserID; pbLang.CreDate = DateTime.Now; pbLang.Description = Description.Text; pbLang.Comment = Comment.Text; pbLang.LanguageID = new DbLanguage(languageId); pbLang.PBID = pb; pbLang.UpdBy = UserAccount.UserID; pbLang.UpdDate = DateTime.Now; pbLang.UpdPgm = UserAccount.CurrentLanguageCode; list.Add(pbLang); //} } if (Mode.Equals(FlagEnum.EditFlag)) { DbPBLangService.UpdatePBLang(list); } if (Mode.Equals(FlagEnum.NewFlag)) { DbPBLangService.AddPBLang(list); } Notify_Ok(sender, e); } catch (ServiceValidationException ex) { this.ValidationErrors.MergeErrors(ex.ValidationErrors); } //} }
public void WhenSingleValidatorReturnsTrue() { ValidatorGroup vg = new ValidatorGroup(Expression.Parse("true")); vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new TrueValidator()); vg.Validators.Add(new FalseValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsFalse(valid, "Validation should fail when single inner validator returns true."); Assert.AreEqual(2, errors.GetErrors("errors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); }
public void EmptyErrorsReturnEmptyCollections() { IValidationErrors errors = new ValidationErrors(); IList<ErrorMessage> typedErrors = errors.GetErrors("xyz"); Assert.IsNotNull(typedErrors); Assert.AreEqual(0, typedErrors.Count); IList<string> resolvedErrors = errors.GetResolvedErrors("xyz", new NullMessageSource()); Assert.IsNotNull(resolvedErrors); Assert.AreEqual(0, resolvedErrors.Count); }
public void TestValidationErrorsAreCollected() { IList persons = new ArrayList(); persons.Add(new TestObject(null, 24)); persons.Add(new TestObject("Goran Milosavljevic", 24)); persons.Add(new TestObject("Ivan Cikic", 28)); persons.Add(new TestObject(null, 20)); RequiredValidator req = new RequiredValidator("Name", "true"); req.Actions.Add(new ErrorMessageAction("1", new string[] { "firstProvider", "secondProvider" })); CollectionValidator validator = new CollectionValidator(true,true); validator.Validators.Add(req); IValidationErrors ve = new ValidationErrors(); Assert.IsFalse(validator.Validate(persons, ve)); Assert.IsFalse(ve.IsEmpty); }
public void MergeErrorsWithNull() { IValidationErrors errors = new ValidationErrors(); errors.AddError(GoodErrorKey, ErrorMessageOne); errors.AddError(GoodErrorKey, ErrorMessageTwo); errors.MergeErrors(null); // must be unchanged with no Exception thrown... Assert.IsFalse(errors.IsEmpty); Assert.IsNotNull(errors.GetErrors(GoodErrorKey)); Assert.AreEqual(2, errors.GetErrors(GoodErrorKey).Count); }
/// <summary> /// Actual implementation how to validate the specified object. /// </summary> /// <param name="validationContext">The object to validate.</param> /// <param name="contextParams">Additional context parameters.</param> /// <param name="errors"><see cref="ValidationErrors"/> instance to add error messages to.</param> /// <returns><c>True</c> if validation was successful, <c>False</c> otherwise.</returns> protected override bool ValidateGroup(IDictionary contextParams, IValidationErrors errors, object validationContext) { ValidationErrors tmpErrors = new ValidationErrors(); bool valid = false; foreach (IValidator validator in Validators) { bool tmpValid = validator.Validate(validationContext, contextParams, tmpErrors); if (valid && tmpValid) { valid = false; if (this.FastValidate) { break; } } else if (tmpValid) { valid = true; } } if (!valid) { errors.MergeErrors(tmpErrors); } return valid; }
public void SerializeErrors() { ValidationErrors errors = new ValidationErrors(); ErrorMessageOne = new ErrorMessage("Kissing Leads To Brain Disease", new object[] {"Param11", 5, "Param13"}); ErrorMessageTwo = new ErrorMessage("This Is Eva Green", new object[] { "Param21", 'g' , new object[] {"Goran", "Milosavljevic"} }); ErrorMessage ErrorMessageThree = new ErrorMessage("Third error message", null); ErrorMessage ErrorMessageFour = new ErrorMessage("Fourth error message", new object[]{}); errors.AddError("key1", ErrorMessageOne); errors.AddError("key1", ErrorMessageTwo); errors.AddError("key2", ErrorMessageThree); errors.AddError("key3", ErrorMessageFour); Stream streamBefore = new MemoryStream(); Stream streamAfter = new MemoryStream(); // serialize ValidationErrors XmlSerializer serializer = new XmlSerializer(typeof(ValidationErrors)); serializer.Serialize(streamBefore, errors); streamBefore.Position = 0; // deserialize ValidationErrors ValidationErrors result = (ValidationErrors) serializer.Deserialize(streamBefore); // serialize ValidationErrors serializer.Serialize(streamAfter, result); // compare ValidationErrors instances byte[] byteBefore = new byte[streamBefore.Length]; byte[] byteAfter = new byte[streamAfter.Length]; Assert.AreEqual(byteAfter.Length, byteBefore.Length); streamBefore.Position = 0; streamAfter.Position = 0; streamBefore.Read(byteBefore, 0, (int) streamBefore.Length); streamAfter.Read(byteAfter, 0, (int) streamAfter.Length); Assert.AreEqual(byteBefore, byteAfter); }
public void WhenMultipleValidatorsReturnTrueAndNotFastValidate() { ExclusiveValidatorGroup vg = new ExclusiveValidatorGroup(Expression.Parse("true")); vg.FastValidate = false; IValidationErrors errors = new ValidationErrors(); WhenMultipleValidatorsReturnTrue(vg, errors); // ALL validators are called Assert.AreEqual(2, errors.GetErrors("errors").Count); Assert.IsTrue( ((BaseTestValidator)vg.Validators[0]).WasCalled ); Assert.IsTrue( ((BaseTestValidator)vg.Validators[1]).WasCalled ); Assert.IsTrue( ((BaseTestValidator)vg.Validators[2]).WasCalled ); Assert.IsTrue( ((BaseTestValidator)vg.Validators[3]).WasCalled ); }
public void ContainsNoErrorsDirectlyAfterInstantiation() { IValidationErrors errors = new ValidationErrors(); Assert.IsTrue(errors.IsEmpty); Assert.IsNotNull(errors.GetErrors(GoodErrorKey)); }
public void WhenGroupIsNotValidatedBecauseWhenExpressionReturnsFalse() { ExclusiveValidatorGroup vg = new ExclusiveValidatorGroup("false"); vg.Validators.Add(new FalseValidator()); vg.Validators.Add(new FalseValidator()); IValidationErrors errors = new ValidationErrors(); errors.AddError("existingErrors", new ErrorMessage("error", null)); bool valid = vg.Validate(new object(), errors); Assert.IsTrue(valid, "Validation should succeed when group validator is not evaluated."); Assert.AreEqual(0, errors.GetErrors("errors").Count); Assert.AreEqual(1, errors.GetErrors("existingErrors").Count); }
protected void ctlButtonSave_Click(object sender, EventArgs e) { #region create DTO for save Role role = new SuRole(); //role = SuRoleService.FindByIdentity(RoleID); role.Active = ctlCheckboxActive.Checked; role.UpdBy = UserAccount.UserID; role.UpdPgm = base.ProgramCode; if (Mode == FlagEnum.EditFlag) { role.CreBy = UserAccount.UserID; } role.RoleCode = ctlTextBoxGroupCode.Text; role.RoleName = ctlTextBoxGroupName.Text; role.ApproveVerifyDocument = ctlCheckboxApproveVerifyDoc.Checked; role.ReceiveDocument = ctlCheckboxRecieveDoc.Checked; role.VerifyDocument = ctlCheckboxVerifyDoc.Checked; role.ApproveVerifyDocument = ctlCheckboxApproveVerifyDoc.Checked; role.VerifyPayment = ctlCheckBoxVerifyPayment.Checked; role.ApproveVerifyPayment = ctlCheckBoxApproveVerifyPayment.Checked; role.CounterCashier = ctlCheckBoxCounterCashier.Checked; role.AllowMultipleApproveAccountant = ctlCheckboxAllowMultipleApproveAccountant.Checked; role.AllowMultipleApprovePayment = ctlCheckBoxAllowMultipleApprovePayment.Checked; role.UseCustomizationLimitAmount = ctlUseCustomizationLimitAmount.Checked; role.LimitAmountForVerifierChange = UIHelper.ParseDouble(ctlLimitAmountForVerifierChange.Text); try { if (!string.IsNullOrEmpty(ctlTextBoxVerifyMax.Text)) { role.VerifyMaxLimit = UIHelper.ParseDouble(ctlTextBoxVerifyMax.Text); } else { role.VerifyMaxLimit = int.MaxValue; } if (!string.IsNullOrEmpty(ctlTextBoxVerifyMin.Text)) { role.VerifyMinLimit = UIHelper.ParseDouble(ctlTextBoxVerifyMin.Text); } else { role.VerifyMinLimit = 0; } if (!string.IsNullOrEmpty(ctlTextBoxApproveVerifyMax.Text)) { role.ApproveVerifyMaxLimit = UIHelper.ParseDouble(ctlTextBoxApproveVerifyMax.Text); } else { role.ApproveVerifyMaxLimit = int.MaxValue; } if (!string.IsNullOrEmpty(ctlTextBoxApproveVerifyMin.Text)) { role.ApproveVerifyMinLimit = UIHelper.ParseDouble(ctlTextBoxApproveVerifyMin.Text); } else { role.ApproveVerifyMinLimit = 0; } } catch (FormatException) { Spring.Validation.ValidationErrors errors = new Spring.Validation.ValidationErrors(); errors.AddError("Role.Error", new ErrorMessage("Limit-field area be accept numeric only.")); ValidationErrors.MergeErrors(errors); return; } #endregion try { if (Mode == FlagEnum.NewFlag) { SuRoleService.AddRole(role); } else if (Mode == FlagEnum.EditFlag) { role.RoleID = RoleID; SuRoleService.UpdateRole(role); } //Auto computer will refresh workflow permission here. Notify_Ok(sender, e); HidePopUp(); } catch (ServiceValidationException ex) { ValidationErrors.MergeErrors(ex.ValidationErrors); } }