Exemple #1
0
        /// <summary>
        /// Le e valida configuracoes.
        /// <para>
        /// Verifica se existe uma secao do IConfiguration cuja o nome coincide com o nome do tipo T fornecido,
        /// caso a secao exista, le as propriedades da secao e vincula a uma nova instancia do tipo T;
        /// caso a secao nao existe, tentar ler as propriedades da raiz do IConfiguration e vincula a uma nova instancia do tipo T;
        /// </para>
        /// <para>
        /// Posteriormente a instancia T criada eh validada com base em Otc.ComponentModel.Annotation; caso a validacao
        /// falhe, uma excecao do tipo InvalidOperationException sera lancada.
        /// </para>
        /// </summary>
        /// <typeparam name="T">Tipo do objeto a ser criado e devolvido.</typeparam>
        /// <param name="configuration">O object IConfiguration.</param>
        /// <exception cref="InvalidOperationException" />
        /// <returns>O objeto preenchido com os valores presentes nas configuracoes</returns>
        public static T SafeGet <T>(this IConfiguration configuration)
        {
            var typeName = typeof(T).Name;

            if (configuration.GetChildren().Any(item => item.Key == typeName))
            {
                configuration = configuration.GetSection(typeName);
            }

            T model = configuration.Get <T>();

            if (model == null)
            {
                throw new InvalidOperationException(
                          $"Item de configuracao nao encontrado para o tipo {typeof(T).FullName}.");
            }

            if (!ModelValidator.TryValidate(model, out IEnumerable <ValidationResult> errors))
            {
                string message = $"A validacao de configuracao para o tipo '{model.GetType().FullName}' falhou: " +
                                 string.Join(", ", errors.Select(r => $"\"{r.ErrorMessage}\""));

                throw new InvalidOperationException(message);
            }

            return(model);
        }
Exemple #2
0
 private static void ValidateModel(object model)
 {
     if (!ModelValidator.TryValidate(model, out IEnumerable <ValidationResult> errors))
     {
         throw new ModelValidationException(
                   errors.Select(e =>
                                 new ModelValidationError(e.ErrorKey, e.ErrorMessage)).ToArray());
     }
 }
        public void ValidateDemoPatient()
        {
            var s = this.GetType().Assembly.GetManifestResourceStream("Hl7.Fhir.Test.patient-example.xml");

            var patient = FhirParser.ParseResource(XmlReader.Create(s));

            ICollection <ValidationResult> dummy = new List <ValidationResult>();

            ModelValidator.Validate(patient);

            Assert.IsTrue(ModelValidator.TryValidate(patient, dummy));
        }
Exemple #4
0
        public void TryValidate_SingleInvalidProperty_ReturnsSingleValidationResult()
        {
            var validatableObject = new ValidatableObject {
                Name = "N", Description = "Description"
            };
            var modelValidator = new ModelValidator();

            var isModelValid = modelValidator.TryValidate(validatableObject, out var validationResults);

            Assert.IsFalse(isModelValid);
            Assert.AreEqual(1, validationResults.Count);
            var nameValidationResult = validationResults.Single();

            Assert.AreEqual("Invalid value for Name, length must be greater than 2.", nameValidationResult.ErrorMessage);
            CollectionAssert.AreEquivalent(new[] { "Name" }, nameValidationResult.MemberNames);
        }
        /// <summary>
        /// Serialize an input (model) into JSON string
        /// </summary>
        /// <param name="obj">Object.</param>
        /// <returns>JSON string.</returns>
        public String Serialize(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            if (!modelValidator.TryValidate(obj, out ICollection <ValidationResult> validationResults))
            {
                throw new ModelValidationException(obj.GetType().Name, validationResults);
            }

            try
            {
                return(JsonConvert.SerializeObject(obj));
            }
            catch (Exception e)
            {
                throw new ApiException(500, e.Message);
            }
        }
Exemple #6
0
        public void TryValidate_TwoInvalidProperties_ReturnsMultipleValidationResults()
        {
            var validatableObject = new ValidatableObject {
                Name = "N", Description = "D"
            };
            var modelValidator = new ModelValidator();

            var isModelValid = modelValidator.TryValidate(validatableObject, out var validationResults);

            Assert.IsFalse(isModelValid);
            Assert.AreEqual(2, validationResults.Count);

            var nameValidationResult = validationResults.Single(vr => vr.ErrorMessage.Contains("Name"));

            Assert.AreEqual("Invalid value for Name, length must be greater than 2.", nameValidationResult.ErrorMessage);
            CollectionAssert.AreEquivalent(new[] { "Name" }, nameValidationResult.MemberNames);

            var descriptionValidationResult = validationResults.Single(vr => vr.ErrorMessage.Contains("Description"));

            Assert.AreEqual("Invalid value for Description, length must be greater than 3.", descriptionValidationResult.ErrorMessage);
            CollectionAssert.AreEquivalent(new[] { "Description" }, descriptionValidationResult.MemberNames);
        }
 private static IEnumerable <ValidationResult> GetErrosFromModel(object model)
 {
     ModelValidator.TryValidate(model, out IEnumerable <ValidationResult> errors);
     return(errors);
 }