コード例 #1
0
        public async Task ResourceValidationExceptionShouldReturnExpectedCode(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string message,
            string entityType,
            string entityId,
            string errorMessage)
        {
            var expectedErrors = new List <ValidationError> {
                new ValidationError(entityType, entityId, ValidationErrorCode.Invalid, errorMessage)
            };

            var thrownException = new EntityValidationException(new ValidationErrorDetails(message, expectedErrors));

            exceptionService.Setup(s => s.Execute()).Throws(thrownException);

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                try
                {
                    await response.HandleErrors();
                }
                catch (EntityValidationException exception)
                {
                    Assert.Equal("AR422", exception.Event.Code);
                }
            }
        }
コード例 #2
0
        public async Task ResourceValidationExceptionShouldIncludeExpectedErrors(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            string code,
            string message,
            string errorMessage)
        {
            var expectedErrors = new List <ValidationError> {
                new ValidationError("EntityType", "EntityId", ValidationErrorCode.Invalid, errorMessage)
            };

            var thrownException = new EntityValidationException(code, new ValidationErrorDetails(message, expectedErrors));

            exceptionService.Setup(s => s.Execute()).Throws(thrownException);

            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                try
                {
                    await response.HandleErrors();
                }
                catch (EntityValidationException exception)
                {
                    var errors = exception.Event?.ErrorDetails?.Errors;
                    errors.Should().BeEquivalentTo(expectedErrors);
                }
            }
        }
コード例 #3
0
        public void DadoUmFornecedorPFMenorDeIdade_AoCadastrarFornecedorNumaEmpresaDoParana_DeveImpedirOCadastro()
        {
            DadoUmFornecedorPFMenorDeIdade();
            EntityValidationException ex = Assert.Throws <EntityValidationException>(() => AoCadastrarFornecedor());

            ex.Erros[0].Should().Be("Fornecedores do Paraná devem ser maiores de idade.");
            ex.Message.Should().Be("Entidade inválida");
        }
コード例 #4
0
        public void DadoUmFornecedorPFSemRgEDataDeNascimento_AoCadastrarFornecedor_DeveImpedirOCadastro()
        {
            DadoUmFornecedorPFSemRgEDataDeNascimento();
            EntityValidationException ex = Assert.Throws <EntityValidationException>(() => AoCadastrarFornecedor());

            ex.Erros[0].Should().Be("O campo RG de fornecedor deve deve ter entre 5 e 11 números.");
            ex.Erros[1].Should().Be("A data de nascimento é obrigatória para pessoa física.");
            ex.Message.Should().Be("Entidade inválida");
        }
コード例 #5
0
        public void Validate(T entity)
        {
            EntityValidationException <T> exception = null;

            if (this.exceptionQueue.TryDequeue(out exception))
            {
                throw exception;
            }
            throw new InvalidOperationException("Fake queue was empty");
        }
コード例 #6
0
        public async Task ResourceValidationResponseShouldThrowValidationException(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            EntityValidationException exception)
        {
            exceptionService.Setup(s => s.Execute()).Throws(exception);
            using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create())
            {
                var response = await server.HttpClient.GetAsync("/");

                await Assert.ThrowsAsync <EntityValidationException>(() => response.HandleErrors());
            }
        }
コード例 #7
0
ファイル: DataContextInternal.cs プロジェクト: Sellec/OnUtils
        private void PrepareEFException(Exception exSource)
        {
            if (exSource is DbUpdateConcurrencyException)
            {
                var ex2   = exSource as DbUpdateConcurrencyException;
                var newEx = new UpdateConcurrencyException(
                    ex2.Message,
                    ex2.InnerException,
                    ex2.Entries.Select(x => new RepositoryEntryInternal(x)));

                throw newEx;
            }
            else if (exSource is DbUpdateException)
            {
                var ex2 = exSource as DbUpdateConcurrencyException;
                if (ex2 != null)
                {
                    var newEx = new UpdateException(
                        ex2.Message,
                        ex2.InnerException,
                        ex2.Entries.Select(x => new RepositoryEntryInternal(x)));

                    throw newEx;
                }
                else
                {
                    var newEx = new UpdateException(
                        exSource.Message,
                        exSource.InnerException,
                        null);
                    throw newEx;
                }
            }
            else if (exSource is System.Data.Entity.Validation.DbEntityValidationException)
            {
                var ex2 = exSource as System.Data.Entity.Validation.DbEntityValidationException;

                var newEx = new EntityValidationException(
                    ex2.Message,
                    ex2.EntityValidationErrors.Select(x => new EntityValidationResult(new RepositoryEntryInternal(x.Entry), x.ValidationErrors.Select(y => new ValidationError(y.PropertyName, y.ErrorMessage)))),
                    ex2.InnerException
                    );

                throw newEx;
            }
        }
