コード例 #1
0
        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__Name_is_null_or_empty__Should_be_invalid([Values(null, "")] string name)
        {
            var invalidTariff = new VisitTariff {
                Name = name
            };

            _validator.ShouldHaveValidationErrorFor(x => x.Name, invalidTariff);
        }
コード例 #3
0
        public void Validate__Name_lenght_is_greater_than_50__Should_be_invalid()
        {
            var invalidTariff = new VisitTariff {
                Name = "123456789012345678901234567890123456789012345678901"
            };

            invalidTariff.Name.Length.Should().BeGreaterThan(50);
            _validator.ShouldHaveValidationErrorFor(x => x.Name, invalidTariff);
        }
コード例 #4
0
        public void Validate__Name_lenght_is_less_than_50__Should_be_valid()
        {
            var validTariff = new VisitTariff {
                Name = "1234567890123456789012345678901234567890123456789"
            };

            validTariff.Name.Length.Should().BeLessThan(50);
            _validator.ShouldNotHaveValidationErrorFor(x => x.Name, validTariff);
        }
コード例 #5
0
        public void Equals__Check_equality_the_same_single_sightseeing_tariff__Should_be_the_same()
        {
            var sightseeingTariff1 = new VisitTariff {
                Id = "1", Name = "test"
            };

            bool isEqual = sightseeingTariff1.Equals(sightseeingTariff1);

            isEqual.Should().BeTrue();
        }
コード例 #6
0
 private VisitTariffDto CreateSightseeingTariffDto(VisitTariff tariff)
 {
     return(new VisitTariffDto
     {
         Id = tariff.Id,
         Name = tariff.Name,
         CreatedAt = tariff.CreatedAt,
         UpdatedAt = tariff.UpdatedAt,
         TicketTariffs = tariff.TicketTariffs as ICollection <TicketTariffDto>
     });
 }
コード例 #7
0
        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;
            }
        }
コード例 #8
0
        public void Equals__One_sightseeing_tariff_is_null__Should_not_be_the_same()
        {
            VisitTariff SightseeingTariff1 = null;
            var         sightseeingTariff2 = new VisitTariff {
                Id = "1", Name = "test"
            };

            bool isEqual = sightseeingTariff2.Equals(SightseeingTariff1);

            isEqual.Should().BeFalse();
        }
コード例 #9
0
        public void Equals__Check_equality_of_two_different_types__Should_not_be_the_same()
        {
            DateTime?date = null;
            var      sightseeingTariff1 = new VisitTariff {
                Id = "1", Name = "test"
            };

            bool isEqual = sightseeingTariff1.Equals(date);

            isEqual.Should().BeFalse();
        }
コード例 #10
0
        public void Equals__One_sightseeing_tariff_is_reffered_to_second__Should_be_the_same()
        {
            var sightseeingTariff1 = new VisitTariff {
                Id = "1", Name = "test"
            };
            var sightseeingTariff2 = sightseeingTariff1;

            bool isEqual = sightseeingTariff1.Equals(sightseeingTariff2);

            isEqual.Should().BeTrue();
        }
