예제 #1
0
        /// <summary>
        /// Returns our standard SingularError for a Conflict/409.
        /// </summary>
        /// <param name="errorCode">The error code.</param>
        /// <returns></returns>
        protected IActionResult Conflict(ApiErrors errorCode)
        {
            var message = Mapper.Map <FriendlyError>(errorCode);

            //message.CorrelationId = Logger.Log(Log.Severity.Error, Log.Category.Business, message.Message);
            return(StatusCode((int)HttpStatusCode.Conflict, message));
        }
예제 #2
0
        public static ApiResult GetApiRequest(ApiRequests type, string name)
        {
            name = GetName(name);
            string url = getApiUrl(type, name);

            try
            {
                ApiErrors error = ApiErrors.None_Online;
                WebClient wc    = new WebClient();
                wc.Encoding = Encoding.UTF8;
                string outs = wc.DownloadString(url).Replace("{", "").Replace("}", "");
                wc.Dispose();

                error = CheckError(outs);
                //if (error == ApiErrors.None)
                //{
                //    outs = outs.Replace("{\"stream\":", "");
                //}
                return(new ApiResult(outs, error, type));
            }
            catch (Exception x)
            {
                return(new ApiResult(x.Message, ApiErrors.Error, type));
            }
        }
 public static IActionResult BadRequest(this ControllerBase controller, ApiErrors apiError)
 {
     return(new BadRequestObjectResult(new
     {
         ErrorCode = apiError.Id,
         ErrorMessage = apiError.Value
     }));
 }
예제 #4
0
 public Startup()
 {
     _apiErrors  = new ApiErrors();
     _authConfig = new DataAuthConfig()
     {
         Key      = Environment.GetEnvironmentVariable("AUTH_KEY"),
         Audience = Environment.GetEnvironmentVariable("AUTH_AUDIENCE"),
         Issuer   = Environment.GetEnvironmentVariable("AUTH_ISSUER"),
         Lifetime = int.Parse(Environment.GetEnvironmentVariable("AUTH_LIFETIME") ??
                              throw new Exception("AUTH_LIFETIME must me a number"))
     };
 }
예제 #5
0
        /// <summary>
        /// Returns our standard SingularError for an internal server error
        /// </summary>
        /// <param name="errorCode">The error code.</param>
        /// <param name="ex"></param>
        /// <returns>NegotiatedContentResult <see cref="FriendlyError"/>.</returns>
        protected IActionResult InternalServerError(ApiErrors errorCode, Exception ex)
        {
            var bve = ex.GetBaseException() as BusinessValidationException;

            if (bve != null)
            {
                // sometimes BVE's are wrapped up in other exceptions (e.g. during an AutoMapper map)
                // find the BVE and responds appropriately according to it
                return(BadRequest(bve));
            }
            var message = Mapper.Map <FriendlyError>(errorCode);

            //message.CorrelationId = Logger.Log(Log.Severity.Error, Log.Category.Business, ex);
            message.SetException(ex);

            return(StatusCode((int)HttpStatusCode.InternalServerError, message));
        }
예제 #6
0
        protected override async Task <IProcessResult <EmptyResult> > Handle(DeleteExpenditureRequest msg)
        {
            var exp = await coreExpenditureRepo.GetExpenditureCoreInfoByExternalId(msg.ExpenditureToDelete);

            if (exp == null)
            {
                return(Failure(ApiErrors.NotFoundException($"No expense exists with id: {msg.ExpenditureToDelete}")));
            }


            switch (exp.ExpenditureType)
            {
            case ExpenditureTypeEnum.ArcFlashLabelExpenditure:
                await arcFlashLabelExpenditureRepo.DeleteEntity(msg.ExpenditureToDelete);

                break;

            case ExpenditureTypeEnum.CompanyVehicleExpenditure:
                await companyVehicleExpenditureRepo.DeleteEntity(msg.ExpenditureToDelete);

                break;

            case ExpenditureTypeEnum.ContractorExpenditure:
                await contractorExpenditureRepo.DeleteEntity(msg.ExpenditureToDelete);

                break;

            case ExpenditureTypeEnum.MiscExpenditure:
                await miscExpenditureRepo.DeleteEntity(msg.ExpenditureToDelete);

                break;

            case ExpenditureTypeEnum.TimeAndExpenceExpenditure:
                await timeAndExpenceExpenditureRepo.DeleteEntity(msg.ExpenditureToDelete);

                break;

            default:
                throw new NotImplementedException();
            }

            return(Success(EmptyResult.Instance));
        }
예제 #7
0
        public async Task <IActionResult> Login(LoginReqDto loginReq)
        {
            var user = await uow.UserRepository.Authenticate(loginReq.UserName, loginReq.Password);

            ApiErrors apiError = new ApiErrors();

            if (user == null)
            {
                apiError.ErrorCode    = Unauthorized().StatusCode;
                apiError.ErrorMessage = "Invalid User ID or Password";
                apiError.ErrorDetails = "Provided user details are invalid";
                return(Unauthorized(apiError));
            }

            var loginRes = new LoginResDto();

            loginRes.UserName = user.Username;
            loginRes.Token    = CreateJWT(user);
            return(Ok(loginRes));
        }
