public async Task AddVisitsTicketTariffAsync__Already_there_is_the_same_element_in_database__Should_return_400BadRequest_response()
        {
            var ticketTariffs = new TicketTariff[] { new TicketTariff {
                                                         Id = "1", DefaultPrice = 30
                                                     } };
            var parentVisitTariff = new VisitTariff
            {
                Id            = _visitTariffId,
                UpdatedAt     = new DateTime(2019, 1, 1),
                Name          = "sample parent visit tariff name",
                TicketTariffs = ticketTariffs
            };
            var ticketTariffDto = CreateTicketTariffDto(ticketTariffs[0]);

            _mapperMock.Setup(x => x.Map <TicketTariff>(ticketTariffDto)).Returns(ticketTariffs[0]);
            _visitTariffDbServiceMock.Setup(x => x.GetAsync(It.IsNotNull <string>())).ReturnsAsync(parentVisitTariff);
            _ticketTariffDbServiceMock.Setup(x => x.RestrictedAddAsync(It.IsNotNull <TicketTariff>())).ThrowsAsync(new InvalidOperationException());

            var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

            var result = await controller.AddVisitsTicketTariffAsync(_visitTariffId, ticketTariffDto);

            (result as ObjectResult).StatusCode.Should().Be(400);
            ((result as ObjectResult).Value as ResponseWrapper).Error.Should().NotBeEquivalentTo(new ApiError());
        }
示例#2
0
        public void Validate__DefaultPrice_is_greater_than_1000__Should_be_invalid()
        {
            var invalidTicketTariff = new TicketTariff {
                DefaultPrice = 3400.0f
            };

            _validator.ShouldHaveValidationErrorFor(x => x.DefaultPrice, invalidTicketTariff);
        }
示例#3
0
        public void Validate__Description_is_null_or_empty__Should_be_invalid([Values(null, "")] string description)
        {
            var invalidTicketTariff = new TicketTariff {
                Description = description
            };

            _validator.ShouldHaveValidationErrorFor(x => x.Description, invalidTicketTariff);
        }
示例#4
0
        public void Validate__Description_has_less_than_256_characters__Should_be_valid()
        {
            var validTicketTariff = new TicketTariff {
                Description = "123456789"
            };

            _validator.ShouldNotHaveValidationErrorFor(x => x.Description, validTicketTariff);
        }
示例#5
0
        public void Validate__DefaultPrice_is_greater_than_0_and_less_than_1000__Should_be_valid()
        {
            var validTicketTariff = new TicketTariff {
                DefaultPrice = 100.0f
            };

            _validator.ShouldNotHaveValidationErrorFor(x => x.DefaultPrice, validTicketTariff);
        }
示例#6
0
        public void Validate__DefaultPrice_is_exactly_1000__Should_be_valid()
        {
            var validTicketTariff = new TicketTariff {
                DefaultPrice = 1000.0f
            };

            _validator.ShouldNotHaveValidationErrorFor(x => x.DefaultPrice, validTicketTariff);
        }
示例#7
0
        public void Validate__DefaultPrice_is_less_than_0_or_equals_to_0__Should_be_invalid([Values(-1.0f, 0.0f)] float price)
        {
            var invalidTicketTariff = new TicketTariff {
                DefaultPrice = price
            };

            _validator.ShouldHaveValidationErrorFor(x => x.DefaultPrice, invalidTicketTariff);
        }