コード例 #11
0
        public async Task <IActionResult> UpdateVisitsTicketTariffAsync(string visitTariffId, string ticketTariffId, [FromBody] TicketTariffDto ticketTariff)
        {
            _logger.LogInformation($"Starting method '{nameof(UpdateVisitsTicketTariffAsync)}'.");

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

            if (!ticketTariffId.Equals(ticketTariff.Id))
            {
                return(OnMismatchParameterError($"An '{nameof(ticketTariffId)}' in URL end field '{nameof(ticketTariff.Id)}' in request body mismatches. Value in URL: '{ticketTariffId}'. " +
                                                $"Value in body: '{ticketTariff.Id}'."));
            }

            VisitTariff parentVisitTariff = null;

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

                var ticketTariffToBeUpdated = MapToDomainModel(ticketTariff);
                var updatedTicketTariff     = await _ticketTariffDbService.RestrictedUpdateAsync(ticketTariffToBeUpdated);

                // Update parent VisitTariff by adding
                parentVisitTariff.TicketTariffs.Add(updatedTicketTariff);
                await _visitTariffDbService.RestrictedUpdateAsync(parentVisitTariff);

                // Revers map for client response.
                var updatedTicketTariffDto = MapToDto(updatedTicketTariff);
                var response = new ResponseWrapper(updatedTicketTariffDto);
                _logger.LogInformation($"Finished method '{nameof(UpdateVisitsTicketTariffAsync)}'");
                return(Ok(response));
            }
            catch (InvalidOperationException ex) when(parentVisitTariff is null)
            {
                return(OnNotFoundError($"Cannot found '{typeof(VisitTariff).Name}' with specified id: '{visitTariffId}'.", ex));
            }
            catch (InvalidOperationException ex)
            {
                return(OnNotFoundError($"Cannot found '{typeof(TicketTariff).Name}' with specified id: '{ticketTariffId}'.", ex));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex, _ticketTariffDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
コード例 #12
0
        public void Equals__At_least_one_property_value_is_different__Should_not_be_the_same()
        {
            var sightseeingTariff1 = new VisitTariff {
                Id = "1", Name = "test"
            };
            var sightseeingTariff2 = new VisitTariff {
                Id = "1", Name = "other test"
            };

            bool isEqual = sightseeingTariff1.Equals(sightseeingTariff2);

            isEqual.Should().BeFalse();
        }
コード例 #13
0
        public void Equals__Two_sightseeing_tariff_with_the_same_properties_value__Should_be_the_same()
        {
            var sightseeingTariff1 = new VisitTariff {
                Id = "1", Name = "test"
            };
            var sightseeingTariff2 = new VisitTariff {
                Id = "1", Name = "test"
            };

            bool isEqual = sightseeingTariff1.Equals(sightseeingTariff2);

            isEqual.Should().BeTrue();
        }
コード例 #14
0
        public void SetUp()
        {
            _ticketTariffDbServiceMock = new Mock <ITicketTariffDbService>();
            _visitTariffDbServiceMock  = new Mock <IVisitTariffDbService>();
            _mapperMock = new Mock <IMapper>();
            _logger     = Mock.Of <ILogger <TicketTariffsController> >();

            _ticketTariffs = new TicketTariff[]
            {
                new TicketTariff
                {
                    Id           = "1",
                    Description  = "This is",
                    DefaultPrice = 40,
                    UpdatedAt    = DateTime.UtcNow.AddDays(-1)
                },
                new TicketTariff
                {
                    Id           = "2",
                    Description  = "This is",
                    DefaultPrice = 35,
                    UpdatedAt    = DateTime.UtcNow.AddDays(-1)
                }
            };

            _parentVisitTariff = new VisitTariff
            {
                Id            = _visitTariffId,
                UpdatedAt     = new DateTime(2019, 1, 1),
                Name          = "sample parent visit tariff name",
                TicketTariffs = new List <TicketTariff>(_ticketTariffs) as ICollection <TicketTariff>
            };

            _ticketTariffDtos = new TicketTariffDto[]
            {
                new TicketTariffDto
                {
                    Id           = "4",
                    Description  = "This is DTO",
                    DefaultPrice = 23,
                    UpdatedAt    = DateTime.UtcNow.AddDays(-1)
                },
                new TicketTariffDto
                {
                    Id           = "5",
                    Description  = "This id DTO",
                    DefaultPrice = 50,
                    UpdatedAt    = DateTime.UtcNow.AddDays(-1)
                }
            };
        }
コード例 #15
0
        public async Task AddTariffAsync__Add_succeeded__Should_return_200OK_response_with_added_element()
        {
            var validTariff = new VisitTariff {
                Id = "12312321321321", Name = "Valid name"
            };
            var validTariffDto = CreateSightseeingTariffDto(validTariff);

            _mapperMock.Setup(x => x.Map <VisitTariff>(It.IsNotNull <VisitTariffDto>())).Returns(validTariff);
            _mapperMock.Setup(x => x.Map <VisitTariffDto>(It.IsNotNull <VisitTariff>())).Returns(validTariffDto);
            _tariffDbServiceMock.Setup(x => x.AddAsync(validTariff)).ReturnsAsync(validTariff);
            _tariffDbServiceMock.Setup(x => x.RestrictedAddAsync(validTariff)).ReturnsAsync(validTariff);
            var controller = new VisitTariffsController(_tariffDbServiceMock.Object, _logger, _mapperMock.Object);

            var result = await controller.AddTariffAsync(validTariffDto);

            (result as ObjectResult).StatusCode.Should().Be(201);
            ((result as ObjectResult).Value as ResponseWrapper).Data.Should().NotBeNull();
        }
コード例 #16
0
        public async Task UpdateTariffAsync__Element_not_found__Should_return_404NotFound_response_with_error()
        {
            var validTariff = new VisitTariff {
                Id = "12312321321321", Name = "Valid name"
            };
            var validTariffDto = CreateSightseeingTariffDto(validTariff);

            _mapperMock.Setup(x => x.Map <VisitTariff>(It.IsNotNull <VisitTariffDto>())).Returns(validTariff);
            _mapperMock.Setup(x => x.Map <VisitTariffDto>(It.IsNotNull <VisitTariff>())).Returns(validTariffDto);
            _tariffDbServiceMock.Setup(x => x.UpdateAsync(It.IsNotNull <VisitTariff>())).ThrowsAsync(new InvalidOperationException());
            _tariffDbServiceMock.Setup(x => x.RestrictedUpdateAsync(It.IsNotNull <VisitTariff>())).ThrowsAsync(new InvalidOperationException());
            var controller = new VisitTariffsController(_tariffDbServiceMock.Object, _logger, _mapperMock.Object);

            var result = await controller.UpdateTariffAsync(validTariffDto.Id, validTariffDto);

            (result as ObjectResult).StatusCode.Should().Be(404);
            ((result as ObjectResult).Value as ResponseWrapper).Error.Should().NotBeNull();
        }
コード例 #17
0
        public void SetUp()
        {
            _tariffDbServiceMock = new Mock <IVisitTariffDbService>();
            _mapperMock          = new Mock <IMapper>();
            _logger      = Mock.Of <ILogger <VisitTariffsController> >();
            _validTariff = new VisitTariff
            {
                Id            = "15891fb0-faec-43c6-9e83-04a4a17c3660",
                Name          = "Sample sightseeing tariff name for test",
                TicketTariffs = new TicketTariff[]
                {
                    new TicketTariff
                    {
                        Id           = "84b9aa90-faec-43c6-9e83-15891fb0205a",
                        Description  = "Sample ticket tariff for test",
                        DefaultPrice = 23,
                        UpdatedAt    = DateTime.Now
                    }
                }
            };

            _tariffs = new VisitTariff[]
            {
                new VisitTariff {
                    Id = "1", UpdatedAt = DateTime.MinValue, Name = "Not updated since created"
                },
                new VisitTariff {
                    Id = "2", UpdatedAt = DateTime.Now.AddMinutes(30), Name = "Updated in future. It's the latest tariff and should be retrieved"
                }
            };

            _tariffDtos = new VisitTariffDto[]
            {
                new VisitTariffDto {
                    Id = "1", UpdatedAt = null, Name = "Not updated since created"
                },
                new VisitTariffDto {
                    Id = "2", UpdatedAt = DateTime.Now.AddMinutes(30), Name = "Updated in future. It's the latest tariff and should be retrieved"
                }
            };
        }
コード例 #18
0
        public async Task <IActionResult> GetVisitsTicketTariffAsync(string visitTariffId, string ticketTariffId)
        {
            if (string.IsNullOrEmpty(visitTariffId) || string.IsNullOrEmpty(ticketTariffId))
            {
                return(OnInvalidParameterError($"Parameters '{nameof(visitTariffId)}' and '{nameof(ticketTariffId)}' cannot be null or empty."));
            }

            VisitTariff visitTariff = null;

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

                var ticketTariff    = visitTariff.TicketTariffs.Single(x => x.Id.Equals(ticketTariffId));
                var ticketTariffDto = MapToDto(ticketTariff);
                var response        = new ResponseWrapper(ticketTariffDto);
                return(Ok(response));
            }
            catch (InvalidOperationException ex) when(visitTariff is null)
            {
                return(OnNotFoundError($"Cannot found '{typeof(VisitTariff).Name}' with specified id: '{visitTariffId}'.", ex));
            }
            catch (InvalidOperationException ex)
            {
                return(OnNotFoundError($"Cannot found '{typeof(TicketTariff).Name}' with specified id: '{ticketTariffId}'.", ex));
            }
            catch (InternalDbServiceException ex)
            {
                LogInternalDbServiceException(ex);
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
コード例 #19
0
        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();
        }
コード例 #20
0
 /// <summary>
 /// Asynchronously adds <see cref="VisitTariff"/> entity to the database. Do not allow add entity with the same Description property. 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="VisitTariff"/> entities does not exist or it is null or
 /// cannot save properly any changes made by add operation.</exception>
 public async Task <VisitTariff> RestrictedAddAsync(VisitTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(RestrictedAddAsync)}'.");
     // Call restricted add mode.
     return(await AddBaseAsync(tariff, true));
 }
