private HttpRequestmethod ParseMethod(string method)
 {
     if (!Enum.TryParse(method, true, out HttpRequestmethod parsedMethod))
     {
         BadRequestException.ThrowFromInvalidRequest();
     }
     return(parsedMethod);
 }
        public void BadRequestException_WhenCreate_ShouldReturnStatusCode()
        {
            // Act
            var sut = new BadRequestException();

            // Assert
            sut.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
        public async Task Should_Throw_Exception_UserNotFoundException()
        {
            BadRequestException e = await Assert.ThrowsAnyAsync <BadRequestException>(() =>
                                                                                      BotClient.PromoteChatMemberAsync(_fixture.SupergroupChat.Id, 123456)
                                                                                      );

            Assert.IsType <UserNotFoundException>(e);
        }
        public async Task Should_Throw_Exception_ChatNotFoundException()
        {
            BadRequestException e = await Assert.ThrowsAnyAsync <BadRequestException>(() =>
                                                                                      BotClient.SendTextMessageAsync(0, "test")
                                                                                      );

            Assert.IsType <ChatNotFoundException>(e);
        }
Example #5
0
        public void ContructorTest()
        {
            Assert.IsTrue(typeof(BadRequestException).IsSubclassOf(typeof(MtgExceptionBase)));

            BadRequestException exception = new BadRequestException("testing");

            Assert.AreEqual("MTG Api Error, testing", exception.Message);
        }
Example #6
0
        /// <inheritdoc />
        public virtual Task <IWebApiResponse> OnRequestAsync(MiddlewareContext context, Func <MiddlewareContext, CancellationToken, Task <IWebApiResponse> > callNext, CancellationToken cancellationToken = default)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (callNext is null)
            {
                throw new ArgumentNullException(nameof(callNext));
            }
            return(ExecAsync());

            async Task <IWebApiResponse> ExecAsync()
            {
                var httpResponse = await callNext(context, cancellationToken).ConfigureAwait(false);

                if (httpResponse == null)
                {
                    return(null !);
                }

                if ((int)httpResponse.StatusCode >= 200 && (int)httpResponse.StatusCode <= 299)
                {
                    return(httpResponse);
                }

                ErrorObject error;

                try
                {
                    error = JsonSerializer.Deserialize <ErrorObject>(httpResponse.Content, deserializerOptions);
                }
                catch (JsonException)
                {
                    // Fallback message
                    throw new UnexpectedStatusException(context.Request, httpResponse, httpResponse.Content ?? string.Empty);
                }

                var errorResponse = new WebApiResponse <ErrorObject>(error, httpResponse.StatusCode, httpResponse.ResponseHeaders);

                throw httpResponse.StatusCode switch
                      {
                          HttpStatusCode.BadRequest => BadRequestException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.Unauthorized => AuthorizationRequiredException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.Forbidden => AuthorizationRequiredException.CreateFromResponse(context.Request, errorResponse),
                          HttpStatusCode.NotFound => new NotFoundException(context.Request, errorResponse),
#if NETSTANDARD
                          (HttpStatusCode)429 => new TooManyRequestsException(context.Request, errorResponse),
#else
                          HttpStatusCode.TooManyRequests => new TooManyRequestsException(context.Request, errorResponse),
#endif
                          HttpStatusCode.InternalServerError => new ServerErrorException(context.Request, errorResponse),
                          HttpStatusCode.ServiceUnavailable => new ServiceUnavailableException(context.Request, errorResponse),
                          _ => new UnexpectedStatusException(context.Request, httpResponse, httpResponse.Content ?? string.Empty)
                      };
            }
        }
    }
