Represents and error when a required object is not found
Inheritance: Exception
        async Task <IStorageAccount> GetResourceAsync(string resourceGroupName, string resourceName, bool failIfNotFound = true, CancellationToken cancellationToken = default)
        {
            var resource = await _azure.StorageAccounts.GetByResourceGroupAsync(resourceGroupName, resourceName, cancellationToken);

            if (resource == null)
            {
                if (failIfNotFound)
                {
                    throw NotFoundException.CreateForAzureResource(resourceName, resourceGroupName);
                }
                else
                {
                    return(null);
                }
            }

            return(resource);
        }
Exemple #2
0
        public void CancelReservation(int reservationId)
        {
            ExecuteFaultHandledOperation(() =>
            {
                IReservationRepository reservationRepository = _DataRepositoryFactory.GetDataRepository <IReservationRepository>();

                Reservation reservation = reservationRepository.Get(reservationId);
                if (reservation == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("No reservation found found for ID '{0}'.", reservationId));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                ValidateAuthorization(reservation);

                reservationRepository.Remove(reservationId);
            });
        }
Exemple #3
0
    public async Task <BookDto> GetByIdAsync(long id)
    {
        var sql_ = Db.NewSql();

        sql_.Line("SELECT * FROM Book WHERE Id=@id");
        var book = await Db.FirstOrDefaultAsync <BookDto>(sql_, new { id });

        NotFoundException.ThrowIf(book == null);

        sql_.Clear();
        sql_.Line("SELECT T.*")
        .Line("FROM BookTag BT")
        .Line("LEFT JOIN Tag T ON T.Id=BT.TagId")
        .Line("WHERE BT.BookId=@id");
        book.Tags = (await Db.QueryAsync <Tag>(sql_, new { id })).ToList();

        return(book);
    }
        public async void DeletePaymentById()
        {
            IClient commerceToolsClient = this.paymentsFixture.GetService <IClient>();
            Payment payment             = this.paymentsFixture.CreatePayment();
            var     deleteCommand       = new DeleteByIdCommand <Payment>(payment.Id, payment.Version)
            {
                DataErasure = true
            };
            Payment deletedPayment = commerceToolsClient
                                     .ExecuteAsync(
                deleteCommand)
                                     .Result;
            NotFoundException exception = await Assert.ThrowsAsync <NotFoundException>(() =>
                                                                                       commerceToolsClient.ExecuteAsync(
                                                                                           new GetByIdCommand <Cart>(deletedPayment.Id)));

            Assert.Equal(404, exception.StatusCode);
        }
Exemple #5
0
        public async Task Write_404_Response_If_NotFound_Is_Thrown()
        {
            var exception = new NotFoundException("Category", 1);

            Task next(HttpContext context)
            {
                throw exception;
            }

            var middleware = new ExceptionHandlingMiddleware(next);
            var context    = HttpContextFactory.Create();

            await middleware.Invoke(context);

            Assert.AreEqual("application/json", context.Response.ContentType);
            Assert.AreEqual(404, context.Response.StatusCode);
            Assert.AreEqual(exception.Message, await context.Response.ReadAsAsync <string>());
        }
Exemple #6
0
        public async Task <TagOutput> UpdateTagAsync(Guid tagId, TagInput input)
        {
            var tag = await _tagRepository.FindByIdAsync(tagId);

            if (null == tag)
            {
                throw NotFoundException <Tag> .WithId(tagId);
            }

            if (await IsTagNameBusyAsync(input.Name))
            {
                throw TagException.NameIsBusy(input.Name);
            }

            tag.Name = input.Name;

            return(new TagOutput(tag));
        }
        protected async Task <IVirtualMachine> GetInternalAsync(string resourceGroupName, string resourceName, bool failIfNotFound = true)
        {
            var resource = await _azure.VirtualMachines.GetByResourceGroupAsync(resourceGroupName, resourceName);

            if (resource == null)
            {
                if (failIfNotFound)
                {
                    throw NotFoundException.CreateForAzureResource(resourceName, resourceGroupName);
                }
                else
                {
                    return(null);
                }
            }

            return(resource);
        }
        public void Given_a_NotFoundException_exception_is_thrown_within_deeper_flow__When_GetAractionsByPropRef_ArrearsActionController_method_is_called__Then_controller_returns_404_status_code_response()
        {
            //Arrange
            TestHelper.SetUp_MockValidatorSuccessResponse(_mockGetByPropRefValidator);

            var not_found_exception = new NotFoundException();

            _mockUsecase.Setup(u => u.GetByPropRef(It.IsAny <GetAractionsByPropRefRequest>())).Throws(not_found_exception); // doesn't matter where so long it's not within the controller

            //Act
            var response        = _controllerUnderTest.GetAractionsByPropRef(null);
            var response_result = (ObjectResult)response;

            //Assert
            Assert.NotNull(response);
            Assert.NotNull(response_result);
            Assert.AreEqual(404, response_result.StatusCode);
        }