예제 #8
0
 public static void AppHandlerException(IApplicationBuilder errorApp, ApiErrors apiErrors)
 {
     errorApp.Run(async context =>
     {
         var error = context.Features.Get <IExceptionHandlerPathFeature>().Error;
         if (error.GetType() == typeof(Error))
         {
             var errInstance = (Error)error;
             context.Response.ContentType = "application/json";
             context.Response.StatusCode  = errInstance.HttpStatus;
             await context.Response.WriteAsync(JsonConvert.SerializeObject(errInstance));
         }
         else
         {
             context.Response.ContentType = "application/json";
             context.Response.StatusCode  = apiErrors.ServerError.HttpStatus;
             await context.Response.WriteAsync(JsonConvert.SerializeObject(apiErrors.ServerError));
         }
     });
 }
예제 #9
0
        public Task <ActionResult> Get(int year, int month, string type)
        {
            if (string.IsNullOrEmpty(type))
            {
                return(Task.FromResult(FaultedActionResult(BlErrors.Error1002(nameof(type)))));
            }

            var lowerType = type.ToLower();

            if (lowerType == REPORT_TYPE_TXT)
            {
                return(ActionResultAsync(_rateService.GetTxtReportAsync(year, month)));
            }

            else if (lowerType == REPORT_TYPE_JSON)
            {
                return(ActionResultAsync(_rateService.GetReportAsync(year, month)));
            }

            return(Task.FromResult(FaultedActionResult(ApiErrors.Error2001(type))));
        }
예제 #10
0
        public void OnException(ExceptionContext context)
        {
            var error = new ApiErrors();

            if (_hostingEnviorment.IsDevelopment())
            {
                error.Message = context.Exception.Message;
                error.Details = context.Exception.StackTrace;
            }
            else
            {
                error.Message = "A server error occured.";
                error.Details = context.Exception.Message;
            }


            context.Result = new ObjectResult(error)
            {
                StatusCode = 500
            };
        }
예제 #11
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context); //means all of the code is in try catch block
            }
            catch (Exception ex)
            {
                ApiErrors      response;
                HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
                String         message;
                var            exceptionType = ex.GetType();

                if (exceptionType == typeof(UnauthorizedAccessException))
                {
                    statusCode = HttpStatusCode.Forbidden;
                    message    = "You are not authorized";
                }
                else
                {
                    statusCode = HttpStatusCode.InternalServerError;
                    message    = "Some unknown error occured";
                }

                if (env.IsDevelopment())
                {
                    response = new ApiErrors((int)statusCode, ex.Message, ex.StackTrace.ToString());
                }
                else
                {
                    response = new ApiErrors((int)statusCode, message);
                }


                logger.LogError(ex, ex.Message);
                context.Response.StatusCode  = (int)statusCode;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(response.ToString());
            }
        }
예제 #12
0
        public async Task <IActionResult> Register(LoginReqDto loginReq)
        {
            ApiErrors apiError = new ApiErrors();

            if (loginReq.UserName.IsEmpty() || loginReq.Password.IsEmpty())
            {
                apiError.ErrorCode    = BadRequest().StatusCode;
                apiError.ErrorMessage = "User name or password can not be blank";
                return(BadRequest(apiError));
            }

            if (await uow.UserRepository.UserAlreadyExists(loginReq.UserName))
            {
                apiError.ErrorCode    = BadRequest().StatusCode;
                apiError.ErrorMessage = "User already exists, please try something new";
                return(BadRequest(apiError));
            }


            uow.UserRepository.Register(loginReq.UserName, loginReq.Password);
            await uow.SaveAsync();

            return(StatusCode(201));
        }
예제 #13
0
 public NewsService(RipDatabase db, ApiErrors apiErrors)
 {
     _apiErrors = apiErrors;
     _db        = db;
 }
예제 #14
0
 public ProfileService(RipDatabase db, ApiErrors apiErrors)
 {
     _apiErrors = apiErrors;
     _db        = db;
 }
예제 #15
0
 public ApiException(ApiErrors error, Exception innerException = null) : base(error.GetDescription(),
                                                                              innerException)
 {
     ErrorNumber = (int)error;
 }
예제 #16
0
 public ApiResult(string Raw, ApiErrors error, ApiRequests request)
 {
     raw          = Raw;
     this.error   = error;
     this.request = request;
 }
예제 #17
0
 public CommentService(RipDatabase db, ApiErrors apiErrors)
 {
     _apiErrors = apiErrors;
     _db        = db;
 }
예제 #18
0
 public AuthService(RipDatabase ripDatabase, DataAuthConfig authConfig, ApiErrors apiErrors)
 {
     _db         = ripDatabase;
     _authConfig = authConfig;
     _apiErrors  = apiErrors;
 }