Example #7
0
        public async Task <IActionResult> UpdateAProject([FromBody] ProjectProfile projectProfile, string projectNumber)
        {
            if (projectProfile == null)
            {
                var error = new BadRequestException("The given project profile is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (
                projectProfile.ProjectManager == null || String.IsNullOrEmpty(projectProfile.ProjectManager.UserID) ||
                projectProfile.ProjectSummary == null ||
                String.IsNullOrEmpty(projectProfile.ProjectSummary.ProjectNumber) || String.IsNullOrEmpty(projectNumber) ||
                projectProfile.ProjectSummary.Location == null
                )
            {
                var error = new BadRequestException("The Project (Manager(ID) / Summary / Number / Location) cannot be null or empty string!");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (projectProfile.ProjectSummary.ProjectNumber != projectNumber)
            {
                var errMessage = $"The project number on URL '{projectNumber}'" +
                                 $" does not match with '{projectProfile.ProjectSummary.ProjectNumber}' in Request Body's Project Summary";
                var error = new BadRequestException(errMessage);
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var location = await locationsRepository.GetALocation(projectProfile.ProjectSummary.Location.City);

                var updatedProjectNumber = await projectsRepository.UpdateAProject(projectProfile, location.Id);

                var response = new UpdatedResponse <string>(updatedProjectNumber, "Successfully updated");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                if (err is CustomException <InternalServerException> )
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, ((CustomException <InternalServerException>)err).GetException()));
                }
                else
                {
                    var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                    if (err is SqlException)
                    {
                        var error = new InternalServerException(errMessage);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                    }
                    else
                    {
                        var error = new BadRequestException(errMessage);
                        return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                    }
                }
            }
        }