示例#8
0
        /// <summary>
        /// Asynchronously retrieves <see cref="TicketTariff"/> entities with specified page size and page number.
        /// Throws an exception if arguments is out of range or any problem with retrieving occurred.
        /// </summary>
        /// <param name="pageNumber">Page number that will be retrieved. Must be greater than 0.</param>
        /// <param name="pageSize">Page size. Must be a positive number.</param>
        /// <returns>Set of <see cref="TicketTariff"/> entities.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="pageSize"/> is a negative number or <paramref name="pageNumber"/> is less than 1.</exception>
        /// <exception cref="InternalDbServiceException">The resource does not exist or has a null value or any
        /// other problems with retrieving data from database occurred.</exception>
        public async Task <IEnumerable <TicketTariff> > GetWithPaginationAsync(int pageNumber = 1, int pageSize = 30)
        {
            _logger.LogInformation($"Starting method '{nameof(GetWithPaginationAsync)}'.");

            if (pageNumber < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(pageNumber), $"'{pageNumber}' is not valid value for argument '{nameof(pageNumber)}'. Only number greater or equals to 1 is valid.");
            }

            if (pageSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageSize), $"'{pageSize}' is not valid value for argument '{nameof(pageSize)}'. Only number greater or equals to 0 is valid.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.TicketTariffs ?? throw new InternalDbServiceException($"Table of type '{typeof(TicketTariff).Name}' is null.");

            try
            {
                IEnumerable <TicketTariff> tariffs = new TicketTariff[] { }.AsEnumerable();
                int maxNumberOfPageWithData;

                int numberOfResourceElements = await _context.TicketTariffs.CountAsync();

                int numberOfElementsOnLastPage = numberOfResourceElements % pageSize;
                int numberOfFullPages          = (numberOfResourceElements - numberOfElementsOnLastPage) / pageSize;

                if (numberOfElementsOnLastPage > 0)
                {
                    maxNumberOfPageWithData = ++numberOfFullPages;
                    _logger.LogWarning($"Last page of data contain {numberOfElementsOnLastPage} elements which is less than specified in {nameof(pageSize)}: {pageSize}.");
                }
                else
                {
                    maxNumberOfPageWithData = numberOfFullPages;
                }

                if (numberOfResourceElements == 0 || pageSize == 0 || pageNumber > maxNumberOfPageWithData)
                {
                    _logger.LogInformation($"Finished method '{nameof(GetWithPaginationAsync)}'. Returning {tariffs.Count()} elements.");
                    return(tariffs);
                }

                _logger.LogDebug($"Starting retrieve data. '{nameof(pageNumber)}': {pageNumber.ToString()}, '{nameof(pageSize)}': {pageSize.ToString()}.");
                tariffs = _context.TicketTariffs.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
                _logger.LogDebug("Retrieve data succeeded.");
                _logger.LogInformation($"Finished method '{nameof(GetWithPaginationAsync)}'.");
                return(tariffs);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when retrieving ticket tariffs from database. See the inner exception for more details.", ex);
                throw internalException;
            }
        }
示例#9
0
        public void Equals__Check_equality_the_same_single_discount__Should_be_the_same()
        {
            var ticketTariff1 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };

            bool isEqual = ticketTariff1.Equals(ticketTariff1);

            isEqual.Should().BeTrue();
        }
示例#10
0
        public void Equals__One_ticket_tariff_is_reffered_to_second__Should_be_the_same()
        {
            var ticketTariff1 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };
            var ticketTariff2 = ticketTariff1;

            bool isEqual = ticketTariff1.Equals(ticketTariff2);

            isEqual.Should().BeTrue();
        }
示例#11
0
        public void Validate__Description_has_exactly_256_characters__Should_be_valid()
        {
            var validTicketTariff = new TicketTariff
            {
                Description = "1234567890123456789012345678901123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901" +
                              "123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901123456789012345678901234567890123456789"
            };

            validTicketTariff.Description.Length.Should().Be(256);
            _validator.ShouldNotHaveValidationErrorFor(x => x.Description, validTicketTariff);
        }
示例#12
0
        public void Equals__One_ticket_tariff_is_null__Should_not_be_the_same()
        {
            TicketTariff ticketTariff1 = null;
            var          ticketTariff2 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };

            bool isEqual = ticketTariff2.Equals(ticketTariff1);

            isEqual.Should().BeFalse();
        }
