public static void Add <TModel, TMetadata>(this ModelMetadataProvider provider) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider( typeof(TModel), typeof(TMetadata)), typeof(TModel)); }
public static void InstallForThisAssembly() { if (_installed) { return; } lock (InstalledLock) { if (_installed) { return; } var types = Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name.Contains("GestionAdministrativa")) .Select(x => Assembly.Load(x)) .SelectMany(x => x.GetTypes()); foreach (Type type in types) { foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)) { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type); } } _installed = true; } }
public void Cliente_AlterarCliente_DeveFalharDevidoClienteInvalido() { //Arrange var cliente = _clienteTestsFixture.GerarClientes(1, true, false).FirstOrDefault(); var iApplicationServiceCliente = new Mock <IClienteApplicationService>(); iApplicationServiceCliente.Setup(c => c.Alterar(cliente)).Verifiable(); var context = new ValidationContext(cliente, null, null); var results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(ClienteDTO), typeof(ClienteDTO)), typeof(ClienteDTO)); var clientesController = new ClientesController(iApplicationServiceCliente.Object); //Act clientesController.NotFound(cliente); var isModelStateValid = Validator.TryValidateObject(cliente, context, results, true); // Assert iApplicationServiceCliente.Verify(c => c.Alterar(cliente), Times.Never); Assert.False(isModelStateValid); }
/// <summary> /// Validate specific proprty in entity /// </summary> /// <param name="columnName">proprty name</param> /// <returns></returns> public string this[string columnName] { get { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(this.GetType()), this.GetType()); StringBuilder b = new StringBuilder(); var context = new ValidationContext(this, serviceProvider: null, items: null) { MemberName = columnName }; var results = new List <System.ComponentModel.DataAnnotations.ValidationResult>(); foreach (var itm in this.GetType().GetProperties()) { if (itm.Name == columnName) { var isValid = Validator.TryValidateProperty(itm.GetValue(this, null), context, results); if (!isValid) { foreach (var validationResult in results) { b.AppendLine(validationResult.ErrorMessage); } } } } return(b.ToString()); } }
/// <summary> /// Register the MetadataType class for a certain type. /// </summary> public static void Register(Type type) { foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type); } }
public async Task CreatePostModelValidationTestAsync() { HotelContext db = new HotelContext(); DepartmentsController controller = new DepartmentsController(db); Department dep = new Department(); dep.Depname = "test"; var context = new ValidationContext(dep, null, null); var results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider( typeof(Department), typeof(Department)), typeof(Department) ); var isModelStateValid = Validator.TryValidateObject(dep, context, results, true); var expected = await controller.Create(dep); Assert.IsTrue(isModelStateValid); var removeTestObjects = db.Departments.Where(x => x.Depname == "test").ToList(); db.Departments.RemoveRange(removeTestObjects); db.SaveChanges(); }
public void Should_Return_Success_When_Valid_Bank_Model() { var client = new ClientModel(); client.Name = "Marlon"; client.LastName = "Graciano Machado de Amorim"; client.Type = (KindPerson)1; var address = new AddressModel(); address.City = "Rio de Janeiro"; address.Country = "Brasil"; address.Neighborhood = "Campo Grande"; address.Number = 55; address.Street = "Rua Argoin"; var bankAccount = new BankAccountModel(); bankAccount.AccountNumber = 12345; bankAccount.AgencyNumber = 1234; bankAccount.Type = (BankAccountType)1; bankAccount.Owner = client; bankAccount.Address = address; var context = new ValidationContext(bankAccount, null, null); var results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(BankAccountModel), typeof(BankAccountModel)), typeof(BankAccountModel)); var isModelStateValid = Validator.TryValidateObject(bankAccount, context, results, true); Assert.IsTrue(isModelStateValid); }
public static string ValidateProperty <MetadataType>(this object obj, string propertyName) { if (string.IsNullOrEmpty(propertyName)) { return(string.Empty); } var targetType = obj.GetType(); if (targetType != typeof(MetadataType)) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(MetadataType)), targetType); } var propertyValue = targetType.GetProperty(propertyName).GetValue(obj, null); var validationContext = new ValidationContext(obj, null, null) { MemberName = propertyName }; var validationResults = new List <ValidationResult>(); Validator.TryValidateProperty(propertyValue, validationContext, validationResults); if (validationResults.Count > 0) { return(validationResults.First().ErrorMessage); } return(string.Empty); }
private static void RegisterPairOfTypes(Type mainType, Type buddyType) { AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider = new AssociatedMetadataTypeTypeDescriptionProvider(mainType, buddyType); TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, mainType); }
/// <summary> /// Validates the specified child entity. /// </summary> /// <typeparam name="U">The type of the entity</typeparam> /// <param name="type">The type.</param> /// <param name="entity">The entity.</param> /// <returns> /// Return <see cref="EntityValidationResult" />. /// </returns> private EntityValidationResult ValidateEntity <U>(Type type, U entity) { if (!_metaDataTypeList.ContainsKey(type.Name)) { var metadataAttrib = entity.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType <MetadataTypeAttribute>().FirstOrDefault(); System.Type buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : entity.GetType(); if (_callBack != null) { _callBack(type.Name, new AssociatedMetadataTypeTypeDescriptionProvider(type, buddyClassOrModelClass)); } } TypeDescriptor.AddProviderTransparent(_metaDataTypeList[type.Name], type); var validationResults = new List <ValidationResult>(); var vc = new ValidationContext(entity, null, null); var isValid = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, vc, validationResults, true); var errorList = validationResults.Select(r => new EntityValidationError { EntityType = type, ErrorResult = r }).ToList(); return(new EntityValidationResult(errorList)); }
static ChoMetadataTypesRegister() { foreach (Type type in ChoType.GetTypes(typeof(MetadataTypeAttribute))) { MetadataTypeAttribute attrib = type.GetCustomAttribute <MetadataTypeAttribute>(); if (attrib == null || attrib.MetadataClassType == null) { continue; } TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type); } foreach (Type type in ChoType.GetTypes(typeof(ChoMetadataRefTypeAttribute))) { ChoMetadataRefTypeAttribute attrib = type.GetCustomAttribute <ChoMetadataRefTypeAttribute>(); if (attrib == null || attrib.MetadataRefClassType == null) { continue; } TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(attrib.MetadataRefClassType, type), attrib.MetadataRefClassType); } }
public static string Validate(SIPAccount sipAccount) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(SIPAccount), typeof(SIPAccountMetadata)), typeof(SIPAccount)); var validationContext = new ValidationContext(sipAccount, null, null); var validationResults = new List <ValidationResult>(); Validator.TryValidateObject(sipAccount, validationContext, validationResults); if (validationResults.Count > 0) { return(validationResults.First().ErrorMessage); } else { Guid testGuid = Guid.Empty; if (!Guid.TryParse(sipAccount.ID, out testGuid)) { return("The ID was not a valid GUID."); } else if (String.Compare(sipAccount.SIPUsername, BANNED_SIPACCOUNT_NAME, true) == 0) { return("The username you have requested is not permitted."); } else if (sipAccount.SIPUsername.Contains(".") && (sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim().Length >= SIPAccount.USERNAME_MIN_LENGTH && sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() != sipAccount.Owner)) { return("You are not permitted to create this username. Only user " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() + " can create SIP accounts ending in " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".")).Trim() + "."); } } return(null); }
public void TestFixtureSetUp() { // this required in non-MVC, RIA, DynamicData environments for MetaDataType to work with Validator TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(typeof(BookingWithMetadataType), typeof(IBookingMetadataType)), typeof(BookingWithMetadataType)); }
public void SetUp() { gameDetail = new GameDetail(); context = new ValidationContext(gameDetail, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(GameDetail), typeof(GameDetailMetadata)), typeof(GameDetail)); }
public static bool ValidateProperty <MetadataType>(this object obj, int index) { var targetType = obj.GetType(); var propertyName = obj.GetType().GetProperties()[index].Name; if (propertyName == "Item" || propertyName == "Error") { return(false); } bool isError = false; if (targetType != typeof(MetadataType)) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(MetadataType)), targetType); } var propertyValue = targetType.GetProperty(propertyName).GetValue(obj, null); var validationContext = new ValidationContext(obj, null, null) { MemberName = propertyName }; var validationResults = new List <ValidationResult>(); Validator.TryValidateProperty(propertyValue, validationContext, validationResults); if (validationResults.Count > 0) { isError = true; } else { isError = false; } return(isError); }
public static bool IsPropertyValid <Metadata>(this object obj, object value, ref Dictionary <string, string> errors) { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(obj.GetType(), typeof(Metadata)), obj.GetType()); var validationContext = new ValidationContext(obj, null, null); var validationResults = new List <ValidationResult>(); Validator.TryValidateProperty(value, validationContext, validationResults); if (validationResults.Count > 0 && errors == null) { errors = new Dictionary <string, string>(validationResults.Count); } foreach (var validationResult in validationResults) { errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage); } if (validationResults.Count > 0) { return(false); } else { return(true); } }
public void SetUp() { cart = new Cart(); context = new ValidationContext(cart, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Cart), typeof(CartMetadata)), typeof(Cart)); }
/// <summary> /// Manually the model validation. /// </summary> /// <typeparam name="T">The type of the T</typeparam> /// <typeparam name="TM">The type of the m.</typeparam> /// <param name="tvalue">The t value.</param> /// <param name="tmvalue">The m value.</param> /// <returns>List ValidationResult</returns> public static List <ValidationResult> ManuallyModelValidation <T, TM>(T tvalue, TM tmvalue) { TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(TM)), typeof(T)); var validationResults = new List <ValidationResult>(); return(validationResults); }
public void SetUp() { genre = new Genre(); genre.genreCode = "Horror"; context = new ValidationContext(genre, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Genre), typeof(GenreMetadata)), typeof(Genre)); }
public Note() { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider( typeof(Note), typeof(NoteMetadata)), typeof(Note)); }
public void SetUp() { order = new Order(); order.status = "Pending"; context = new ValidationContext(order, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Order), typeof(OrderMetadata)), typeof(Order)); }
public void SetUp() { platform = new Platform(); platform.platformCode = "N64"; context = new ValidationContext(platform, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Platform), typeof(PlatformMetadata)), typeof(Platform)); }
public void SetUp() { prov = new Province(); prov.provinceCode = "Ontario"; context = new ValidationContext(prov, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Province), typeof(ProvinceMetadata)), typeof(Province)); }
public void SetUp() { role = new Role(); role.roleCode = "Employee"; context = new ValidationContext(role, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Role), typeof(RoleMetadata)), typeof(Role)); }
// [RegularExpression(@"^(?=.*[a-z])(?=.*\d)[a-zA-Z\d]{8,}$", //ErrorMessage = "Password must contain, letters and numbers")] // [Required(ErrorMessage = "Your password is too short")] // [NotMapped] // public string AnotherPasword { get; set; } // private string anotherPasword; // [RegularExpression(@"^(?=.*[a-z])(?=.*\d)[a-zA-Z\d]{8,}$", //ErrorMessage = "Password must contain, letters and numbers")] // [Required(ErrorMessage = "Your password is too short")] // [NotMapped] // public string AnotherPasword // { // get { return anotherPasword; } // set { anotherPasword = value; RaisePropertyChanged("Address1"); } // } public void MetaSetUp() { // In wpf you need to explicitly state the metadata file. // Maybe this will be improved in future versions of EF. TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(typeof(boring_bar), typeof(BoringBarMetadata)), typeof(boring_bar)); }
private static bool TestModel <T>(T model) { var context = new ValidationContext(model, null, null); var results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(T)), typeof(T)); return(Validator.TryValidateObject(model, context, results, true)); }
public void SetUp() { review = new Review(); review.status = "Pending"; review.revComment = "This is a great comment"; context = new ValidationContext(review, null, null); results = new List <ValidationResult>(); TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Review), typeof(ReviewMetadata)), typeof(Review)); }
// [RegularExpression(@"^(?=.*[a-z])(?=.*\d)[a-zA-Z\d]{8,}$", //ErrorMessage = "Password must contain, letters and numbers")] // [Required(ErrorMessage = "Your password is too short")] // [NotMapped] // public string AnotherPasword { get; set; } // private string anotherPasword; // [RegularExpression(@"^(?=.*[a-z])(?=.*\d)[a-zA-Z\d]{8,}$", //ErrorMessage = "Password must contain, letters and numbers")] // [Required(ErrorMessage = "Your password is too short")] // [NotMapped] // public string AnotherPasword // { // get { return anotherPasword; } // set { anotherPasword = value; RaisePropertyChanged("Address1"); } // } public void MetaSetUp() { // In wpf you need to explicitly state the metadata file. // Maybe this will be improved in future versions of EF. TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(typeof(document_spindle), typeof(DocumentSpindleMetaData)), typeof(document_spindle)); }
static ChoMetadataTypesRegister() { foreach (Type type in ChoType.GetTypes(typeof(MetadataTypeAttribute))) { MetadataTypeAttribute attrib = ChoType.GetAttribute <MetadataTypeAttribute>(type); TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type); } }
public MetadataClientTypeAttribute(Type modelType, Type dataType) { TypeDescriptor.AddProviderTransparent( new AssociatedMetadataTypeTypeDescriptionProvider( modelType, dataType ), modelType); }