/// <summary> /// Validates this request /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> void IImagingExaminationRequest.Validate(string path, List <ValidationMessage> messages) { var validationBuilder = new ValidationBuilder(path, messages); if (RequesterOrderIdentifier != null) { RequesterOrderIdentifier.Validate(validationBuilder.Path, messages); } if (ReportIdentifier != null) { ReportIdentifier.Validate(validationBuilder.Path, messages); } if (StudyIdentifier != null) { StudyIdentifier.Validate(validationBuilder.Path, messages); } if (LaboratoryTestResultIdentifier != null) { LaboratoryTestResultIdentifier.Validate(validationBuilder.Path, messages); } if (ImageDetails != null && ImageDetails.Any()) { foreach (var imageDetail in ImageDetails) { imageDetail.Validate(validationBuilder.Path, messages); } } }
/// <summary> /// Validates this RequestedService /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); vb.ArgumentRequiredCheck("RequestedServiceDateTime", RequestedServiceDateTime); if (ServiceCommencementWindow != null) { ServiceCommencementWindow.Validate(vb.Path + "ServiceCommencementWindow", vb.Messages); } // var choice1 = new Dictionary<string, object> // { // { "ServiceCommencementWindow", ServiceCommencementWindow }, // { "ServiceScheduled", ServiceScheduled } // }; // // vb.ChoiceCheck(choice1); // if (vb.ArgumentRequiredCheck("RequestedServiceDescription", RequestedServiceDescription)) { if (RequestedServiceDescription != null) { RequestedServiceDescription.ValidateMandatory(vb.Path + "RequestedServiceDescription", vb.Messages); } } vb.ArgumentRequiredCheck("ServiceBookingStatus", ServiceBookingStatus); if (ServiceProvider != null) { ServiceProvider.Validate(vb.Path + "ServiceProvider", vb.Messages); } }
public IHttpContext workhourEdit(IHttpContext context, string workhourId) { try { if (!context.token().hasPermission("workhour.write")) { context.Response.StatusCode = HttpStatusCode.NotFound; context.Response.SendResponse(""); return(context); } ValidationBuilder valBuilder = new ValidationBuilder(); ValidationCollection valCollection; string[] valArray = { "name=StartTime, isRequired=,isTime=", "name=EndTime, isRequired=,isTime=", }; valCollection = valBuilder.build(valArray); WorkHours workhour = BaseController.getUserInput <WorkHours>(context, valCollection); workhour.Id = uint.Parse(workhourId); WorkHours.edit(uint.Parse(context.Request.PathParameters["id"]), workhour); context.Response.SendResponse(""); } catch (Exception ex) { context.Response.StatusCode = HttpStatusCode.InternalServerError; context.Response.SendResponse(ex.Message); } return(context); }
public IHttpContext workhourCreate(IHttpContext context) { try { if (!context.token().hasPermission("workhour.write")) { context.Response.StatusCode = HttpStatusCode.NotFound; context.Response.SendResponse(""); return(context); } ValidationBuilder valBuilder = new ValidationBuilder(); ValidationCollection valCollection; string[] valArray = { "name=StartTime, isRequired=,isTime=", "name=EndTime, isRequired=,isTime=", }; valCollection = valBuilder.build(valArray); var wrkhour = BaseController.getUserInput <WorkHours>(context, valCollection); wrkhour.add(); context.Response.SendResponse(""); } catch (Exception ex) { context.Response.StatusCode = HttpStatusCode.InternalServerError; context.Response.SendResponse(ex.Message); } return(context); }
/// <summary> /// Validates this IAdverseSubstanceReactionsDischargeSummary /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> void IAdverseReactionDischargeSummary.Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (vb.ArgumentRequiredCheck("AgentDescription", AgentDescription)) { if (AgentDescription != null) { AgentDescription.ValidateMandatory(path + ".AgentDescription", messages); } } if (vb.ArgumentRequiredCheck("AdverseReactionType", AdverseReactionType)) { if (AdverseReactionType != null) { AdverseReactionType.Validate(path + ".AdverseReactionType", messages); } } if (ReactionDescriptions != null && ReactionDescriptions.Any()) { for (var x = 0; x < ReactionDescriptions.Count; x++) { if (ReactionDescriptions[x] != null) { ReactionDescriptions[x].ValidateMandatory( vb.Path + string.Format("ReactionDescriptions[{0}]", x), vb.Messages); } } } }
/// <summary> /// Validates this Diagnoses Interventions /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (ProblemDiagnosis != null) { for (var x = 0; x < ProblemDiagnosis.Count; x++) { ProblemDiagnosis[x].Validate( vb.Path + string.Format("ProblemDiagnosis[{0}]", x), vb.Messages); } } if (Procedures != null) { for (var x = 0; x < Procedures.Count; x++) { Procedures[x].Validate( vb.Path + string.Format("Procedures[{0}]", x), vb.Messages); } } if (UncategorisedMedicalHistoryItem != null) { for (var x = 0; x < UncategorisedMedicalHistoryItem.Count; x++) { UncategorisedMedicalHistoryItem[x].Validate( vb.Path + string.Format("MedicalHistoryItem[{0}]", x), vb.Messages); } } }
public void Test_MultipleBrokenRules() { var builder = new ValidationBuilder(typeof(FooE)); var ruleSet = builder.LowLevelRules; var foo = new FooE { Name = "Robert" }; // should fail both var result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(2, result.Reasons.Length); // should fail only Name length foo.Color = "Blue"; result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); // should fail neither foo.Name = "Bot"; result = ruleSet.Test(foo); Assert.IsTrue(result.Success); Assert.AreEqual(0, result.Reasons.Length); // should fail Color required foo.Color = null; result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); }
private IObjectValidator GetValidator() { var organizationBuilder = new ValidationBuilder <RiskCreatedDateViewModel>(); organizationBuilder.RuleFor(x => x.Value).LessThan(DateTime.Now).WithMessage("Укажите корректную дату"); return(organizationBuilder.Build(this /*методу нужна ЭТА ViewModel*/));// после созданных правил тут мы создаем саму инициализацию. Билдер сбилдся. }
private IObjectValidator GetValidator(IList <Book> books = null, IList <Publisher> publishers = null) { var builder = new ValidationBuilder <Book>(); builder.RuleFor(book => book.ISBN) .Must(ISBNUtils.IsValid) .WithMessage("ISBN is not valid"); builder.RuleFor(book => book.ISBN) .Must(isbn => publishers == null || publishers.Any(publisher => publisher.Id == ISBNUtils.GetPublisherId(isbn))) .WithMessage("Publisher that owns such ISBN does not exist") .Must(isbn => books == null || !books.Any(book => book != this && book.ISBN == isbn)) .WithMessage("ISBN should be unique") .AllWhen(book => ISBNUtils.IsValid(book.ISBN)); builder.RuleFor(book => book.Name) .NotEmpty() .WithMessage("Name can't be empty"); builder.RuleFor(book => book.AgeRestriction) .NotEmpty() .WithMessage("Age Restriction can't be empty") .Matches(@"^\d+\+$") .WithMessage("Age Restriction has wrong format"); return(builder.Build(this)); }
/// <summary> /// Validates this Parent Document /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); vb.ArgumentRequiredCheck("ReleatedDocumentType", ReleatedDocumentType); vb.ArgumentRequiredCheck("DocumentId", DocumentId); }
/// <summary> /// Validates this diagnostic investigation /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (PathologyTestResult != null && PathologyTestResult.Any()) { PathologyTestResult.ForEach(pathologyTestResult => pathologyTestResult.Validate(path + ".PathologyTestResult", messages)); } if (ImagingExaminationResult != null && ImagingExaminationResult.Any()) { ImagingExaminationResult.ForEach(imagingExaminationResult => imagingExaminationResult.Validate(path + ".ImagingExaminationResult", messages)); } if (RequestedService != null && RequestedService.Any()) { if (vb.ArgumentRequiredCheck("RequestedService", RequestedService)) { for (var x = 0; x < RequestedService.Count; x++) { RequestedService[x].Validate(vb.Path + string.Format(".RequestedService[{0}]", x), vb.Messages); } } } if (RequestedService == null && ImagingExaminationResult == null && PathologyTestResult == null) { vb.AddValidationMessage(vb.PathName, null, "Each instance of this Diagnostic Investigations section SHALL have at least one instance of 'PATHOLOGY TEST RESULT' OR 'IMAGING EXAMINATION RESULT' OR 'REQUESTED SERVICE'"); } }
/// <summary> /// Validates this interval /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var validationBuilder = new ValidationBuilder(path, messages); validationBuilder.ArgumentRequiredCheck("UnitOfMeasure", UnitOfMeasure); validationBuilder.ArgumentRequiredCheck("Quantity", Value); }
/// <summary> /// Validates this Organisation /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> void IOrganisation.Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); // Validate Identifiers // optional fields as organisations may not have a HPIO // vb.ArgumentRequiredCheck("Identifiers", Identifiers) if (Identifiers != null) { // Validate each Identifier for (var x = 0; x < Identifiers.Count; x++) { if (Identifiers[x] != null) { Identifiers[x].Validate(vb.Path + string.Format("Identifiers[{0}]", x), vb.Messages); } } } vb.ArgumentRequiredCheck("Name", Name); if (NameUsage.HasValue) { if (NameUsage != null) { vb.NoMatchCheck("NameUsage", NameUsage.Value, OrganisationNameUsage.Undefined); } } }
/// <summary> /// Validates this MeasurementInformation /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (HeadCircumference == null && BodyHeight == null && BodyMassIndex == null && BodyWeight == null) { vb.AddValidationMessage("MeasurementInformation", null, "Please provide an entry for MeasurementInformation"); } if (HeadCircumference != null) { HeadCircumference.Validate(path, messages); } if (BodyHeight != null) { BodyHeight.Validate(path, messages); } if (BodyMassIndex != null) { BodyMassIndex.Validate(path, messages); } if (BodyWeight != null) { BodyWeight.Validate(path, messages); } }
/// <summary> /// Validates this procedure /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void ValidateNoCaption(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); vb.ArgumentRequiredCheck("ExternalDataMediaType", ExternalDataMediaType); vb.ArgumentRequiredCheck("ID", ID); if ((!Path.IsNullOrEmptyWhitespace() && ByteArrayInput != null) || (Path.IsNullOrEmptyWhitespace() && ByteArrayInput == null)) { vb.AddValidationMessage("FileName", null, "The Path and Base64Input are Mutually exclusive, please pass the file by File path or Base64"); } if (!Path.IsNullOrEmptyWhitespace()) { if (!File.Exists(Path)) { vb.AddValidationMessage("FileName", Path, Path + " does not Exist"); } } if (ByteArrayInput != null) { vb.ArgumentRequiredCheck("Base64Input.ByteArray", ByteArrayInput.ByteArray); vb.ArgumentRequiredCheck("ExternalDataMediaType", ByteArrayInput.FileName); } vb.ArgumentRequiredCheck("FileStorageType", FileStorageType); if (!Caption.IsNullOrEmptyWhitespace()) { vb.AddValidationMessage("External Data - Caption", Caption, "Please note the caption in this instance is populated by the 'Report Description' field, so please do not populate this field"); } }
/// <summary> /// Validates this NarrativeOnlyDocument /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">The validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); vb.ArgumentRequiredCheck("Title", Title); vb.ArgumentRequiredCheck("Narrative", Narrative); }
public void BuildValidator_MaxLengthMetaValidationRule() { Assert.That( () => ValidationBuilder.BuildValidator <MetaValidationTestClass1>(), Throws.TypeOf <ValidationConfigurationException>() .And.Message.EqualTo("MaxLength-Constraints greater 50 not allowed for validator 'LengthValidator'!")); }
public void Test_CombinationOfRequiredAndLengthOnSameProperty() { var builder = new ValidationBuilder(typeof(FooD)); var ruleSet = builder.LowLevelRules; var foo = new FooD(); // should fail the "required" but not the "length" test var result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); // should fail the "length" test but not the "required" test foo.Name = "Robert"; result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); // should fail neither foo.Name = "Bob"; result = ruleSet.Test(foo); Assert.IsTrue(result.Success); Assert.AreEqual(0, result.Reasons.Length); }
public void Test_RequiredSpecification() { var builder = new ValidationBuilder(typeof(FooB)); var ruleSet = builder.LowLevelRules; Assert.AreEqual(1, ruleSet.Rules.Count); object rule = ruleSet.Rules[0]; Assert.IsInstanceOf <RequiredSpecification>(rule); var property = CollectionUtils.FirstElement((rule as IPropertyBoundRule).Properties); Assert.AreEqual(typeof(FooB).GetProperty("Name"), property); var foo = new FooB { Name = "Bob" }; Assert.IsTrue(ruleSet.Test(foo).Success); // should fail foo.Name = null; Assert.IsFalse(ruleSet.Test(foo).Success); // emtpy string should fail as well foo.Name = ""; Assert.IsFalse(ruleSet.Test(foo).Success); }
/// <summary> /// Validate the SCS Content for the Australian Childhood Immunisation Register Entries /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (vb.ArgumentRequiredCheck("AustralianChildhoodImmunisationRegisterEntry", AustralianChildhoodImmunisationRegisterEntry)) { for (var x = 0; x < AustralianChildhoodImmunisationRegisterEntry.Count; x++) { AustralianChildhoodImmunisationRegisterEntry[x].Validate(vb.Path + string.Format("AustralianChildhoodImmunisationRegisterEntry[{0}]", x), vb.Messages); //Check to see if BOTH exist in single entry if (AustralianChildhoodImmunisationRegisterEntry[x].VaccineAdministrationEntry != null && AustralianChildhoodImmunisationRegisterEntry[x].VaccineCancellationEntry != null) { vb.AddValidationMessage("AustralianChildhoodImmunisationRegisterEntry", null, "Exactly one 'VACCINE ADMINISTRATION ENTRY' OR exactly one 'VACCINE CANCELLATION ENTRY' SHALL be present per instance of the parent choice ('AUSTRALIAN CHILDHOOD IMMUNISATION REGISTER ENTRY')."); } } //AustralianChildhoodImmunisationRegisterEntry[0]. //PW: 28/08/2016 //THIS IS WRONG - SHOULD ALLOW MULTIPLE ENTRIES, BUT JUST A SINGLE 'ENTRY' or 'CANCELLATION' WITHIN an ENTRY //if (AustralianChildhoodImmunisationRegisterEntry.Count != 1) //{ //vb.AddValidationMessage("AustralianChildhoodImmunisationRegisterEntry",null, "Exactly one 'VACCINE ADMINISTRATION ENTRY' OR exactly one 'VACCINE CANCELLATION ENTRY' SHALL be present per instance of the parent choice ('AUSTRALIAN CHILDHOOD IMMUNISATION REGISTER ENTRY')."); //} } if (vb.ArgumentRequiredCheck("AustralianChildhoodImmunisationRegisterDocumentProvenanceLink", AustralianChildhoodImmunisationRegisterDocumentLink)) { AustralianChildhoodImmunisationRegisterDocumentLink.Validate("AustralianChildhoodImmunisationRegisterDocumentProvenanceLink", messages); } }
public static IHttpContext userGroupEdit(IHttpContext context, string id) { try { if (!context.token().hasPermission("usergroups.write")) { context.Response.StatusCode = HttpStatusCode.NotFound; context.Response.SendResponse(""); return(context); } string[] valArray = { "name=Name,isRequired=" }; var builder = new ValidationBuilder(); var valTemplate = builder.build(valArray); var userGroup = BaseController.getUserInput <UserGroup>(context, valTemplate); userGroup.Id = uint.Parse(id); UserGroup.edit(userGroup, userGroup.Id); context.Response.SendResponse(""); } catch (Exception ex) { context.Response.StatusCode = HttpStatusCode.InternalServerError; context.Response.SendResponse(ex.Message); } return(context); }
private IObjectValidator GetValidator() { var builder = new ValidationBuilder <SendGroupViewModel>(); builder.RuleFor(vm => vm.RegOtdelenie).MyNotEmpty(); builder.RuleFor(vm => vm.City).MyNotEmpty(); builder.RuleFor(vm => vm.Depo).MyNotEmpty(); builder.RuleFor(vm => vm.Uvolnenie).MyNotEmptyDat(); builder.RuleFor(vm => vm.Poezd).MyNotEmpty(); builder.RuleFor(vm => vm.Vagon).MyNotEmpty(); builder.RuleFor(vm => vm.OtprDat).MyNotEmptyDat(); builder.RuleFor(vm => vm.PribDat).MyNotEmptyDat(); //.Matches(@"^\d{1,2}:d{2}$") builder.RuleFor(vm => vm.PribTime) .Must(IsValidTime) .WithMessage("{PropertyName} должно быть в формате ЧЧ:ММ"); /* builder.RuleFor(vm=>vm).NotEmpty() * .When(vm => vm.Persons, persons => !persons.Any(pp=>pp.IsMain)) * .WithMessage("В группе должен быть старший"); */ builder.RuleFor(vm => vm.Vokzal).MyNotEmpty(); ;//TODO .When(vm => UchZavedenie, uchZavedenie => !string.IsNullOrEmpty(uchZavedenie)).Between("1950", "2050"); return(builder.Build(this)); }
public void BuildSpecialCustomer_RemoveLastNameHardConstraint_ThrowsException() { Assert.That(() => ValidationBuilder.BuildValidator <SpecialCustomer2> (), Throws.TypeOf <ValidationConfigurationException> ().And.Message.EqualTo( "Hard constraint validator(s) 'LengthValidator' on property " + "'Remotion.Validation.IntegrationTests.TestDomain.ComponentA.Person.LastName' cannot be removed.")); }
/// <summary> /// Validates this Reviewed Immunisations /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (AdministeredImmunisation != null) { for (var x = 0; x < AdministeredImmunisation.Count; x++) { AdministeredImmunisation[x].Validate ( vb.Path + string.Format("AdministeredImmunisation[{0}]", x), vb.Messages ); } } if (ExclusionStatement != null) { ExclusionStatement.Validate(vb.Path + "GeneralStatement", vb.Messages); } // Recommendations exclusion statement choice var medicationsChoice = new Dictionary <string, object>() { { "AdministeredImmunisations", AdministeredImmunisation }, { "ExclusionStatement", ExclusionStatement } }; vb.ChoiceCheck(medicationsChoice); }
/// <summary> /// Validates this result value /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages to date, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var validationBuilder = new ValidationBuilder(path, messages); if (ValueAsCodableText != null) { ValueAsCodableText.Validate(validationBuilder.Path + "ValueAsCodableText", messages); } if (TestResultValue != null) { TestResultValue.Validate(validationBuilder.Path + "TestResultValue", messages); } if (ValueAsQuantityRange != null) { ValueAsQuantityRange.Validate(validationBuilder.Path + "ValueAsQuantityRange", messages); } var choiceDictionary = new Dictionary <String, object> { { "ValueAsCodableText", ValueAsCodableText }, { "ValueAsQuantity", TestResultValue }, { "ValueAsQuantityRange", ValueAsQuantityRange } }; validationBuilder.ChoiceCheck(choiceDictionary); }
public void Check_NestedLinq_ReturnsCorrectValidationMessage() { //Arrange var obj = new ParentObject() { Nesteds = new NestedObject[] { new NestedObject() { Id = 1, Name = "One" }, new NestedObject() { Id = 2, Name = "Two" }, new NestedObject() { Id = 3, Name = "Three" }, } }; _sut = new ValidationBuilder <ParentObject>(obj); //Act var messages = _sut.Check(o => o.Nesteds.All(n => n.Name == "nope")) .Build(); //Assert AssertHelper.MessageCount(messages, 1); AssertHelper.Paths(messages.First().Paths, "/Nesteds/Name"); }
/// <summary> /// Validates this test procedure name /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); DocumentType?.Validate(path + "DocumentType", messages); vb.ArgumentRequiredCheck("DocumentTitle", DocumentTitle); }
/// <summary> /// Validates this HealthProfile /// </summary> /// <param name="path">The path to this object as a string</param> /// <param name="messages">the validation messages, these may be added to within this method</param> public void Validate(string path, List <ValidationMessage> messages) { var vb = new ValidationBuilder(path, messages); if (NominatedPrimaryHealthCareProviders != null) { if (NominatedPrimaryHealthCareProviders != null) { foreach (var nominatedPrimaryHealthCareProviders in NominatedPrimaryHealthCareProviders) { nominatedPrimaryHealthCareProviders.Validate(vb.Path + "NominatedPrimaryHealthCareProvider", vb.Messages); } } } if (vb.ArgumentRequiredCheck("AdverseReactions", AdverseReactions)) { if (AdverseReactions != null) { AdverseReactions.Validate(vb.Path + "AdverseReactions", vb.Messages); } } if (Alerts != null) { Alerts.Validate(vb.Path + "Alerts", vb.Messages); } }
public static IHttpContext departmentEdit(IHttpContext context, string id) { try { if (!context.token().hasPermission("departments.write")) { context.Response.StatusCode = HttpStatusCode.NotFound; context.Response.SendResponse(""); return(context); } var builder = new ValidationBuilder(); string[] valArray = { "name=Name,isRequired=" }; var valTemplate = builder.build(valArray); var department = BaseController.getUserInput <Departments>(context, valTemplate); department.Id = uint.Parse(id); Departments.edit(department.Id, department); } catch (Exception ex) { context.Response.SendResponse(ex.Message); context.Response.StatusCode = HttpStatusCode.InternalServerError; } return(context); }
public void Test_EmbeddedValue() { var builder = new ValidationBuilder(typeof(FooC)); var ruleSet = builder.LowLevelRules; Assert.AreEqual(1, ruleSet.Rules.Count); object rule = ruleSet.Rules[0]; var property = CollectionUtils.FirstElement((rule as IPropertyBoundRule).Properties); Assert.AreEqual(typeof(FooC).GetProperty("EmbeddedFoo"), property); var foo = new FooC { EmbeddedFoo = null }; // this should pass, because rules on the embedded value class are not evaluated when the property is null Assert.IsTrue(ruleSet.Test(foo).Success); // should pass foo.EmbeddedFoo = new FooA { Name = "Bob" }; Assert.IsTrue(ruleSet.Test(foo).Success); // should fail because Robert is longer than 5 chars foo.EmbeddedFoo.Name = "Robert"; Assert.IsFalse(ruleSet.Test(foo).Success); }
public void ChainName_should_return_private_field_if_it_has_value() { // Arrange var builder = new ValidationBuilder<Order, string>(x => x.ID) {ChainName = "My.Chain.Name"}; // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("My.Chain.Name")); }
public void ChainName_should_return_value_resolved_from_expression__if_private_field_does_not_have_value() { // Arrange var builder = new ValidationBuilder<Order, string>(x => x.ID); // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("Order.ID")); }
public void GetChainFromExpression_should_return_a_chain() { // Arrange var builder = new ValidationBuilder<Order, string>(x => x.OrderDetails[0].ProductCode); builder.UpdateContainerName("The.Order"); // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("The.Order.OrderDetails[0].ProductCode")); }
public void ChainName_should_return_container_name_if_cannot_resolve_value_from_expression() { // Arrange var builder = new ValidationBuilder<Order, string>(null); builder.UpdateContainerName("The.Order"); // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("The.Order")); }
public void ContainerName_when_set_will_update_chain_name() { // Arrange var builder = new ValidationBuilder<Order, string>(null); builder.ChainName = "Chain.Name"; Assert.That(builder.ChainName, Is.EqualTo("Chain.Name")); builder.UpdateContainerName("The.Order"); // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("The.Order")); }
public void Test_LengthSpecification() { var builder = new ValidationBuilder(typeof(FooA)); var ruleSet = builder.LowLevelRules; Assert.AreEqual(1, ruleSet.Rules.Count); object rule = ruleSet.Rules[0]; Assert.IsInstanceOf<LengthSpecification>(rule); var property = CollectionUtils.FirstElement((rule as IPropertyBoundRule).Properties); Assert.AreEqual(typeof(FooA).GetProperty("Name"), property); var fooA = new FooA {Name = "Bob"}; Assert.IsTrue(ruleSet.Test(fooA).Success); fooA.Name = "Robert"; Assert.IsFalse(ruleSet.Test(fooA).Success); }
public void GetChainFromExpression_should_return_a_container_if_expression_type_is_not_member_access() { // Arrange var builder = new ValidationBuilder<Order, string>(x => "Not A Member Access Expression"); builder.UpdateContainerName("The.Order.OrderDetails[0].Id"); // Action var name = builder.ChainName; // Assert Assert.That(name, Is.EqualTo("The.Order.OrderDetails[0].Id")); }
public void Test_EmbeddedValue() { var builder = new ValidationBuilder(typeof(FooC)); var ruleSet = builder.LowLevelRules; Assert.AreEqual(1, ruleSet.Rules.Count); object rule = ruleSet.Rules[0]; var property = CollectionUtils.FirstElement((rule as IPropertyBoundRule).Properties); Assert.AreEqual(typeof(FooC).GetProperty("EmbeddedFoo"), property); var foo = new FooC {EmbeddedFoo = null}; // this should pass, because rules on the embedded value class are not evaluated when the property is null Assert.IsTrue(ruleSet.Test(foo).Success); // should pass foo.EmbeddedFoo = new FooA {Name = "Bob"}; Assert.IsTrue(ruleSet.Test(foo).Success); // should fail because Robert is longer than 5 chars foo.EmbeddedFoo.Name = "Robert"; Assert.IsFalse(ruleSet.Test(foo).Success); }
public void Test_RequiredSpecification() { var builder = new ValidationBuilder(typeof(FooB)); var ruleSet = builder.LowLevelRules; Assert.AreEqual(1, ruleSet.Rules.Count); object rule = ruleSet.Rules[0]; Assert.IsInstanceOf<RequiredSpecification>(rule); var property = CollectionUtils.FirstElement((rule as IPropertyBoundRule).Properties); Assert.AreEqual(typeof(FooB).GetProperty("Name"), property); var foo = new FooB {Name = "Bob"}; Assert.IsTrue(ruleSet.Test(foo).Success); // should fail foo.Name = null; Assert.IsFalse(ruleSet.Test(foo).Success); // emtpy string should fail as well foo.Name = ""; Assert.IsFalse(ruleSet.Test(foo).Success); }
public void Test_MultipleBrokenRules() { var builder = new ValidationBuilder(typeof(FooE)); var ruleSet = builder.LowLevelRules; var foo = new FooE {Name = "Robert"}; // should fail both var result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(2, result.Reasons.Length); // should fail only Name length foo.Color = "Blue"; result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); // should fail neither foo.Name = "Bot"; result = ruleSet.Test(foo); Assert.IsTrue(result.Success); Assert.AreEqual(0, result.Reasons.Length); // should fail Color required foo.Color = null; result = ruleSet.Test(foo); Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); }
public void Test_HighLevel_rules_method() { var builder = new ValidationBuilder(typeof(BarA)); var result = builder.HighLevelRules.Test(new BarA()); // expect exactly one broken rule Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); }
public void Test_HighLevel_rules_method_inherited() { // BarB inherits from BarA, but does not define its own additional rules method var builder = new ValidationBuilder(typeof(BarB)); var result = builder.HighLevelRules.Test(new BarB()); // expect exactly one broken rule (more than 1 would indicate that the GetRules had been processed more than once) Assert.IsFalse(result.Success); Assert.AreEqual(1, result.Reasons.Length); // BarC inherits from BarA, and also defines its own additional rules method builder = new ValidationBuilder(typeof(BarC)); result = builder.HighLevelRules.Test(new BarC()); // expect 2 broken rules, one from BarA and one from BarC Assert.IsFalse(result.Success); Assert.AreEqual(2, result.Reasons.Length); }