示例#13
0
        public void Equals__Check_equality_of_two_different_types__Should_not_be_the_same()
        {
            DateTime?date          = null;
            var      ticketTariff2 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };

            bool isEqual = ticketTariff2.Equals(date);

            isEqual.Should().BeFalse();
        }
        public async Task <IActionResult> AddVisitsTicketTariffAsync(string visitTariffId, [FromBody] TicketTariffDto ticketTariff)
        {
            _logger.LogInformation($"Starting method '{nameof(AddVisitsTicketTariffAsync)}'.");

            if (string.IsNullOrEmpty(visitTariffId))
            {
                return(OnInvalidParameterError($"Parameter '{nameof(visitTariffId)}' cannot be null or empty."));
            }

            TicketTariff ticketTariffToBeAdded = null;
            VisitTariff  visitTariff           = null;

            try
            {
                visitTariff = await _visitTariffDbService.GetAsync(visitTariffId);

                // Ignore Id if the client set it. Id of entity is set internally by the server.
                ticketTariff.Id = null;

                ticketTariffToBeAdded = MapToDomainModel(ticketTariff);

                var addedTicketTariff = await _ticketTariffDbService.RestrictedAddAsync(ticketTariffToBeAdded);

                // Add new ticket tariff to parent visit tariff.
                visitTariff.TicketTariffs.Add(addedTicketTariff);
                await _visitTariffDbService.RestrictedUpdateAsync(visitTariff);

                // Reverse map only for response to the client.
                var    addedTariffDto       = MapToDto(addedTicketTariff);
                var    response             = new ResponseWrapper(addedTariffDto);
                string addedTicketTariffUrl = $"{ControllerPrefix}/{addedTicketTariff.Id}";
                _logger.LogInformation($"Finished method '{nameof(AddVisitsTicketTariffAsync)}'.");

                return(Created(addedTicketTariffUrl, response));
            }
            catch (InvalidOperationException ex) when(visitTariff is null)
            {
                return(OnNotFoundError($"Cannot found '{typeof(VisitTariff).Name}' with specified id: '{visitTariffId}'.", ex));
            }
            catch (InvalidOperationException ex)
            {
                return(OnInvalidParameterError($"Element '{typeof(TicketTariff).Name}' already exists.", ex));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex, _ticketTariffDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
示例#15
0
        public void Validate__Description_has_more_than_256_characters__Should_be_invalid()
        {
            var invalidTicketTariff = new TicketTariff
            {
                Description = "1234567890123456789012345678901123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901" +
                              "1234567890123456789012345678901123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901" +
                              "1234567890123456789012345678901123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901"
            };

            invalidTicketTariff.Description.Length.Should().BeGreaterThan(256);
            _validator.ShouldHaveValidationErrorFor(x => x.Description, invalidTicketTariff);
        }
        //#region DeleteTicketTariffAsync(string id);
        //nie ma takiego elementu o podanym id -> 404 not found
        // argument jest pusty albo null -> 400 bad request
        // usunieto poprawnie -> 200 ok
        // any internal error refferd to the db occurred -> throws internal db service exc
        // any unexpected internal error occurred -> throws exc

        //[Test]
        //public async Task DeleteTicketTariffAsync__An_internal_error_reffered_to_the_database_occurred__Should_throw_InternalDbServiceException()
        //{
        //    Example of these errors: database does not exist, table does not exist etc.

        //    _ticketTariffDbServiceMock.Setup(x => x.DeleteAsync(It.IsAny<string>())).ThrowsAsync(new InternalDbServiceException());
        //    var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

        //    Func<Task> result = async () => await controller.DeleteVisitsTicketTariffAsync("1");

        //    await result.Should().ThrowExactlyAsync<InternalDbServiceException>();
        //}

        //[Test]
        //public async Task DeleteTicketTariffAsync__An_unexpected_internal_error_occurred__Should_throw_Exception()
        //{
        //    _ticketTariffDbServiceMock.Setup(x => x.DeleteAsync(It.IsAny<string>())).ThrowsAsync(new Exception());
        //    var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

        //    Func<Task> result = async () => await controller.DeleteTicketTariffAsync("1");

        //    await result.Should().ThrowExactlyAsync<Exception>();
        //}

        //[Test]
        //public async Task DeleteTicketTariffAsync__Element_not_found__Should_return_404NotFound_response_with_error()
        //{
        //    string id = "-1";
        //    _ticketTariffDbServiceMock.Setup(x => x.DeleteAsync(id)).ThrowsAsync(new InvalidOperationException());
        //    var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

        //    var result = await controller.DeleteTicketTariffAsync(id);

        //    (result as ObjectResult).StatusCode.Should().Be(404);
        //    ((result as ObjectResult).Value as ResponseWrapper).Error.Should().NotBeNull();
        //}

        //[Test]
        //public async Task DeleteTicketTariffAsync__Argument_id_is_null_or_empty__Should_return_400BadRequest_response([Values(null, "")] string id)
        //{
        //    _ticketTariffDbServiceMock.Setup(x => x.DeleteAsync(id)).ThrowsAsync(new ArgumentException());
        //    var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

        //    var result = await controller.DeleteTicketTariffAsync(id);

        //    (result as ObjectResult).StatusCode.Should().Be(400);
        //    ((result as ObjectResult).Value as ResponseWrapper).Error.Should().NotBeNull();
        //}

        //[Test]
        //public async Task DeleteTicketTariffAsync__Delete_succeeded__Should_return_200OK_response()
        //{
        //    _ticketTariffDbServiceMock.Setup(x => x.DeleteAsync(It.IsNotNull<string>()));
        //    var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

        //    var result = await controller.DeleteTicketTariffAsync("1");

        //    (result as ObjectResult).StatusCode.Should().Be(200);
        //    ((result as ObjectResult).Value as ResponseWrapper).Error.Should().BeEquivalentTo(new ApiError());
        //}

        //#endregion


        #region Privates

        private TicketTariffDto CreateTicketTariffDto(TicketTariff ticketTariff)
        {
            return(new TicketTariffDto
            {
                Id = ticketTariff.Id,
                Description = ticketTariff.Description,
                DefaultPrice = ticketTariff.DefaultPrice,
                IsPerHour = ticketTariff.IsPerHour,
                CreatedAt = ticketTariff.CreatedAt,
                IsPerPerson = ticketTariff.IsPerPerson,
                UpdatedAt = ticketTariff.UpdatedAt
            });
        }
示例#17
0
        public void Equals__Two_ticket_tariffs_with_the_same_properties_value__Should_be_the_same()
        {
            var ticketTariff1 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };
            var ticketTariff2 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };

            bool isEqual = ticketTariff1.Equals(ticketTariff2);

            isEqual.Should().BeTrue();
        }