Exemple #9
0
        // TODO this is because running under iis express
        //[PrincipalPermission(SecurityAction.Demand, Role = Security.Car_Rental_Admin_Role)]
        //[PrincipalPermission(SecurityAction.Demand, Name = Security.Car_Rental_User)]
        public Account GetCustomerAccountInfo(string loginEmail)
        {
            return(base.ExecuteFaultHandledOperation(() =>
            {
                var accountRepository = this._dataRepositoryFactory.GetDataRepository <IAccountRepository>();

                var accountEntity = accountRepository.GetByLogin(loginEmail);
                if (accountEntity == null)
                {
                    var ex = new NotFoundException($"Account with login {loginEmail} is not in database");
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                base.ValidateAuthorization(accountEntity);

                return accountEntity;
            }));
        }
Exemple #10
0
        public void UpdateCartItem(int cartItemId, int quantity)
        {
            ExecuteFaultHandledOperation(() => {
                ICartRepository cartRepository =
                    _dataRepositoryFactory.GetDataRepository <ICartRepository>();
                CartItem cartItem = cartRepository.Get(cartItemId);
                if (cartItem == null)
                {
                    NotFoundException ex =
                        new NotFoundException(string.Format($"No cart item found for ID '{cartItemId}'."));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }
                ValidationAuthorization(((IAccountOwnedEntity)cartItem).OwnerAccountId); //GetOwnerAccountId(cartItem)

                cartItem.Quantity = quantity;
                var updatedEntity = cartRepository.Update(cartItem);
            });
        }
        public async Task <INetworkSecurityGroup> GetResourceInternalAsync(string resourceGroupName, string resourceName, bool failIfNotFound = true)
        {
            var resource = await _azure.NetworkSecurityGroups.GetByResourceGroupAsync(resourceGroupName, resourceName);

            if (resource == null)
            {
                if (failIfNotFound)
                {
                    throw NotFoundException.CreateForAzureResource(resourceName, resourceGroupName);
                }
                else
                {
                    return(null);
                }
            }

            return(resource);
        }
Exemple #12
0
        public Account GetCustomerAccountInfo(string loginEmail)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAccountRepository accountRepository = _DataRepositoryFactory.GetDataRepository <IAccountRepository>();

                Account accountEntity = accountRepository.GetByLogin(loginEmail);
                if (accountEntity == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("Account with login {0} is not in database", loginEmail));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                ValidateAuthorization(accountEntity);

                return accountEntity;
            }));
        }
Exemple #13
0
        private void MessagesAreAddedToMessagesCollection()
        {
            var message1 = "message1";
            var message2 = "messages2";
            var messages = new string[] { message1, message2 };

            var error = new NotFoundException();

            error.AddMessages(messages);

            var message = error.Messages.First();

            Assert.Equal(1, error.Messages.Count);

            Assert.Contains(message1, message.Value);
            Assert.Contains(message2, message.Value);
            Assert.Equal(message.Key, Defaults.ErrorMessage.Key);
        }
        public Task GetErrorResponseAsync()
        {
            var context   = HttpContext.Features.Get <IExceptionHandlerFeature>();
            var exception = context.Error;

            _logger.LogError($"internal error: \r\n{exception}");

            Response.StatusCode = exception switch
            {
                NotSupportedException _ => StatusCodes.Status501NotImplemented,
                ConflictException _ => StatusCodes.Status400BadRequest,
                NotFoundException _ => StatusCodes.Status404NotFound,
                                      _ => Response.StatusCode
            };

            return(Task.CompletedTask);
        }
    }
