public void UniqueKeyExceptionIsRecognized1()
        {
            // --- Arrange
            var child1 = new ChildRecord
            {
                Name  = "Child1",
                Value = 1
            };
            var child2 = new ChildRecord
            {
                Name  = "Child1",
                Value = 2
            };

            // --- Act
            UniqueKeyViolationException exCaught = null;

            try
            {
                using (var ctx = DataAccessFactory.CreateContext <ITestDataOperations>())
                {
                    ctx.InsertChild(child1);
                    ctx.InsertChild(child2);
                }
            }
            catch (UniqueKeyViolationException ex)
            {
                exCaught = ex;
            }

            // --- Assert
            // ReSharper disable once PossibleNullReferenceException
            exCaught.TableName.ShouldEqual("dbo.Child");
            exCaught.KeyName.ShouldEqual("AK_Child_Name");
        }
Exemplo n.º 2
0
        public void al_actualizar_una_persona_con_email_existente_debe_devolver_una_excepción_de_tipo_UniqueKeyViolationException_en_donde_el_data_contenga_la_key_errorCode_con_valor_ERR_PERSONA_EMAILEXIST()
        {
            // Arrange.
            Persona persona = new Persona()
            {
                Id                    = 1,
                NombreCompleto        = "Testing, Uno",
                EMail                 = "*****@*****.**",
                TotalAhorro           = 100.0M,
                PorcAhorro            = 1.0M,
                Direccion             = "Server de testing 1",
                Lat                   = -34.6377278M,
                Lon                   = -58.4098517M,
                Estado                = AccountStatus.Active,
                FechaNacimiento       = DateTime.Now,
                RecibirNotificaciones = true,
                Sexo                  = "M",
                Password              = "******",
                RegionalData          = new RegionalData()
                {
                    CountryCode = "AR"
                }
            };

            UniqueKeyViolationException ukvex = new UniqueKeyViolationException("xxx UK_Personas_EMail xxx.");

            // Mock del repository.
            Mock <IPersonaRepository> personaRepositoryMock = new Mock <IPersonaRepository>();

            personaRepositoryMock.Setup(mgr => mgr.Update(It.IsAny <Persona>())).Throws(ukvex);

            PersonaManager personaManager = new PersonaManager(personaRepositoryMock.Object, new PersonaValidator(), new PagedListValidator());

            // Act.
            Action action = () => personaManager.Update(persona);

            // Assert.
            action.Should().ThrowExactly <UniqueKeyViolationException>()
            .And.Data.Should().Contain(new DictionaryEntry("ErrorCode", ExErrorCode.ErrPersonaEmailExist));
        }
Exemplo n.º 3
0
        public void al_insertar_un_nuevo_pais_con_codigoIata_existente_debe_devolver_una_excepción_UniqueKeyViolationException_en_donde_el_data_contenga_una_key_ErrorCode_con_valor_ERR_PAIS_IATACODEEXIST()
        {
            // Arrange.
            Pais pais = PaisMockGenerator.GetByCodigoIata("AR");

            UniqueKeyViolationException ukvex = new UniqueKeyViolationException("xxx PRIMARY xxx.");

            // Mock del repository.
            Mock <IPaisRepository> paisRepositoryMock = new Mock <IPaisRepository>();

            paisRepositoryMock.Setup(mgr => mgr.Insert(It.IsAny <Pais>())).Throws(ukvex);

            PaisManager paisManager = new PaisManager(paisRepositoryMock.Object, new PaisValidator(), new PagedListValidator());

            // Act.
            Action action = () => paisManager.Insert(pais);

            // Assert.
            pais.CodigoIata.Should().BeEquivalentTo("AR");
            action.Should().ThrowExactly <UniqueKeyViolationException>()
            .And.Data.Should().Contain(new DictionaryEntry("ErrorCode", ExErrorCode.ErrPaisIataCodeExist));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Procesa la excepción de base de datos especificada y devuelve una excepción core agregando
        /// datos de la consulta y la excepción original como inner.
        /// </summary>
        /// <param name="conn">La nonexión usada.</param>
        /// <param name="ex">Excepción original.</param>
        /// <exception cref="ArgumentNullException">El argumento ex es null.</exception>
        /// <returns>Una excepción core.</returns>
        public static Exception Process(IDbConnection conn, Exception ex)
        {
            if (ex == null)
            {
                throw new ArgumentNullException(nameof(ex));
            }

            /*
             * Para estos casos no hace falta tratamiento:
             * ==========================================
             * Servicio de base de datos apagado (InternalServerError, UnableToConnectToHost).
             * Nombre de base de datos incorrecta (InternalServerError, AuthenticationFailed).
             * Credenciales de base de datos incorrecta (InternalServerError, AuthenticationFailed).
             *
             */

            string constraintName = null;

            Apollo.NetCore.Core.Exceptions.DataException dex;
            MySqlException mysqlEx = ex as MySqlException;

            if (mysqlEx != null)
            {
                // Exception de MySql.
                switch (mysqlEx.Number)
                {
                case MySqlErrCodeUkDuplicateEntry:
                    // Duplicate entry.

                    /*
                     * Ejemplos de mensajes:
                     * Message = "Duplicate entry 'Traslada' for key 'UK_Name'"
                     * Message = "Duplicate entry '1' for key 'PRIMARY'"
                     */
                    constraintName = GetConstraintName(mysqlEx.Message, "UK");
                    dex            = new UniqueKeyViolationException(mysqlEx.Message, mysqlEx, constraintName);
                    break;

                case MySqlErrCodeFkConstrainFails:
                    // Foreign key constraint fails.

                    /*
                     * Ejemplos de mensajes:
                     * Message = "Cannot delete or update a parent row: a foreign key constraint fails (`zwitcher`.`appendpointconfig`, CONSTRAINT `FK_AppConfig_Id` FOREIGN KEY (`AppConfigId`) REFERENCES `appconfig` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION)"
                     */

                    constraintName = GetConstraintName(mysqlEx.Message, "FK");
                    dex            = new ReferentialIntegrityViolationException(mysqlEx.Message, mysqlEx, constraintName);
                    break;

                default:
                    // Otra excepción de MySql.
                    dex = new Apollo.NetCore.Core.Exceptions.DataException(mysqlEx.Message, mysqlEx);
                    break;
                }
            }
            else
            {
                // Otra exepción.
                dex = new Apollo.NetCore.Core.Exceptions.DataException(ex.Message, ex);
            }

            // Agrega al data de la excepción datos de la conexión.
            if (conn != null)
            {
                // TODO:
            }

            if (!string.IsNullOrWhiteSpace(constraintName))
            {
                dex.Data.Add(ExDataKey.ConstraintName, constraintName);
            }

            throw dex;
        }