コード例 #21
0
        /// <summary>
        /// Asynchronously adds <see cref="VisitTariff"/> 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 'Name' value. Moreover it will does not allow to add navigation property while adding <see cref="VisitTariff"/>.
        /// </summary>
        /// <param name="tariff"><see cref="VisitTariff"/> 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 'Name' value. Moreover it will does not allow to add navigation property while adding <see cref="VisitTariff"/>.</param>
        /// <returns>Added <see cref="VisitTariff"/> entity.</returns>
        private async Task <VisitTariff> AddBaseAsync(VisitTariff 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?.VisitTariffs ?? throw new InternalDbServiceException($"Table of type '{typeof(VisitTariff).Name}' is null.");

            try
            {
                if (isRestrict)
                {
                    // Resticted add mode that use custom equality comparer. The sightseeing tariffs are equal if they have the same Name.
                    // Moreover this mode does not allow adding navigation property togather with parent entity (SightseeinTariff -> TicketTariffs).
                    tariff.TicketTariffs = null;

                    // Check if exist in db tariff with the same 'Name' 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.Name)}' is not unique.");
                    }
                }
                else
                {
                    // Normal add mode without any additional restrictions.
                    if (_context.VisitTariffs.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.VisitTariffs.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 sighseeing tarifff to the database. See the inner excpetion for more details.", ex);
                throw internalException;
            }
        }
コード例 #22
0
 /// <summary>
 /// Asynchronously adds <see cref="VisitTariff"/> 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 the one to be added in database.</exception>
 /// <exception cref="InternalDbServiceException">The table with <see cref="VisitTariff"/> entities does not exist or it is null or
 /// cannot save properly any changes made by add operation.</exception>
 public async Task <VisitTariff> AddAsync(VisitTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(AddAsync)}'.");
     // Call normal add mode.
     return(await AddBaseAsync(tariff));
 }