示例#18
0
        public void Equals__At_least_one_property_value_is_different__Should_not_be_the_same()
        {
            var ticketTariff1 = new TicketTariff {
                Id = "1", Description = "description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };
            var ticketTariff2 = new TicketTariff {
                Id = "1", Description = "other description", DefaultPrice = 20, IsPerHour = true, IsPerPerson = true
            };

            bool isEqual = ticketTariff1.Equals(ticketTariff2);

            isEqual.Should().BeFalse();
        }
        public async Task UpdateVisitsTicketTariffAsync__Update_succeeded__Should_return_200OK_response_with_updated_element()
        {
            var validTicketTariff = new TicketTariff {
                Id = "4", Description = "Valid description updated"
            };
            var validTicketTariffDto = CreateTicketTariffDto(validTicketTariff);

            _mapperMock.Setup(x => x.Map <TicketTariff>(It.IsNotNull <TicketTariffDto>())).Returns(validTicketTariff);
            _mapperMock.Setup(x => x.Map <TicketTariffDto>(It.IsNotNull <TicketTariff>())).Returns(validTicketTariffDto);
            _ticketTariffDbServiceMock.Setup(x => x.RestrictedUpdateAsync(validTicketTariff)).ReturnsAsync(validTicketTariff);
            var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

            var result = await controller.UpdateVisitsTicketTariffAsync(_visitTariffId, "4", validTicketTariffDto);

            (result as ObjectResult).StatusCode.Should().Be(200);
            ((result as ObjectResult).Value as ResponseWrapper).Data.Should().BeEquivalentTo(validTicketTariffDto);
        }
        public async Task GetVisitsTicketTariffAsync__Data_retrieve_succeeded__Should_return_200Ok_response_with_data()
        {
            var ticketTariffs = new TicketTariff[] { new TicketTariff {
                                                         Id = "1", DefaultPrice = 30
                                                     } };
            var parentVisitTariff = new VisitTariff
            {
                Id            = _visitTariffId,
                UpdatedAt     = new DateTime(2019, 1, 1),
                Name          = "sample parent visit tariff name",
                TicketTariffs = ticketTariffs
            };

            _ticketTariffDbServiceMock.Setup(x => x.RestrictedAddAsync(It.IsNotNull <TicketTariff>())).ReturnsAsync(ticketTariffs[0]);
            _visitTariffDbServiceMock.Setup(x => x.GetAsync(It.IsNotNull <string>())).ReturnsAsync(parentVisitTariff);
            _mapperMock.Setup(x => x.Map <TicketTariffDto>(It.IsNotNull <TicketTariff>())).Returns(CreateTicketTariffDto(ticketTariffs[0]));
            var controller = new TicketTariffsController(_ticketTariffDbServiceMock.Object, _visitTariffDbServiceMock.Object, _logger, _mapperMock.Object);

            // Get first TicketTariff from _parentvisitTariff.
            var result = await controller.GetVisitsTicketTariffAsync(_visitTariffId, ticketTariffs[0].Id);

            (result as ObjectResult).StatusCode.Should().Be(200);
            ((result as ObjectResult).Value as ResponseWrapper).Data.Should().NotBeNull();
        }
示例#21
0
 /// <summary>
 /// Asynchronously adds <see cref="TicketTariff"/> entity to the database. Do not allow add entity with the same Description, IsPerHour, IsPerPerson and DefaultPrice.
 /// Throws an exception if already there is the same entity in database or any problem with saving changes occurred.
 /// </summary>
 /// <param name="tariff">The tariff to be added. Cannot be null.</param>
 /// <returns>The added entity.</returns>
 /// <exception cref="ArgumentNullException">The value of <paramref name="tariff"/> to be added is null.</exception>
 /// <exception cref="InvalidOperationException">There is the same entity that one to be added in database.</exception>
 /// <exception cref="InternalDbServiceException">The table with <see cref="TicketTariff"/> entities does not exist or it is null or
 /// cannot save properly any changes made by add operation.</exception>
 public async Task <TicketTariff> RestrictedAddAsync(TicketTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(RestrictedAddAsync)}'.");
     // Call restricted add mode.
     return(await AddBaseAsync(tariff, true));
 }