Exemple #15
0
        public async Task <int> GetBikeCountInStation(string stationName)
        {
            try
            {
                foreach (char letter in stationName)
                {
                    if (char.IsDigit(letter))
                    {
                        System.ArgumentException argumentException = new System.ArgumentException("Station name can not contain numbers");
                        throw argumentException;
                    }
                }
                string responseBody = await client.GetStringAsync("http://api.digitransit.fi/routing/v1/routers/hsl/bike_rental");

                BikeRentalStationList bike = JsonConvert.DeserializeObject <BikeRentalStationList>(responseBody);
                for (int i = 0; i < bike.stations.Length; i++)
                {
                    if (bike.stations[i].name == stationName)
                    {
                        bikeCount = bike.stations[i].bikesAvailable;
                        Console.WriteLine(bikeCount + "\n" + stationName);
                        return(bikeCount);
                    }
                }
                NotFoundException exception = new NotFoundException("Station not found");
                throw exception;
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :", ex.Message);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :", ex.Message);
            }
            catch (NotFoundException ex)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :", ex.Message);
            }
            return(1);
        }
        public Album GetAlbum(int albumId)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAlbumRepository albumRepository = _genericRepositoryFactory.GetGenericRepository <IAlbumRepository>();

                Album albumEntity = albumRepository.Get(albumId).Result;

                if (albumEntity == null)
                {
                    NotFoundException ex
                        = new NotFoundException(string.Format("Album with Id of {0} is not in the database.", albumId));

                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                return albumEntity;
            }));
        }
        private async Task HandlesBaseExceptionWithStatusCode4xx()
        {
            var mappings = new HttpStatusCodeMappings();
            var handler  = new ExceptionHandler(mappings, _logger);

            var exception       = new NotFoundException();
            var mockHttpContext = CreateMockHttpContext(exception);

            await handler.HandleAsync(mockHttpContext);

            Assert.Equal(404, _mockHttpResponse.Object.StatusCode);
            Assert.Equal("application/json", _mockHttpResponse.Object.ContentType);

            var serializedError = JsonConvert.SerializeObject(exception.Error);

            Assert.Equal(serializedError, GetResponseBodyAsString(_mockHttpResponse.Object));
            Assert.StartsWith("Debug", _logger.LoggedMessages[0]);
            Assert.Contains(serializedError, _logger.LoggedMessages[0]);
        }
        public void ExecuteRentalFromReservation(int reservationId)
        {
            ExecuteFaultHandledOperation(() =>
            {
                IAccountRepository accountRepository         = _dataRepositoryFactory.GetDataRepository <IAccountRepository>();
                IReservationRepository reservationRepository = _dataRepositoryFactory.GetDataRepository <IReservationRepository>();
                ICarRentalEngine carRentalEngine             = _businessEngineFactory.GetBusinessEngine <ICarRentalEngine>();

                Reservation reservation = reservationRepository.Get(reservationId);
                if (reservation == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("Reservation {0} is not found.", reservationId));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                Account account = accountRepository.Get(reservation.AccountId);
                if (account == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("No account found for account ID '{0}'.", reservation.AccountId));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                try
                {
                    //Call to business engine
                    Rental rental = carRentalEngine.RentCarToCustomer(account.LoginEmail, reservation.CarId, reservation.RentalDate, reservation.ReturnDate);
                }
                catch (UnableToRentForDateException ex)
                {
                    throw new FaultException <UnableToRentForDateException>(ex, ex.Message);
                }
                catch (CarCurrentlyRentedException ex)
                {
                    throw new FaultException <CarCurrentlyRentedException>(ex, ex.Message);
                }
                catch (NotFoundException ex)
                {
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                reservationRepository.Remove(reservation);
            });
        }
Exemple #19
0
        public async void DeleteCategoryByIdAndExpandParent()
        {
            IClient  commerceToolsClient = this.categoryFixture.GetService <IClient>();
            Category category            = this.categoryFixture.CreateCategory(this.categoryFixture.GetCategoryDraftWithParent());

            //expansions
            List <Expansion <Category> >  expansions = new List <Expansion <Category> >();
            ReferenceExpansion <Category> expand     = new ReferenceExpansion <Category>(c => c.Parent);

            expansions.Add(expand);

            Category          retrievedCategory = commerceToolsClient.ExecuteAsync(new DeleteByIdCommand <Category>(new Guid(category.Id), category.Version, expansions)).Result;
            NotFoundException exception         = await Assert.ThrowsAsync <NotFoundException>(() =>
                                                                                               commerceToolsClient.ExecuteAsync(
                                                                                                   new GetByIdCommand <Category>(new Guid(retrievedCategory.Id))));

            Assert.NotNull(retrievedCategory.Parent.Obj);
            Assert.Equal(404, exception.StatusCode);
        }
Exemple #20
0
        public Car GetCar(int carId)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                ICarRepository carRepository = _DataRepositoryFactory.GetDataRepository <ICarRepository>();

                Car carEntity = carRepository.Get(carId);

                if (carEntity == null)
                {
                    NotFoundException ex =
                        new NotFoundException(string.Format("Car with ID of {0} is not in the database", carId));

                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                return carEntity;
            }));
        }
        public async Task Invoke_500Exception_Handle_TestAsync()
        {
            var exception = new NotFoundException("test");

            Task next(HttpContext context) => throw exception;

            var context  = Substitute.For <HttpContext>();
            var response = Substitute.For <HttpResponse>();
            var body     = Substitute.For <Stream>();

            response.Body.Returns(body);
            context.Response.Returns(response);

            fExceptionHandlingFacade
            .When(x => x.Handle(Arg.Is(exception), out Arg.Any <string>(), out Arg.Any <int>()))
            .Do(x => x[2] = 500);

            await Assert.ThrowsAsync <NotFoundException>(async() => await new ExceptionHandlingMiddleware(next, fExceptionHandlingFacade).InvokeAsync(context));
        }
        public Company GetCompanyByID(int company_key)
        {
            Log.Info("Accessing CompanyBusinessEngine GetCompanyByID function");
            return(ExecuteFaultHandledOperation(() =>
            {
                var company_data = _company_repo.GetByID(company_key);
                Log.Info("CompanyBusinessEngine GetByID function completed");

                if (company_data.CompanyKey != 0)
                {
                    return _comp_es.Map(company_data);
                }
                else
                {
                    NotFoundException ex = new NotFoundException($"Company with key {company_key} is not in database");
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }
            }));
        }
        private static JsonResponseModel CreateJsonNotFoundModel()
        {
            // Need to populate errors.

            var exception    = new NotFoundException("page");
            var errorHandler = (IErrorHandler) new StandardErrorHandler();
            var message      = errorHandler.FormatErrorMessage(exception);
            var errorCode    = errorHandler.GetErrorCode(exception);

            return(new JsonResponseModel
            {
                Success = false,
                Errors = new List <JsonError> {
                    new JsonError {
                        Code = errorCode, Message = message
                    }
                }
            });
        }