コード例 #23
0
        /// <summary>
        /// Asynchronously updates <see cref="VisitTariff"/> 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">VisitTariff 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="VisitTariff"/> entity.</returns>
        private async Task <VisitTariff> UpdateBaseAsync(VisitTariff 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?.VisitTariffs ?? throw new InternalDbServiceException($"Table of type '{typeof(VisitTariff).Name}' is null.");

            try
            {
                if (_context.VisitTariffs.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.VisitTariffs.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 tariff with id '{tariff.Id}'.");

                VisitTariff 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.VisitTariffs.SingleAsync(x => x.Id.Equals(tariff.Id));

                    // Set the TicketTariffs navigation property to the original value, because restricted update mode does not allow updating of TicketTariffs.
                    // For any changes from the client in TicketTariff objects, use the TicketTairiffsController methods.
                    tariff.TicketTariffs = originalTariff.TicketTariffs;

                    updatedTariff = BasicRestrictedUpdate(originalTariff, tariff) as VisitTariff;
                }
                else
                {
                    // Normal update mode without any additional restrictions.
                    updatedTariff = _context.VisitTariffs.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 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 sighseeing tariff with id '{tariff.Id}'. See inner excpetion for more details.", ex);
                throw internalException;
            }
        }
コード例 #24
0
 /// <summary>
 /// Asynchronously updates <see cref="VisitTariff"/> 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 <VisitTariff> UpdateAsync(VisitTariff tariff)
 {
     _logger.LogInformation($"Starting method '{nameof(UpdateAsync)}'.");
     // Call normal update mode.
     return(await UpdateBaseAsync(tariff));
 }
コード例 #25
0
 private VisitTariffDto MapToDto(VisitTariff tariff) => _mapper.Map <VisitTariffDto>(tariff);