コード例 #8
0
        public async Task OwinExceptionShouldInvokeLogger(
            SampleServerFactory serverFactory,
            Mock <IExceptionService> exceptionService,
            EntityValidationException exception,
            Mock <IAutoResponseLogger> logger)
        {
            logger.Setup(l => l.LogException(It.IsAny <Exception>())).Returns(Task.FromResult(0));
            exceptionService.Setup(s => s.Execute()).Throws(exception);

            using (var server = serverFactory
                                .With <IExceptionService>(exceptionService.Object)
                                .With <IAutoResponseLogger>(logger.Object)
                                .Create())
            {
                await server.HttpClient.GetAsync("/");

                logger.Verify(l => l.LogException(It.IsAny <Exception>()), Times.Once());
            }
        }
コード例 #9
0
        public static ServiceBadRequest GetValidationProblemDetails(EntityValidationException ex)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();
            var results = ex.Validation;

            var members = results.SelectMany(r => r.MemberNames);

            foreach (var member in members)
            {
                List <string> errMessages = new List <string>();
                foreach (var error in results.Where(r => r.MemberNames.Contains(member)))
                {
                    errMessages.Add(error.ErrorMessage);
                }
                errors.Add(member, errMessages.ToArray());
            }
            ServiceBadRequest details = new ServiceBadRequest(errors);

            return(details);
        }
コード例 #10
0
        /// <summary>
        ///     提交当前单元操作的结果
        /// </summary>
        /// <returns></returns>
        public int Commit()
        {
            if (IsCommitted)
            {
                return(0);
            }
            try
            {
                int result = Context.SaveChanges();
                IsCommitted = true;
                return(result);
            }
            catch (Exception ex)
            {
                var entities = from entity in Context.ChangeTracker.Entries()
                               where entity.State == EntityState.Added ||
                               entity.State == EntityState.Modified ||
                               entity.State == EntityState.Deleted
                               select entity.Entity;

                var validationResults = new List <ValidationResult>();
                foreach (var entity in entities)
                {
                    var validationContext = new ValidationContext(entity);
                    Validator.TryValidateObject(entity, validationContext, validationResults);
                }
                EntityValidationException validationException = new EntityValidationException(validationResults.Select(x => new ValidationException(x, null, null)));

                StringBuilder sbErrors = new StringBuilder();
                foreach (var err in validationException.ValidationErrors)
                {
                    var validationResult = err.ValidationResult;
                    sbErrors.Append("Error: " + validationResult.MemberNames.First() + ", Message: " + validationResult.ErrorMessage + Environment.NewLine);
                }
                throw PublicHelper.ThrowDataAccessException("提交数据验证时发生异常:" + sbErrors, ex);
            }
        }
コード例 #11
0
        public void EntityValidationExceptionLogRegister()
        {
            var validationResults = new List <ValidationResult>
            {
                new ValidationResult("Name not empty", new List <string> {
                    "Name"
                }),
                new ValidationResult("Id not empty", new List <string> {
                    "Id"
                })
            };

            var entityValidationException = new EntityValidationException(validationResults);

            GivenRequiredService().Log(entityValidationException);

            var ex = TestLog.GetException();

            ex[0].Should().BeOfType <ValidationException>();
            ex[0].As <ValidationException>().Message.Should().Be("Name not empty");

            ex[1].Should().BeOfType <ValidationException>();
            ex[1].As <ValidationException>().Message.Should().Be("Id not empty");
        }
コード例 #12
0
 public FakeEntityValidator <T> WithValidationMessage(string message)
 {
     this.exception = new EntityValidationException <T>(message);
     return(this);
 }
コード例 #13
0
        public void ErrorMessageIsPopulated()
        {
            var ex = new EntityValidationException("msg");

            Assert.AreEqual("msg", ex.Message);
        }
コード例 #14
0
 public static void AddValidationErrors(this ModelStateDictionary modelState, EntityValidationException exception)
 {
     exception.Errors.ToList().ForEach(t => modelState.AddModelError(string.Empty, t.ErrorMessage));
 }
コード例 #15
0
        public void HttpStatusCodeIsPopulated()
        {
            var ex = new EntityValidationException("msg");

            Assert.AreEqual(HttpStatusCode.InternalServerError, ex.ResponseCode);
        }
コード例 #16
0
        public void HttpErrorMessageIsPopulated()
        {
            var ex = new EntityValidationException("msg");

            Assert.AreEqual("InternalServerError", ex.HttpErrorMessage);
        }
コード例 #17
0
 private void _addValidationErrors(EntityValidationException exception)
 {
     exception.Errors.ToList().ForEach(t => ModelState.AddModelError(string.Empty, t.ErrorMessage));
 }
コード例 #18
0
        public void IsBaseException()
        {
            var ex = new EntityValidationException("msg");

            Assert.IsInstanceOfType(ex, typeof(BaseCaughtException));
        }