Exemple #24
0
        public async Task <int> Handle(CreateEventCommand request, CancellationToken cancellationToken)
        {
            Topic topic = await _topicRepository.GetAsync(request.TopicId.Value);

            NotFoundException.ThrowIfNull(topic, nameof(topic));

            Event @event = topic.AddEvent(
                request.Title,
                request.Content,
                request.StartDate.Value,
                request.EndDate,
                request.X.Value,
                request.Y.Value,
                request.EventTypeId.Value);

            await _topicRepository.UnitOfWork.SaveEntitiesAsync();

            return(@event.Id);
        }
Exemple #25
0
        public void al_solicitar_una_persona_mediante_su_id_que_no_se_encuentre_en_el_sistema_debe_devolver_una_excepción_de_tipo_NotFoundException_en_donde_el_data_contenga_la_key_errorCode_con_valor_ERR_PERSONA_NOTFOUND()
        {
            // Arrange.
            NotFoundException nfex = new NotFoundException();

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

            personaRepositoryMock.Setup(mgr => mgr.GetById(It.IsInRange(1, int.MaxValue, Range.Inclusive))).Throws(nfex);

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

            // Act.
            Action action = () => personaManager.GetById(1);

            // Assert.
            action.Should().ThrowExactly <NotFoundException>()
            .And.Data.Should().Contain(new DictionaryEntry("ErrorCode", ExErrorCode.ErrPersonaNotFound));
        }