Example #8
0
        public async Task <IActionResult> ConfirmResource([FromRoute] int openingId)
        {
            if (openingId == 0)
            {
                var error = new BadRequestException($"The given opening {openingId} is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }
            try
            {
                Position position = await positionsRepository.GetAPosition(openingId);

                if (position == null)
                {
                    var error = new NotFoundException($"Invalid positionId {openingId}.");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }

                if (position.ResourceId == null || position.ResourceId == "")
                {
                    var error = new BadRequestException($"Position {position.Id} does not have a resource assigned.");
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }

                position.IsConfirmed = true;
                var updatedPosition = await positionsRepository.UpdateAPosition(position);

                IEnumerable <Position> positionsOfUser = await positionsRepository.GetAllPositionsOfUser(position.ResourceId);

                IEnumerable <OutOfOffice> outOfOfficesOfUser = await outOfOfficeRepository.GetAllOutOfOfficeForUser(position.ResourceId);

                var utilization = await utilizationRepository.CalculateUtilizationOfUser(positionsOfUser, outOfOfficesOfUser);

                await usersRepository.UpdateUtilizationOfUser(utilization, position.ResourceId);

                RequestProjectAssign response = new RequestProjectAssign
                {
                    OpeningId            = openingId,
                    UserID               = position.ResourceId,
                    ConfirmedUtilization = utilization
                };
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Example #9
0
        public async Task Should_Throw_Exception_InvalidUserIdException()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowInvalidUserIdException);

            BadRequestException e = await Assert.ThrowsAnyAsync <BadRequestException>(() =>
                                                                                      BotClient.PromoteChatMemberAsync(_fixture.SupergroupChat.Id, 123456));

            Assert.IsType <InvalidUserIdException>(e);
        }
Example #10
0
        public async Task Should_Throw_On_Deleting_Chat_Deleted_Photo()
        {
            BadRequestException e = await Assert.ThrowsAsync <BadRequestException>(() =>
                                                                                   BotClient.DeleteChatPhotoAsync(_classFixture.Chat.Id));

            // ToDo: Create exception type
            Assert.IsType <BadRequestException>(e);
            Assert.Equal("Bad Request: CHAT_NOT_MODIFIED", e.Message);
        }
Example #11
0
        public async Task Should_Throw_Exception_While_Leaving_Private_Chat()
        {
            BadRequestException exception = await Assert.ThrowsAsync <BadRequestException>(
                async() => await BotClient.LeaveChatAsync(chatId: Fixture.PrivateChat)
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("chat member status can't be changed in private chats", exception.Message);
        }
Example #12
0
        public async Task Should_Throw_Exception_ChatNotFoundException()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowChatNotFoundException);

            BadRequestException e = await Assert.ThrowsAnyAsync <BadRequestException>(() =>
                                                                                      BotClient.SendTextMessageAsync(0, "test"));

            Assert.IsType <ChatNotFoundException>(e);
        }
Example #13
0
        public async Task Should_Throw_BadRequestExceptionn()
        {
            BadRequestException exception = await Assert.ThrowsAsync <BadRequestException>(
                async() => await BotClient.GetChatMemberAsync(Fixture.SupergroupChat.Id, -100120232)
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("wrong user_id specified", exception.Message);
        }
Example #14
0
        public IHttpResponse Handle(IHttpRequest request)
        {
            var    getParameters  = new Dictionary <string, string>(request.UrlParameters);
            var    postParameters = new Dictionary <string, string>(request.FormData);
            string requestMethod  = request.Method.ToString().ToUpper();
            string controllerName = string.Empty;
            string actionName     = string.Empty;

            var pathParts = request.Path
                            .Split(new[] { '/', '?' }, StringSplitOptions.RemoveEmptyEntries);

            if (request.Path == "/")
            {
                controllerName = $"Home{MvcContext.Get.ControllersSuffix}";
                actionName     = "Index";
            }
            else if (pathParts.Length < 2)
            {
                BadRequestException.ThrowFromInvalidRequest();
            }
            else
            {
                controllerName = $"{pathParts[0].Capitalize()}{MvcContext.Get.ControllersSuffix}";

                actionName = pathParts[1].Capitalize();
            }

            Controller controller = this.GetController(controllerName);

            if (controller != null)
            {
                controller.Request = request;
                controller.InitializeController();
            }

            MethodInfo methodInfo = this.GetMethod(controller, requestMethod, actionName);

            if (methodInfo == null)
            {
                return(new NotFoundResponse());
            }

            IEnumerable <ParameterInfo> parameters = methodInfo.GetParameters();

            object[] methodParameters = this.AddParameters(parameters, getParameters, postParameters);

            try
            {
                IHttpResponse response = this.GetResponse(methodInfo, controller, methodParameters);
                return(response);
            }
            catch (Exception e)
            {
                return(new InternalServerErrorResponse(e));
            }
        }
Example #15
0
        /// <summary>
        /// Returns an action result based on the input application exception
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static IActionResult ToActionResult(this ApplicationException ex)
        {
            return(ex switch
            {
                BadRequestException _ => new BadRequestObjectResult(ex.Message), //400

                ServiceNotAvailableException _ => new StatusCodeResult(503),

                _ => (IActionResult) new BadRequestResult(),
            });
        protected async Task SendServerUnavailableAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "SERVER_UNAVAILABLE", message)
            {
                Status = StatusCodes.Status503ServiceUnavailable
            };

            await SendErrorAsync(response, error);
        }
        protected async Task SendInternalErrorAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "INTERNAL", message)
            {
                Status = StatusCodes.Status500InternalServerError
            };

            await SendErrorAsync(response, error);
        }
Example #18
0
        private static BadRequestException GetModelValidationException <TParent, TChild>(
            TParent referringEntity, Guid childId)
            where TParent : IGuidIdentity where TChild : IGuidIdentity
        {
            var message =
                $"{typeof(TParent).Name} (id='{referringEntity.Id}') " +
                $"refers to an invalid {typeof(TChild).Name} (child Id='{childId}')";

            return(BadRequestException.BadReference(message));
        }
        protected async Task SendConflictAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "CONFLICT", message)
            {
                Status = StatusCodes.Status409Conflict
            };

            await SendErrorAsync(response, error);
        }
        protected async Task SendNotFoundAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "NOT_FOUND", message)
            {
                Status = StatusCodes.Status404NotFound
            };

            await SendErrorAsync(response, error);
        }
        protected async Task SendUnauthorizedAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "UNAUTHORIZED", message)
            {
                Status = StatusCodes.Status401Unauthorized
            };

            await SendErrorAsync(response, error);
        }
        protected async Task SendBadRequestAsync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "BAD_REQUEST", message)
            {
                Status = StatusCodes.Status400BadRequest
            };

            await SendErrorAsync(response, error);
        }