示例#22
0
 /// <summary>
 /// Asynchronously adds <see cref="TicketTariff"/> entity to the database. Throws an exception if
 /// already there is the same entity in database or any problem with saving changes occurred.
 /// </summary>
 /// <param name="tariff">The tariff to be added. Cannot be null.</param>
 /// <returns>The added entity.</returns>
 /// <exception cref="ArgumentNullException">The value of <paramref name="tariff"/> to be added is null.</exception>
 /// <exception cref="InvalidOperationException">There is the same entity that one to be added in the database.</exception>
 /// <exception cref="InternalDbServiceException">The table with <see cref="TicketTariff"/> entities does not exist or it is null or
 /// cannot save properly any changes made by add operation.</exception>
 public async Task <TicketTariff> AddAsync(TicketTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(AddAsync)}'.");
     // Call normal add mode.
     return(await AddBaseAsync(tariff));
 }
示例#23
0
        /// <summary>
        /// Asynchronously adds <see cref="TicketTariff"/> entity. If <paramref name="isRestrict"/> set to false then no restrictions will be used. If set to true then the restricted mode will be used.
        /// It will check if in database is entity with the same 'Description', 'IsPerHour', 'IsPerPerson' and 'DefaultPrice' value.
        /// </summary>
        /// <param name="tariff"><see cref="TicketTariff"/> to be added.</param>
        /// <param name="isRestrict">If set to false then no restrictions will be used and update allow entirely entity updating. If set to true then the restricted mode will be used.
        /// It will check if in database is entity with the same 'Description', 'IsPerHour', 'IsPerPerson' and 'DefaultPrice' value.</param>
        /// <returns>Added <see cref="TicketTariff"/> entity.</returns>
        private async Task <TicketTariff> AddBaseAsync(TicketTariff tariff, bool isRestrict = false)
        {
            _logger.LogDebug($"Starting method '{nameof(AddBaseAsync)}'.");

            if (tariff is null)
            {
                throw new ArgumentNullException($"Argument '{nameof(tariff)}' cannot be null.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.TicketTariffs ?? throw new InternalDbServiceException($"Table of type '{typeof(TicketTariff).Name}' is null.");

            try
            {
                if (isRestrict)
                {
                    // Resticted add mode that use custom equality comparer. The ticket tariffs are equal if they have the same Description, IsPerHour, IsPerPerson and DefaultPrice.

                    // Check if exist in db tariff with the same Description, IsPerHour, IsPerPerson and DefaultPrice as adding.
                    if (await IsEntityAlreadyExistsAsync(tariff))
                    {
                        throw new InvalidOperationException($"There is already the same element in the database as the one to be added. The value of '{nameof(tariff.Description)}', " +
                                                            $"'{nameof(tariff.IsPerHour)}', '{nameof(tariff.IsPerPerson)}' and '{nameof(tariff.DefaultPrice)}' are not unique.");
                    }
                }
                else
                {
                    // Normal add mode without any additional restrictions.
                    if (_context.TicketTariffs.Contains(tariff))
                    {
                        throw new InvalidOperationException($"There is already the same element in the database as the one to be added. Id of this element: '{tariff.Id}'.");
                    }
                }

                _logger.LogDebug($"Starting add tariff with id '{tariff.Id}'.");
                var addedTariff = _context.TicketTariffs.Add(tariff).Entity;
                await _context.TrySaveChangesAsync();

                _logger.LogDebug("Add data succeeded.");
                _logger.LogDebug($"Finished method '{nameof(AddBaseAsync)}'.");
                return(addedTariff);
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError($"{ex.GetType().Name} - Changes made by add operations cannot be saved properly. See the inner exception for more details. Operation failed.", ex);
                var internalException = new InternalDbServiceException("Changes made by add operations cannot be saved properly. See the inner exception for more details.", ex);
                throw internalException;
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError($"{ex.GetType().Name} - {ex.Message}", ex);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when adding ticket tarifff with id: '{tariff.Id}' to the database. See the inner excpetion for more details.", ex);
                throw internalException;
            }
        }
示例#24
0
        /// <summary>
        /// Asynchronously updates <see cref="TicketTariff"/> entity. If <paramref name="isRestrict"/> set to false then no restrictions will be used and update allow entirely entity updating.
        /// Otherwise the restricted mode will be using. It will ignore updating some read-only properties.
        /// </summary>
        /// <param name="tariff"><see cref="TicketTariff"/> To be updated</param>
        /// <param name="isRestrict">If set to false then no restrictions will be used and update allow entirely entity updating. If set to true then the restricted mode will be used.
        /// It will ignore some read-only properties changes.</param>
        /// <returns>Updated <see cref="TicketTariff"/> entity.</returns>
        private async Task <TicketTariff> UpdateBaseAsync(TicketTariff tariff, bool isRestrict = false)
        {
            _logger.LogDebug($"Starting method '{nameof(UpdateBaseAsync)}'.");

            _ = tariff ?? throw new ArgumentNullException(nameof(tariff), $"Argument '{nameof(tariff)}' cannot be null.");

            if (string.IsNullOrEmpty(tariff.Id))
            {
                throw new ArgumentException($"Argument '{nameof(tariff.Id)}' cannot be null or empty.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.TicketTariffs ?? throw new InternalDbServiceException($"Table of type '{typeof(TicketTariff).Name}' is null.");

            try
            {
                if (_context.TicketTariffs.Count() == 0)
                {
                    throw new InvalidOperationException($"Cannot found element with id '{tariff.Id}' for update. Resource {_context.Groups.GetType().Name} does not contain any element.");
                }

                if (await _context.TicketTariffs.ContainsAsync(tariff) == false)
                {
                    throw new InvalidOperationException($"Cannot found element with id '{tariff.Id}' for update. Any element does not match to the one to be updated.");
                }

                _logger.LogDebug($"Starting update ticket tariff with id '{tariff.Id}'.");

                TicketTariff updatedTariff = null;
                tariff.UpdatedAt = DateTime.UtcNow;

                if (isRestrict)
                {
                    // Resticted update mode that ignores all changes in read-only properties like Id, CreatedAt, UpdatedAt, ConcurrencyToken and navigation properties like TicketTariffs.
                    var originalTariff = await _context.TicketTariffs.SingleAsync(x => x.Id.Equals(tariff.Id));

                    updatedTariff = BasicRestrictedUpdate(originalTariff, tariff) as TicketTariff;
                }
                else
                {
                    // Normal update mode without any additional restrictions.
                    updatedTariff = _context.TicketTariffs.Update(tariff).Entity;
                }

                await _context.TrySaveChangesAsync();

                _logger.LogDebug($"Update data succeeded.");
                _logger.LogDebug($"Finished method '{nameof(UpdateBaseAsync)}'.");
                return(updatedTariff);
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - Cannot found element for update. See the exception for more details. Operation failed.");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when updating ticket tariff with id '{tariff.Id}'. See the inner exception for more details.", ex);
                throw internalException;
            }
        }
示例#25
0
 /// <summary>
 /// Asynchronously updates <see cref="TicketTariff"/> entity.
 /// Throws an exception if cannot found entity or any problem with updating occurred.
 /// </summary>
 /// <param name="tariff">The tariff to be updated. Cannot be null or has Id property set to null or empty string.</param>
 /// <returns>Updated entity.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="tariff"/> is null.</exception>
 /// <exception cref="ArgumentException"><paramref name="tariff"/> has Id property set to null or empty string.</exception>
 /// <exception cref="InvalidOperationException">Cannot found entity to be updated.</exception>
 /// <exception cref="InternalDbServiceException">The resource does not exist or has a null value or any
 /// other problems with retrieving data from database occurred.</exception>
 public async Task <TicketTariff> UpdateAsync(TicketTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(UpdateAsync)}'.");
     // Call normal update mode.
     return(await UpdateBaseAsync(tariff));
 }
 private TicketTariffDto MapToDto(TicketTariff tariff) => _mapper.Map <TicketTariffDto>(tariff);
示例#27
0
        public void SetUp()
        {
            _validatorMock = new Mock <IValidator <SightseeingGroup> >();
            _logger        = Mock.Of <ILogger <TicketOrderHandler> >();

            var info = new VisitInfo
            {
                Id                     = "1",
                Description            = "recent sightseeing info",
                MaxAllowedGroupSize    = 30,
                MaxChildAge            = 5,
                MaxTicketOrderInterval = 4,
                SightseeingDuration    = 2,
                OpeningHours           = new OpeningHours[] { }
            };

            _infoDbServiceMock = new Mock <IVisitInfoDbService>();
            _infoDbServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(new VisitInfo[] { info }.AsEnumerable());

            _ticketTariff = new TicketTariff {
                Id = "1", DefaultPrice = 20, Description = "ticket tariff"
            };
            _ticketTariffDbServiceMock = new Mock <ITicketTariffDbService>();

            _discount = new Discount {
                Id = "1", Description = "discount", DiscountValueInPercentage = 20, Type = Discount.DiscountType.ForChild
            };
            _discountDbServiceMock = new Mock <IDiscountDbService>();

            _ticket = new Ticket
            {
                Id             = "1",
                OrderStamp     = "stamp",
                PurchaseDate   = DateTime.Now.AddDays(-2),
                TicketUniqueId = "uniqu_id"
            };
            _ticketDbServiceMock = new Mock <ITicketDbService>();

            _customer = new Customer
            {
                Id            = "1",
                DateOfBirth   = DateTime.Now.AddYears(-30),
                EmailAddress  = "*****@*****.**",
                HasFamilyCard = false,
                IsChild       = false,
                IsDisabled    = true,
                Tickets       = new Ticket[] { _ticket }
            };
            _customerDbServiceMock = new Mock <ICustomerDbService>();

            _groupDbServiceMock   = new Mock <ISightseeingGroupDbService>();
            _dbServiceFactoryMock = new Mock <IIndex <string, IServiceBase> >();

            _shallowTicket = new ShallowTicket {
                DiscountId = "1", TicketTariffId = "1", SightseeingDate = DateTime.Now.AddDays(3).Date.AddHours(14)
            };

            _dbServiceFactoryMock.Setup(x => x["ICustomerDbService"]).Returns(_customerDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["IDiscountDbService"]).Returns(_discountDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["ITicketTariffDbService"]).Returns(_ticketTariffDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["IVisitInfoDbService"]).Returns(_infoDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["ISightseeingGroupDbService"]).Returns(_groupDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["ITicketDbService"]).Returns(_ticketDbServiceMock.Object);
        }