public void ShoppingCart_RequiredMembers() { Type type = typeof(ShoppingCart); ShoppingCart cart = (ShoppingCart)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("TotalNumberOfItems"); PropertyValidator.ValidateReadOnly(prop, "TotalNumberOfItems", typeof(int)); prop = type.GetProperty("TotalAmountOwed"); PropertyValidator.ValidateReadOnly(prop, "TotalAmountOwed", typeof(decimal)); MethodInfo mi = type.GetMethod("GetAveragePricePerItem"); Assert.IsNotNull(mi, "Shopping cart class needs the GetAveragePricePerItem method."); Assert.AreEqual(typeof(decimal), mi.ReturnType, "GetAveragePricePerItem() method needs to return type: double"); Assert.AreEqual(0, mi.GetParameters().Length, "GetAveragePricePerItem() should have no parameters"); mi = type.GetMethod("AddItems"); Assert.IsNotNull(mi, "Shopping cart class needs the AddItems method."); Assert.AreEqual(typeof(void), mi.ReturnType, "AddItems() method needs to return type: void"); Assert.AreEqual(2, mi.GetParameters().Length); mi = type.GetMethod("Empty"); Assert.IsNotNull(mi, "Shopping cart class needs the Empty method."); Assert.AreEqual(typeof(void), mi.ReturnType, "Empty() method needs to return type: void"); Assert.AreEqual(0, mi.GetParameters().Length); }
public void PropertyValidator_returns_validation_errors_if_primitive_property_value_is_not_valid() { var mockValidator = new Mock <IValidator>(); mockValidator .Setup(v => v.Validate(It.IsAny <EntityValidationContext>(), It.IsAny <InternalMemberEntry>())) .Returns(() => new[] { new DbValidationError("Name", "error") }); var propertyValidator = new PropertyValidator( "Name", new[] { mockValidator.Object }); var mockInternalEntityEntry = Internal.MockHelper.CreateMockInternalEntityEntry( new Dictionary <string, object> { { "Name", "" } }); var results = propertyValidator.Validate( MockHelper.CreateEntityValidationContext(mockInternalEntityEntry.Object), mockInternalEntityEntry.Object.Member("Name")); ValidationErrorHelper.VerifyResults( new[] { new Tuple <string, string>("Name", "error") }, results); }
public void Dog_RequiredMemberTests() { Type type = typeof(Dog); Dog dog = (Dog)Activator.CreateInstance(type); FieldInfo fi = type.GetField("isSleeping", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fi, "Dog class needs the isSleeping variable."); Assert.AreEqual(typeof(bool), fi.FieldType, "isSleeping should be type: bool"); PropertyInfo prop = type.GetProperty("IsSleeping"); PropertyValidator.ValidateReadOnly(prop, "IsSleeping", typeof(bool)); MethodInfo mi = type.GetMethod("MakeSound"); Assert.IsNotNull(mi, "Dog class needs the MakeSound method."); Assert.AreEqual(typeof(string), mi.ReturnType, "MakeSound() method needs to return type: string"); mi = type.GetMethod("Sleep"); Assert.IsNotNull(mi, "Dog class needs the Sleep() method."); Assert.AreEqual(typeof(void), mi.ReturnType, "Sleep() method needs to return type: void"); mi = type.GetMethod("WakeUp"); Assert.IsNotNull(mi, "Dog class needs the WakeUp() method."); Assert.AreEqual(typeof(void), mi.ReturnType, "WakeUp() method needs to return type: void"); }
public ReleaseOrderViewModel() { _data = new Orders(); _dataLastChange = DateTime.Now; Validator = new PropertyValidator(); ValidationEnabled = false; }
public IHttpActionResult GetProperty(int id) { loggedInUser = GetLoggedInUser(); Entity.Models.Property propertyEntity = db.Properties.FirstOrDefault(p => p.CompanyId == loggedInUser.CompanyId && p.Id == id); //loggedInUser.Properties.FirstOrDefault(p => p.Id == id); if (propertyEntity == null) { return(NotFound()); } if (propertyEntity.CompanyId != loggedInUser.CompanyId) { return(BadRequest("Requested property does not belong to same company as logged in user")); } // Fortunately, our we have a relationship be user and associated properties, so this is easy. var propertyDto = Mapper.Map <Entity.Models.Property, Dto.Models.Property>(propertyEntity); GenerateUserPhotoLinks(propertyDto.Users); var result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return(new ValidatorError("Error mapping property DTO from database", HttpStatusCode.InternalServerError, result, Request)); } return(Ok(propertyDto)); }
public void Calculator_RequiredMembers() { Type type = typeof(Calculator); Calculator calculator = (Calculator)Activator.CreateInstance(type, 0); PropertyInfo prop = type.GetProperty("Result"); PropertyValidator.ValidateReadOnly(prop, "Result", typeof(int)); MethodInfo mi = type.GetMethod("Add"); Assert.IsNotNull(mi, "Calculator class needs the Add method."); Assert.AreEqual(typeof(int), mi.ReturnType, "Add(int addend) method needs to return type: int"); Assert.AreEqual(1, mi.GetParameters().Length, "Add(int addend) should have 1 parameter"); mi = type.GetMethod("Subtract"); Assert.IsNotNull(mi, "Calculator class needs the Subtract method."); Assert.AreEqual(typeof(int), mi.ReturnType, "Subtract(int subtrahend) method needs to return type: int"); Assert.AreEqual(1, mi.GetParameters().Length, "Subtract(int subtrahend) should have 1 parameter"); mi = type.GetMethod("Multiply"); Assert.IsNotNull(mi, "Calculator class needs the Multiply method."); Assert.AreEqual(typeof(int), mi.ReturnType, "Multiply(int multiplier) method needs to return type: int"); Assert.AreEqual(1, mi.GetParameters().Length, "Multiply(int multiplier) should have 1 parameter"); mi = type.GetMethod("Power"); Assert.IsNotNull(mi, "Calculator class needs the Power method."); Assert.AreEqual(typeof(int), mi.ReturnType, "Power(int exponent) method needs to return type: int"); Assert.AreEqual(1, mi.GetParameters().Length, "Power(int exponent) should have 1 parameter"); mi = type.GetMethod("Reset"); Assert.IsNotNull(mi, "Calculator class needs the Reset method."); Assert.AreEqual(typeof(void), mi.ReturnType, "Reset() method needs to return type: void"); Assert.AreEqual(0, mi.GetParameters().Length, "Reset() should have no parameters"); }
public IEnumerable <ModelClientValidationRule> Create(PropertyValidator propertyValidator, ModelMetadata modelMetadata) { ModelMetaData = modelMetadata; var clientRules = new List <ModelClientValidationRule>(); if (propertyValidator.RuleTree.Root is RuleNode) { var rules = GetAllRuleValidatorsForProperty(propertyValidator.RuleTree.Root as RuleNode); //Map RuleValidator to Client Rules foreach (var ruleValidator in rules) { var clientRule = RuleValidatorClientRuleRegistry.Instance.Create(ruleValidator); //If a client rule isn't found for the RuleValidator then NULL is returned if (clientRule != null) { clientRule.ErrorMessage = FormatErrorMessageTemplateWithName(clientRule.ErrorMessage); clientRules.Add(clientRule); } } } return(clientRules); }
public void Product_CheckRequiredMembers() { Type type = typeof(Product); Product product = (Product)Activator.CreateInstance(type); FieldInfo fi = type.GetField("name", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fi, "A field called name needs to exist"); Assert.AreEqual(typeof(string), fi.FieldType, "The name field needs to be type: string"); fi = type.GetField("price", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fi, "A field called price needs to exist"); Assert.AreEqual(typeof(decimal), fi.FieldType, "The price field needs to be type: decimal"); fi = type.GetField("weightInOunces", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(fi, "A field called weightInOunces needs to exist"); Assert.AreEqual(typeof(double), fi.FieldType, "The weightInOunces field needs to be type: double"); PropertyInfo prop = type.GetProperty("Name"); PropertyValidator.ValidateReadWrite(prop, "Name", typeof(string)); prop = type.GetProperty("Price"); PropertyValidator.ValidateReadWrite(prop, "Price", typeof(decimal)); prop = type.GetProperty("WeightInOunces"); PropertyValidator.ValidateReadWrite(prop, "WeightInOunces", typeof(double)); }
private void ExecuteAllValidationsInProperty(PropertyValidator property, object value) { foreach (var validation in property.GetValidations()) { ExecuteValidationInProperty(property.Name, validation, value); } }
/// <summary> /// Facilitates the grouping of a subset of rules to dictate precidence for And / Or opertations. /// </summary> /// <example> /// Validate ActiveDate is in a five day window starting 10 days ago OR a five day window starting in 5 days from now. /// spec.Check(c => c.ActiveDate).Required() /// .Group(d => d.GreaterThan(DateTime.Now.AddDays(-10)) /// .And.LessThan(DateTime.Now.AddDays(-5))) /// .Or /// .Group(d => d.GreaterThan(DateTime.Now.AddDays(5)) /// .And.LessThan(DateTime.Now.AddDays(10))); /// </example> /// <param name="rules"><see cref="Action<RuleBuilder<T, TProperty>>"/></param> /// <returns><see cref="IAndOr<T, TProperty>"/></returns> public IAndOr <T, TProperty> Group(Action <RuleBuilder <T, TProperty> > rules) { var innerPropertyValidator = new PropertyValidator <T, TProperty>(_propertyValidator); var groupRules = new RuleBuilder <T, TProperty>(innerPropertyValidator); rules(groupRules); if (OrNextRule) { if (NextRuleIsConditional) { _propertyValidator.ConditionalOrGroup(innerPropertyValidator); } else { _propertyValidator.OrGroup(innerPropertyValidator); } } else { if (NextRuleIsConditional) { _propertyValidator.ConditionalAndGroup(innerPropertyValidator); } else { _propertyValidator.AndGroup(innerPropertyValidator); } } NextRuleIsConditional = false; OrNextRule = false; return(new ActionJoinBuilder <T, TProperty>(_propertyValidator)); }
public IEnumerable<ModelClientValidationRule> Create(PropertyValidator propertyValidator, ModelMetadata modelMetadata) { ModelMetaData = modelMetadata; var clientRules = new List<ModelClientValidationRule>(); if (propertyValidator.RuleTree.Root is RuleNode) { var rules = GetAllRuleValidatorsForProperty(propertyValidator.RuleTree.Root as RuleNode); //Map RuleValidator to Client Rules foreach (var ruleValidator in rules) { var clientRule = RuleValidatorClientRuleRegistry.Instance.Create(ruleValidator); //If a client rule isn't found for the RuleValidator then NULL is returned if (clientRule != null) { clientRule.ErrorMessage = FormatErrorMessageTemplateWithName(clientRule.ErrorMessage); clientRules.Add(clientRule); } } } return clientRules; }
public void IsValidWhenAllValidatorsAreValid() { var validatableObject = new ValidatableTestObject(); var validator = PropertyValidator .For(validatableObject, o => o.SomeStringProperty) .Required("Error occurred!"); var anotherValidator = PropertyValidator .For(validatableObject, o => o.AnotherStringProperty) .Required("Error occurred!"); var modelValidator = new ModelValidator(validator, anotherValidator); Assert.IsFalse(modelValidator.IsValid); validatableObject.SomeStringProperty = "valid"; Assert.IsFalse(modelValidator.IsValid); validatableObject.AnotherStringProperty = "valid"; Assert.IsTrue(modelValidator.IsValid); validatableObject.AnotherStringProperty = ""; Assert.IsFalse(modelValidator.IsValid); }
public SKUIDViewModel() { _skuid = new SKU_ID(); Validator = new PropertyValidator(); ValidationEnabled = false; AllowChangeIndex = false; }
public void Elevator_HasRequiredMembers() { Type type = typeof(Elevator); Elevator elevator = (Elevator)Activator.CreateInstance(type, 3); PropertyInfo prop = type.GetProperty("CurrentLevel"); PropertyValidator.ValidateReadOnly(prop, "CurrentLevel", typeof(int)); prop = type.GetProperty("NumberOfLevels"); PropertyValidator.ValidateReadOnly(prop, "NumberOfLevels", typeof(int)); prop = type.GetProperty("DoorIsOpen"); PropertyValidator.ValidateReadOnly(prop, "DoorIsOpen", typeof(bool)); MethodInfo method = type.GetMethod("OpenDoor"); MethodValidator.ValidatePublicMethod(method, "OpenDoor", typeof(void)); method = type.GetMethod("CloseDoor"); MethodValidator.ValidatePublicMethod(method, "CloseDoor", typeof(void)); method = type.GetMethod("GoUp"); MethodValidator.ValidatePublicMethod(method, "GoUp", typeof(void)); Assert.AreEqual(1, method.GetParameters().Length, "GoUp should accept 1 parameter"); method = type.GetMethod("GoDown"); MethodValidator.ValidatePublicMethod(method, "GoDown", typeof(void)); Assert.AreEqual(1, method.GetParameters().Length, "GoDown should accept 1 parameter"); }
public void Airplane_HasRequiredMembers() { Type type = typeof(Airplane); Airplane Airplane = (Airplane)Activator.CreateInstance(type, "ABC123", 2, 3); PropertyInfo prop = type.GetProperty("PlaneNumber"); PropertyValidator.ValidateReadOnly(prop, "PlaneNumber", typeof(string)); prop = type.GetProperty("BookedFirstClassSeats"); PropertyValidator.ValidateReadOnly(prop, "BookedFirstClassSeats", typeof(int)); prop = type.GetProperty("AvailableFirstClassSeats"); PropertyValidator.ValidateReadOnly(prop, "AvailableFirstClassSeats", typeof(int)); prop = type.GetProperty("TotalFirstClassSeats"); PropertyValidator.ValidateReadOnly(prop, "TotalFirstClassSeats", typeof(int)); prop = type.GetProperty("BookedCoachSeats"); PropertyValidator.ValidateReadOnly(prop, "BookedCoachSeats", typeof(int)); prop = type.GetProperty("AvailableCoachSeats"); PropertyValidator.ValidateReadOnly(prop, "AvailableCoachSeats", typeof(int)); prop = type.GetProperty("TotalCoachSeats"); PropertyValidator.ValidateReadOnly(prop, "TotalCoachSeats", typeof(int)); MethodInfo method = type.GetMethod("ReserveSeats"); MethodValidator.ValidatePublicMethod(method, "ReserveSeats", typeof(bool)); }
public void GetValidatorForProperty_returns_correct_validator_for_child_complex_property() { var entity = new DepartureArrivalInfoWithNestedComplexType { Airport = new AirportDetails(), }; var mockInternalEntityEntry = Internal.MockHelper.CreateMockInternalEntityEntry(entity); var childPropertyEntry = mockInternalEntityEntry.Object.Property("Airport").Property("AirportCode"); var childPropertyValidator = new PropertyValidator("AirportCode", new IValidator[0]); var complexPropertyValidator = new ComplexPropertyValidator( "Airport", new IValidator[0], new ComplexTypeValidator(new[] { childPropertyValidator }, new IValidator[0])); var entityValidator = new EntityValidator(new[] { complexPropertyValidator }, new IValidator[0]); var mockValidationProvider = MockHelper.CreateMockValidationProvider(); mockValidationProvider.Protected() .Setup <PropertyValidator>("GetValidatorForProperty", ItExpr.IsAny <EntityValidator>(), ItExpr.IsAny <InternalMemberEntry>()) .Returns <EntityValidator, InternalMemberEntry>((ev, e) => complexPropertyValidator); var actualPropertyValidator = mockValidationProvider.Object.GetValidatorForPropertyBase(entityValidator, childPropertyEntry); Assert.Same(childPropertyValidator, actualPropertyValidator); }
public void Employee_HasRequiredMembers() { Type type = typeof(Employee); PropertyInfo prop = type.GetProperty("EmployeeId"); PropertyValidator.ValidateReadPrivateWrite(prop, "EmployeeId", typeof(int)); prop = type.GetProperty("FirstName"); PropertyValidator.ValidateReadPrivateWrite(prop, "FirstName", typeof(string)); prop = type.GetProperty("LastName"); PropertyValidator.ValidateReadWrite(prop, "LastName", typeof(string)); prop = type.GetProperty("FullName"); PropertyValidator.ValidateReadOnly(prop, "FullName", typeof(string)); prop = type.GetProperty("Department"); PropertyValidator.ValidateReadWrite(prop, "Department", typeof(string)); prop = type.GetProperty("AnnualSalary"); PropertyValidator.ValidateReadPrivateWrite(prop, "AnnualSalary", typeof(double)); MethodInfo method = type.GetMethod("RaiseSalary"); MethodValidator.ValidatePublicMethod(method, "RaiseSalary", typeof(void)); }
public void Company_CheckRequiredMembers() { Type type = typeof(Company); Company company = (Company)Activator.CreateInstance(type, "ACME"); PropertyInfo prop = type.GetProperty("Name"); PropertyValidator.ValidateReadOnly(prop, "Name", typeof(string)); prop = type.GetProperty("NumberOfEmployees"); PropertyValidator.ValidateReadWrite(prop, "NumberOfEmployees", typeof(int)); prop = type.GetProperty("Revenue"); PropertyValidator.ValidateReadWrite(prop, "Revenue", typeof(decimal)); prop = type.GetProperty("Expenses"); PropertyValidator.ValidateReadWrite(prop, "Expenses", typeof(decimal)); MethodInfo mi = type.GetMethod("GetCompanySize"); Assert.IsNotNull(mi, "A method called GetCompanySize needs to be included"); Assert.AreEqual(typeof(string), mi.ReturnType, "The GetCompanySize() method needs to be type: string"); mi = type.GetMethod("GetProfit"); Assert.IsNotNull(mi, "A method called GetProfit needs to be included"); Assert.AreEqual(typeof(decimal), mi.ReturnType, "The GetProfit() method needs to be type: decimal"); }
public void GetFormattedErrorMessage_ReturnsFormattedString() { //Create an Entity var emptyContact = new Contact(); emptyContact.FirstName = null; emptyContact.LastName = null; //Create PropertyValidator var propertyValidator = new PropertyValidator<Contact, string>(contact => contact.LastName); //Create a rule RuleValidator<Contact, string> ruleValidator = new LengthBetween<Contact>(1, 5); //Create a context var context = new RuleValidatorContext<Contact, string>(emptyContact, propertyValidator, null); //create it like this? IOC? Factory? //IMessageStore messageStore = new ResourceMessageStore(); //string errorMessage = messageStore.GetFormattedDefaultMessage(ruleValidator.GetType().Name, context, ruleValidator.Parameters); var messageService = new MessageService(); var errorMessage = messageService.GetDefaultMessageAndFormat(new MessageContext(context, ruleValidator.GetType(), false, null, null), ruleValidator.Parameters); Assert.That(errorMessage, Is.Not.Null.Or.Empty); Assert.That(errorMessage, Is.StringContaining("Last Name")); Assert.That(errorMessage, Is.StringContaining("1")); Assert.That(errorMessage, Is.StringContaining("5")); //null: Search for Actual value but it's empty b/c the value is null }
public BoxIDViewModel() { _boxid = new Box_ID(); _SKUIDs = new List <string>(); _tuid = 0; Validator = new PropertyValidator(); ValidationEnabled = false; }
public static IRuleBuilderOptions <T, TProperty?> WrapValueTypeValidator <T, TProperty>( this IRuleBuilder <T, TProperty?> ruleBuilder, PropertyValidator <T, TProperty> valueTypePropertyValidator) where TProperty : struct { return(ruleBuilder.SetValidator( new ValueTypePropertyValidatorWrapper <T, TProperty>(valueTypePropertyValidator))); }
public HistoryCommandsViewModel() { Validator = new PropertyValidator(); SelectedContent = null; RefreshCmd = new RelayCommand(async() => await ExecuteRefresh(), CanExecuteRefresh); RefreshSimpleCmd = new RelayCommand(async() => await ExecuteRefreshSimpleCommands()); }
public void Company_ExpensesProperty() { Type type = typeof(Company); Company company = (Company)Activator.CreateInstance(type, "ACME"); PropertyInfo prop = type.GetProperty("Expenses"); PropertyValidator.ValidateReadWrite(prop, "Expenses", typeof(decimal)); }
public IDisposable SetupValidation <TProperty>(string name, Func <T, TProperty, string> validateFunc) { var property = (IProperty <TProperty>)_container.PropertyStore.GetProperty(name); var validator = new PropertyValidator <TProperty>(this, property, validateFunc); validator.Validate(); return(validator); }
public void ShoppingCart_TotalNumberOfItemsProperty() { Type type = typeof(ShoppingCart); ShoppingCart cart = (ShoppingCart)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("TotalNumberOfItems"); PropertyValidator.ValidateReadOnly(prop, "TotalNumberOfItems", typeof(int)); }
public void Company_NumberOfEmployeesProperty() { Type type = typeof(Company); Company company = (Company)Activator.CreateInstance(type, "ACME"); PropertyInfo prop = type.GetProperty("NumberOfEmployees"); PropertyValidator.ValidateReadWrite(prop, "NumberOfEmployees", typeof(int)); }
public void Company_NameProperty() { Type type = typeof(Company); Company company = (Company)Activator.CreateInstance(type, "ACME"); PropertyInfo prop = type.GetProperty("Name"); PropertyValidator.ValidateReadOnly(prop, "Name", typeof(string)); }
public void ValidationResultReturnsUnvalidatedIfNoValidators() { var validatableObject = new ValidatableTestObject(); var validator = PropertyValidator.For(validatableObject, o => o.SomeStringProperty); var result = validator.ValidationResult; Assert.AreEqual(PropertyValidationResult.Unvalidated, result); }
public void ShoppingCart_TotalAmountOwedProperty() { Type type = typeof(ShoppingCart); ShoppingCart cart = (ShoppingCart)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("TotalAmountOwed"); PropertyValidator.ValidateReadOnly(prop, "TotalAmountOwed", typeof(decimal)); }
public void Product_NameProperty() { Type type = typeof(Product); Product product = (Product)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("Name"); PropertyValidator.ValidateReadWrite(prop, "Name", typeof(string)); }
public void Product_WeightProperty() { Type type = typeof(Product); Product product = (Product)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("WeightInOunces"); PropertyValidator.ValidateReadWrite(prop, "WeightInOunces", typeof(double)); }
public void Product_PriceProperty() { Type type = typeof(Product); Product product = (Product)Activator.CreateInstance(type); PropertyInfo prop = type.GetProperty("Price"); PropertyValidator.ValidateReadWrite(prop, "Price", typeof(decimal)); }
public RuleValidatorContext(object instance, PropertyValidator validator, RuleValidatorContext parentContext) { PropertyName = String.IsNullOrEmpty(validator.PropertyNameOverride) ? validator.PropertyName.SplitPascalCase() : validator.PropertyNameOverride; PropertyValue = validator.GetValueForProperty(instance); PropertyInfo = validator.PropertyInfo; Parent = parentContext; Instance = instance; }
public void ApplyShouldReturnSelf() { // arrange var expected = new PropertyValidator<IComponent, ISite>( c => c.Site, "Site" ); // act var actual = expected.Apply( new RequiredRule<ISite>() ); // assert Assert.Same( expected, actual ); }
public BaseVM(BaseVM parent) { this.Parent = parent; propertyValidators = new Dictionary<string, PropertyValidator>(); foreach (PropertyInfo propertyInfo in this.GetType().GetProperties()) { ValidationAttribute[] vas = GetValidationAttributes(propertyInfo); if (vas.Length > 0 && propertyInfo.GetGetMethod() != null) { PropertyValidator validator = new PropertyValidator(propertyInfo.Name, propertyInfo.GetGetMethod(), vas); propertyValidators[propertyInfo.Name] = validator; } } }
public void A_property_that_is_valid_should_not_return_any_violations() { Member member = new Member(); member.Username = "******"; IValidator<object> validator = new PropertyValidator(typeof(Member).GetProperty("Username")); IEnumerable<IViolation> violations; Assert.That(validator.IsValid(member, out violations), Is.True); List<IViolation> violationList = new List<IViolation>(violations); Assert.That(violationList.Count, Is.EqualTo(0)); }
public void ValidateObjectShouldNotAllowNullInstance() { // arrange var propertyValidator = new PropertyValidator<IComponent, ISite>( c => c.Site, "Site" ); IPropertyValidator validator = propertyValidator; IPropertyValidator<IComponent> validatorOfT = propertyValidator; IComponent instance = null; // act var ex1 = Assert.Throws<ArgumentNullException>( () => validator.ValidateObject( instance ) ); var ex2 = Assert.Throws<ArgumentNullException>( () => validatorOfT.ValidateObject( instance ) ); // assert Assert.Equal( "instance", ex1.ParamName ); Assert.Equal( "instance", ex2.ParamName ); }
public void A_property_that_is_too_short_should_return_a_format_violation() { Member member = new Member(); member.Username = "******"; IValidator<object> validator = new PropertyValidator(typeof (Member).GetProperty("Username")); IEnumerable<IViolation> violations; Assert.That(validator.IsValid(member, out violations), Is.False); List<IViolation> violationList = new List<IViolation>(violations); Assert.That(violationList.Count, Is.EqualTo(1)); Assert.That(violationList[0], Is.TypeOf((typeof (InvalidFormatViolation)))); }
public void ValidateValueShouldEvaluateValue() { // arrange var propertyValidator = new PropertyValidator<IComponent, ISite>( c => c.Site, "Site" ); IPropertyValidator validator = propertyValidator; IPropertyValidator<IComponent> validatorOfT = propertyValidator; ISite value = null; propertyValidator.Apply( new RequiredRule<ISite>() ); // act var actual1 = validator.ValidateValue( value ); var actual2 = validatorOfT.ValidateValue( value ); // assert Assert.Equal( 1, actual1.Count ); Assert.Equal( 1, actual2.Count ); }
public RuleValidatorContext(object instance, PropertyValidator validator, RuleValidatorContext parentContext) { PropertyValue = validator.GetValueForProperty(instance); if (validator.PropertyNameOverride == null) { SelectPropertyName(instance, validator); } else { PropertyName = validator.PropertyNameOverride; } PropertyInfo = validator.PropertyInfo; Parent = parentContext; Instance = instance; Level = validator.Level; }
public void Validate_OptionalProperty_WithNoValue_IsValid() { var emptyContact = new Contact(); emptyContact.FirstName = string.Empty; emptyContact.LastName = string.Empty; var propertyValidator = new PropertyValidator<Contact, string>(contact => contact.LastName); //add a single rule var lengthValidator = new LengthBetween<Contact>(1, 5); propertyValidator.AndRule(lengthValidator); //.Rules.Add(lengthValidator); var notification = new ValidationNotification(); //Validate var result = propertyValidator.Validate(emptyContact, null, notification); Assert.That(result, Is.True); Assert.That(notification.Errors, Is.Empty); }
public PropertyValidatorFixture() { this.adapter1 = A.Fake<IDataAnnotationsValidatorAdapter>(); this.error1 = new ModelValidationError("error1", string.Empty); A.CallTo(() => this.adapter1.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._)) .Returns(new[] {this.error1}); this.adapter2 = A.Fake<IDataAnnotationsValidatorAdapter>(); this.error2 = new ModelValidationError("error2", string.Empty); A.CallTo(() => this.adapter2.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._)) .Returns(new[] { this.error2 }); this.mappings = new Dictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>> { {new RangeAttribute(1, 10), new[] {this.adapter1}}, {new RequiredAttribute(), new[] {this.adapter2}} }; var type = typeof(Model); this.descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type) .GetTypeDescriptor(type) .GetProperties()[0]; this.validator = new PropertyValidator { AttributeAdaptors = this.mappings, Descriptor =this.descriptor }; }
public IHttpActionResult GetProperty(int id) { loggedInUser = GetLoggedInUser(); Entity.Models.Property propertyEntity = db.Properties.FirstOrDefault(p => p.CompanyId == loggedInUser.CompanyId && p.Id == id); //loggedInUser.Properties.FirstOrDefault(p => p.Id == id); if (propertyEntity == null) { return NotFound(); } if (propertyEntity.CompanyId != loggedInUser.CompanyId) { return BadRequest("Requested property does not belong to same company as logged in user"); } // Fortunately, our we have a relationship be user and associated properties, so this is easy. var propertyDto = Mapper.Map<Entity.Models.Property, Dto.Models.Property>(propertyEntity); GenerateUserPhotoLinks(propertyDto.Users); var result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return new ValidatorError("Error mapping property DTO from database", HttpStatusCode.InternalServerError, result, Request); } return Ok(propertyDto); }
public void ValidateValueShouldReturnExpectedResultForIncompatibleValue() { // arrange IPropertyValidator validator = new PropertyValidator<IComponent, ISite>( c => c.Site, "Site" ); var errorMessage = "The Site field of type System.ComponentModel.ISite is incompatible with a value of type System.Object."; var value = new object(); // act var actual = validator.ValidateValue( value ); // assert Assert.Equal( 1, actual.Count ); Assert.Equal( errorMessage, actual[0].ErrorMessage ); Assert.Equal( "Site", actual[0].MemberNames.Single() ); }
public void ValidateValueShouldReturnExpectedResultForNonNullValue() { // arrange IPropertyValidator validator = new PropertyValidator<ISite, bool>( s => s.DesignMode, "DesignMode" ); var errorMessage = "The DesignMode field of type System.Boolean cannot be validated with a null value."; object value = null; // act var actual = validator.ValidateValue( value ); // assert Assert.Equal( 1, actual.Count ); Assert.Equal( errorMessage, actual[0].ErrorMessage ); Assert.Equal( "DesignMode", actual[0].MemberNames.Single() ); }
public void ValidateObjectShouldEvaluateInstance() { // arrange var instance = new Mock<IComponent>().Object; var propertyValidator = new PropertyValidator<IComponent, ISite>( c => c.Site, "Site" ); IPropertyValidator validator = propertyValidator; IPropertyValidator<IComponent> validatorOfT = propertyValidator; propertyValidator.Apply( new RequiredRule<ISite>() ); // act var actual1 = validator.ValidateObject( instance ); var actual2 = validatorOfT.ValidateObject( instance ); // assert Assert.Equal( 1, actual1.Count ); Assert.Equal( 1, actual2.Count ); }
public IHttpActionResult UpdateProperty(int id, Dto.Models.Property propertyDto) { loggedInUser = GetLoggedInUser(); if (!ModelState.IsValid) { return BadRequest(ModelState); } var result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return new ValidatorError("Validation failed for updated property DTO", HttpStatusCode.BadRequest, result, Request); } if (id != propertyDto.Id) { return new BadRequestErrorMessageResult("Updated property DTO id mismatch", this); } if (propertyDto.CompanyId != loggedInUser.CompanyId) { return BadRequest("Updated property does not belong to same company as logged in user"); } else if (db.Properties.Count(p => p.CompanyId == loggedInUser.CompanyId && p.Id != propertyDto.Id && p.Name == propertyDto.Name) > 0) { return new BadRequestErrorMessageResult("Another property has the same name as this property", this); } var propertyEntity = Mapper.Map<Dto.Models.Property, Entity.Models.Property>(propertyDto); db.Properties.Attach(propertyEntity); db.Entry(propertyEntity).State = EntityState.Modified; if (propertyDto.Users != null) { // Update Users for Property db.Entry(propertyEntity).Collection(u => u.Users).Load(); // force load var userIdList = propertyDto.Users.Select(u => u.Id); var newUsers = db.Users.Where(u => userIdList.Contains(u.Id)).ToList(); propertyEntity.Users = newUsers; // for this to work, existing Users must have been forced loaded. } try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PropertyExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public void Validate_Property_With_PropertyNameOverrideExpression_IsValid() { var emptyContact = new Contact(); emptyContact.FirstName = "George's last name"; emptyContact.LastName = string.Empty; var propertyValidator = new PropertyValidator<Contact, string>(contact => contact.LastName); propertyValidator.PropertyNameOverrideExpression = new Func<Contact, string>( o => o.FirstName); //add a single rule var lengthValidator = new LengthBetween<Contact>(1, 5); propertyValidator.AndRule(lengthValidator); //Validate ValidationNotification notification = new ValidationNotification(); propertyValidator.Validate(emptyContact, null, notification); Assert.That(notification.Errors, Is.Not.Empty); }
public IHttpActionResult NewProperty(Dto.Models.Property propertyDto) { loggedInUser = GetLoggedInUser(); if (!ModelState.IsValid) { return BadRequest(ModelState); } var result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return new ValidatorError("Validation failed for new property DTO", HttpStatusCode.BadRequest, result, Request); } if (propertyDto.CompanyId != loggedInUser.CompanyId) { return BadRequest("Property does not belong to same company as logged in user"); } else if (db.Properties.Count(p => p.CompanyId == loggedInUser.CompanyId && p.Id != propertyDto.Id && p.Name == propertyDto.Name) > 0) { return new BadRequestErrorMessageResult("Another property has the same name as this property", this); } var propertyEntity = Mapper.Map<Dto.Models.Property, Entity.Models.Property>(propertyDto); if (propertyDto.Users != null) { var userIdList = propertyDto.Users.Select(u => u.Id); var newUsers = db.Users.Where(u => userIdList.Contains(u.Id)).ToList(); propertyEntity.Users = newUsers; // for this to work, existing Users must have been forced loaded. } var company = db.Companies.Find(propertyEntity.CompanyId); company.Properties.Add(propertyEntity); db.SaveChanges(); propertyDto = Mapper.Map<Entity.Models.Property, Dto.Models.Property>(propertyEntity); GenerateUserPhotoLinks(propertyDto.Users); result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return new ValidatorError("Error mapping property DTO from database", HttpStatusCode.InternalServerError, result, Request); } return CreatedAtRoute("NewPropertyRoute", new { id = propertyDto.Id }, propertyDto); }
public IHttpActionResult DeleteProperty(int id) { loggedInUser = GetLoggedInUser(); var propertyEntity = db.Properties.FirstOrDefault(p => p.CompanyId == loggedInUser.CompanyId && p.Id == id); if (propertyEntity == null) { return NotFound(); } if (propertyEntity.CompanyId != loggedInUser.CompanyId) { return BadRequest("Requested property does not belong to same company as logged in user"); } // Get DTO object before deleting or this will fail. var propertyDto = Mapper.Map<Entity.Models.Property, Dto.Models.Property>(propertyEntity); GenerateUserPhotoLinks(propertyDto.Users); var result = new PropertyValidator().Validate(propertyDto); if (!result.IsValid) { return new ValidatorError("Error mapping property DTO from database", HttpStatusCode.InternalServerError, result, Request); } // EF diagram won't support cascade deletes on many-to-many relationships, so we have to manually // delete properties for user here. foreach (var u in propertyEntity.Users) { u.Properties.Remove(propertyEntity); } db.Properties.Remove(propertyEntity); db.SaveChanges(); return Ok(propertyDto); }
private void SelectPropertyName(object instance, PropertyValidator validator) { var instanceType = instance.GetType(); var validationProperty = GetValidationProperty(validator, instanceType); if(validationProperty != null) { DisplayAttribute displayAttribute = null; if (!_attributeBag.ContainsKey(validationProperty)) { var displayAttributeQry = (from attribute in validationProperty.GetCustomAttributes(true) where attribute is DisplayAttribute select attribute).ToList(); if (displayAttributeQry.Any()) { displayAttribute = displayAttributeQry.First() as DisplayAttribute; } _attributeBag[validationProperty] = displayAttribute; } else { displayAttribute = _attributeBag[validationProperty]; } if (displayAttribute != null) { PropertyName = displayAttribute.GetName(); } } if (String.IsNullOrEmpty(PropertyName)) { PropertyName = validator.PropertyName.SplitPascalCase(); } }
private static PropertyInfo GetValidationProperty(PropertyValidator validator, Type instanceType) { if (!_propertyBag.ContainsKey(instanceType)) { _propertyBag.Add(instanceType, new Dictionary<string, PropertyInfo>()); } var propertyBag = _propertyBag[instanceType]; if (string.IsNullOrEmpty(validator.PropertyName)) { return null; } if (!propertyBag.ContainsKey(validator.PropertyName)) { propertyBag.Add(validator.PropertyName, instanceType.GetProperty(validator.PropertyName)); } var validationProperty = propertyBag[validator.PropertyName]; return validationProperty; }