예제 #1
0
 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);
        }
예제 #4
0
        /// <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());
            }
        }
예제 #5
0
 /// <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);
     }
 }
예제 #6
0
        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);
        }
예제 #8
0
        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);
        }
예제 #9
0
    private static void RegisterPairOfTypes(Type mainType, Type buddyType)
    {
        AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider
            = new AssociatedMetadataTypeTypeDescriptionProvider(mainType, buddyType);

        TypeDescriptor.AddProviderTransparent(typeDescriptionProvider, mainType);
    }
예제 #10
0
            /// <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));
            }
예제 #11
0
        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));
 }
예제 #14
0
 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));
 }
예제 #15
0
        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);
        }
예제 #16
0
        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);
            }
        }
예제 #17
0
 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));
 }
예제 #18
0
        /// <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);
        }
예제 #19
0
 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));
 }
예제 #20
0
 public Note()
 {
     TypeDescriptor.AddProviderTransparent(
         new AssociatedMetadataTypeTypeDescriptionProvider(
             typeof(Note),
             typeof(NoteMetadata)),
         typeof(Note));
 }
예제 #21
0
 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));
 }
예제 #22
0
 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));
 }
예제 #23
0
 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));
 }
예제 #24
0
 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));
 }
예제 #25
0
        //    [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));
        }
예제 #26
0
        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));
        }
예제 #27
0
 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));
 }
예제 #28
0
        //    [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));
        }
예제 #29
0
 static ChoMetadataTypesRegister()
 {
     foreach (Type type in ChoType.GetTypes(typeof(MetadataTypeAttribute)))
     {
         MetadataTypeAttribute attrib = ChoType.GetAttribute <MetadataTypeAttribute>(type);
         TypeDescriptor.AddProviderTransparent(
             new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type);
     }
 }
예제 #30
0
 public MetadataClientTypeAttribute(Type modelType, Type dataType)
 {
     TypeDescriptor.AddProviderTransparent(
         new AssociatedMetadataTypeTypeDescriptionProvider(
             modelType,
             dataType
             ),
         modelType);
 }