Exemple #26
0
        public async Task <AvailableDatasets> Add(int sandboxId, int datasetId)
        {
            var sandbox = await GetSandboxForDatasetOperationsAsync(sandboxId, UserOperation.Study_Crud_Sandbox, false, true);

            ValidateAddOrRemoveDataset(sandbox);

            var datasetFromDb = await _db.Datasets.FirstOrDefaultAsync(ds => ds.Id == datasetId);

            if (datasetFromDb == null)
            {
                throw NotFoundException.CreateForEntity("Dataset", datasetId);
            }

            if (datasetFromDb.StudySpecific)
            {
                var studyForDataset = DatasetUtils.GetStudyFromStudySpecificDatasetOrThrow(datasetFromDb);


                if (datasetFromDb.StudySpecific && studyForDataset.Id != sandbox.Study.Id)
                {
                    throw new ArgumentException($"Dataset {datasetId} cannot be added to Sandbox {sandboxId}. The dataset is Study specific and belongs to another Study than {sandbox.Study.Id}.");
                }
            }


            var sandboxDatasetRelation = await _db.SandboxDatasets.FirstOrDefaultAsync(ds => ds.SandboxId == sandboxId && ds.DatasetId == datasetId);

            //Is dataset allready linked to this sandbox?
            if (sandboxDatasetRelation != null)
            {
                throw new ArgumentException($"Dataset is allready added to Sandbox.");
            }

            // Create new entry in the relation table
            var sandboxDataset = new SandboxDataset {
                SandboxId = sandboxId, DatasetId = datasetId, Added = DateTime.UtcNow, AddedBy = (await _userService.GetCurrentUserAsync()).UserName
            };
            await _db.SandboxDatasets.AddAsync(sandboxDataset);

            await _db.SaveChangesAsync();

            return(MapToAvailable(sandbox));
        }
        public void ExecuteRentalFromReservation(int reservationId)
        {
            base.ExecuteFaultHandledOperation(() =>
            {
                var accountRepository     = this._dataRepositoryFactory.GetDataRepository <IAccountRepository>();
                var reservationRepository = this._dataRepositoryFactory.GetDataRepository <IReservationRepository>();
                var carRentalEngine       = this._businessEngineFactory.GetBusinessEngine <ICarRentalEngine>();

                var reservation = reservationRepository.Get(reservationId);
                if (reservation == null)
                {
                    var ex = new NotFoundException($"Reservation {reservationId} is not found.");
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                var account = accountRepository.Get(reservation.AccountId);
                if (account == null)
                {
                    var ex = new NotFoundException($"No account found for account ID '{reservation.AccountId}'.");
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                try
                {
                    var rental = carRentalEngine.RentCarToCustomer(
                        account.LoginEmail, reservation.CarId, reservation.RentalDate, reservation.ReturnDate);
                }
                catch (UnableToRentForDateException ex)
                {
                    throw new FaultException <UnableToRentForDateException>(ex, ex.Message);
                }
                catch (CarCurrentlyRentedException ex)
                {
                    throw new FaultException <CarCurrentlyRentedException>(ex, ex.Message);
                }
                catch (NotFoundException ex)
                {
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                reservationRepository.Remove(reservation);
            });
        }
Exemple #28
0
        public Rental GetRental(int rentalId)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAccountRepository accountRepository = _DataRepositoryFactory.GetDataRepository <IAccountRepository>();
                IRentalRepository rentalRepository = _DataRepositoryFactory.GetDataRepository <IRentalRepository>();

                Rental rental = rentalRepository.Get(rentalId);
                if (rental == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("No rental record found for id '{0}'.", rentalId));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                ValidateAuthorization(rental);

                return rental;
            }));
        }
Exemple #29
0
        public Invoice GetInvoiceByCode(string invoice_code, string company_code)
        {
            Log.Info("Accessing InvoiceBusinessEngine GetInvoiceByCode function");
            return(ExecuteFaultHandledOperation(() =>
            {
                var invoice_data = _invoice_repo.GetByCode(invoice_code, company_code);
                Log.Info("InvoiceBusinessEngine GetInvoiceByCode function completed");

                if (invoice_data.InvoiceKey != 0)
                {
                    return Map(invoice_data);
                }
                else
                {
                    NotFoundException ex = new NotFoundException(string.Format("Invoice with code {0} is not in database", invoice_code));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }
            }));
        }
        public IEnumerable <Rental> GetRentalHistory(string loginEmail)
        {
            return(ExecuteFaultHandledOperation(() => {
                IAccountRepository accountRepository = _dataRepositoryFactory.GetDataRepository <IAccountRepository>();
                IRentalRepository rentalRepository = _dataRepositoryFactory.GetDataRepository <IRentalRepository>();
                Account account = accountRepository.GetByLogin(loginEmail);
                if (account == null)
                {
                    NotFoundException ex = new NotFoundException(string.Format("No account found for login '{0}'", loginEmail));
                    throw new FaultException <NotFoundException>(ex, ex.Message);
                }

                ValidateAuthorization(account);

                IEnumerable <Rental> rentalHistory = rentalRepository.GetRentalHistoryByAccount(account.AccountId);

                return rentalHistory;
            }));
        }
 protected static InformationalUserError Handle(NotFoundException ex, string action)
     =>
         new InformationalUserError(ex,
             "We could not find this Content, perhaps it was removed or there is a network error",
             "Could not find the desired content");
 protected static InformationalUserError Handle(NotFoundException ex, string action)
     => new InformationalUserError(ex, "Could not find the desired content", CouldNotFindTheDesiredContent);
        public void ShouldReturnTrue_IfGenericArgumentIsTheSameTypeAsExpectedType()
        {
            var exception = new NotFoundException<object>("");

            Assert.That(Extension.IsType(exception, typeof(NotFoundException<>)));
        }
 public void Global_Output__WriteException(OutputLog control, bool includeInner = true)
 {
     var error3 = new ArgumentException("param", "Parameter value not set.");
     var error2 = new Exception(null, error3);
     var error1 = new NotFoundException("My Sample Error", error2);
     Output.WriteException(error1, includeInner);
 }