Example #23
0
        private static BadRequestException GetMissingRequiredReferenceException <TParent, TChild>(
            TParent referringEntity, Guid childId)
            where TParent : IGuidIdentity where TChild : IGuidIdentity
        {
            var message =
                $"{typeof(TParent).Name} (id='{referringEntity.Id}') " +
                $"is missing a mandatory reference to {typeof(TChild).Name}.";

            return(BadRequestException.BadReference(message));
        }
        protected async Task SendSessionExpiredASync(HttpRequest request, HttpResponse response, string message)
        {
            var correlationId = GetCorrelationId(request);
            var error         = new BadRequestException(correlationId, "SESSION_EXPIRED", message)
            {
                Status = 440
            };

            await SendErrorAsync(response, error);
        }
Example #25
0
 private static void HandleBadRequest(IHttpContext ctx, BadRequestException e)
 {
     ctx.SetStatusToBadRequest();
     SerializeError(ctx, new
     {
         Url = ctx.Request.RawUrl,
         e.Message,
         Error = e.Message
     });
 }
Example #26
0
        public async Task <IActionResult> GetMasterlists()
        {
            try
            {
                var disciplineResources = await disciplinesRepository.GetAllDisciplinesWithSkills();

                if (disciplineResources == null || !disciplineResources.Any())
                {
                    var error = new NotFoundException("No disciplines data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var disciplines = MapDisciplines(disciplineResources);

                var locationResources = await locationsRepository.GetAllLocationsGroupByProvince();

                if (locationResources == null || !locationResources.Any())
                {
                    var error = new NotFoundException("No locations data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var locations = MapLocations(locationResources);

                var yearsOfExp = await resourceDisciplineRepository.GetAllYearsOfExp();

                if (yearsOfExp == null || !yearsOfExp.Any())
                {
                    var error = new NotFoundException("No yearsOfExp data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }

                var resource = new MasterResource
                {
                    Disciplines = disciplines,
                    Locations   = locations,
                    YearsOfExp  = yearsOfExp
                };

                var response = new OkResponse <MasterResource>(resource, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
    private HttpRequestMethod ParseMethod(string method)
    {
        HttpRequestMethod parsedMethod;

        if (Enum.TryParse <HttpRequestMethod>(method, false, out parsedMethod))
        {
            BadRequestException.ThrowFromInvalidRequest();
        }

        return(parsedMethod);
    }
        private HttpRequestMethod ParseRequestMethod(string requestMethodString)
        {
            HttpRequestMethod parsedRequestMethod;

            if (!Enum.TryParse(requestMethodString, true, out parsedRequestMethod))
            {
                BadRequestException.ThrowFromInvalidRequest();
            }

            return(parsedRequestMethod);
        }
        private HttpRequestMethod ParseMethod(string method)
        {
            HttpRequestMethod parsedMethod;
            var parseTry = Enum.TryParse(method, true, out parsedMethod);

            if (!parseTry)
            {
                BadRequestException.ThrowFromInvalidRequest();
            }
            return(parsedMethod);
        }
        private void ParseRequestUrl(string[] requestLine)
        {
            string url = requestLine[1];

            if (string.IsNullOrEmpty(url))
            {
                BadRequestException.ThrowFromInvalidRequest();
            }

            this.Url = url;
        }
Example #31
0
 private static void HandleBadRequest(HttpListenerContext ctx, BadRequestException e)
 {
     ctx.SetStatusToBadRequest();
     using (var sw = new StreamWriter(ctx.Response.OutputStream))
     {
         new JsonSerializer().Serialize(sw,
                                        new
                                        {
                                        	url = ctx.Request.RawUrl,
                                        	message = e.Message,
                                        	error = e.Message
                                        });
     }
 }
Example #32
0
		private static void HandleBadRequest(IHttpContext ctx, BadRequestException e)
		{
			ctx.SetStatusToBadRequest();
			SerializeError(ctx, new
			{
				Url = ctx.Request.RawUrl,
				e.Message,
				Error = e.Message
			});
		}