private static void HandleJsonException(HttpActionExecutedContext ec)
        {
            ErrorDto data = new ErrorDto();

            // Different data depending on exception type
            var exceptionType = ec.Exception.GetType();
            if (exceptionType == typeof(BrokenRuleException))
            {
                data.BrokenRules = GetDistinctBrokenRules(((BrokenRuleException) ec.Exception).BrokenRules);
            }
            else if (exceptionType == typeof(UserFriendlyException))
            {
                data.Message = ec.Exception.Message.Replace("\r\n", "<br/>");
            }
            else
            {
                data.Message = string.Format("An unexpected error has occurred. Please try agian.");
            }

            ec.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content =
                    new ObjectContent<ErrorDto>(
                        data,
                        new JsonMediaTypeFormatter() {UseDataContractJsonSerializer = false})
            };
        }
        public async Task ExecuteAsync(IdentityServerContext context)
        {
            var dto = new ErrorDto
            {
                error = Error,
                error_description = ErrorDescription
            };

            context.HttpContext.Response.StatusCode = 400;
            context.HttpContext.Response.SetNoCache();
            await context.HttpContext.Response.WriteJsonAsync(dto);
        }
        private HttpResponseMessage Execute()
        {
            var dto = new ErrorDto
            {
                error = _error 
            };

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new ObjectContent<ErrorDto>(dto, new JsonMediaTypeFormatter())
            };

            return response;
        }
        private HttpResponseMessage Execute()
        {
            var dto = new ErrorDto
            {
                error = Error 
            };

            var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new ObjectContent<ErrorDto>(dto, new JsonMediaTypeFormatter())
            };

            Logger.Info("Returning error: " + Error);
            return response;
        }
Esempio n. 5
0
        public async Task <IActionResult> UpdateUser([FromBody] User user)
        {
            try
            {
                user.Modificado = DateTime.Now;
                var result = await service.Update(user);

                if (result)
                {
                    return(Ok(result));
                }

                return(StatusCode(result.StatusCode, ErrorDto.Create(result.StatusCode, result.Error)));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ErrorDto.Create(500, "Internal server error")));
            }
        }
Esempio n. 6
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // ** method that take id parameters in product has one value so FirstOrDefault() will work.
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _productService.GetByIdAsyn(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();
                errorDto.Status = 404;
                errorDto.Errors.Add($"ProductId = {id} was not found in the Database.");
                context.Result = new NotFoundObjectResult(errorDto);
            }
        }
Esempio n. 7
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id      = (int)context.ActionArguments.Values.FirstOrDefault();//controllerdeki actionların idsini yakalar.
            var product = await _productService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Status = 404;
                errorDto.Errors.Add($"id'si {id} olan ürün veritabanında bulunamadı.");

                context.Result = new NotFoundObjectResult(errorDto);
            }
        }
        internal OperationResult <T> CallServicePut <T>(string jsonRequest, string method)
        {
            InitializeClient();
            HttpContent content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

            string responseString;

            try
            {
                var response = client.PutAsync(method, content).Result;
                responseString = response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                return(new OperationResult <T>(ErrorDto.BuildTechnical(ex.Message)));
            }

            return(deserialize.Execute <T>(responseString));
        }
Esempio n. 9
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _categoryApiService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Errors.Add($"The Category with the id {id} could not be found in the variant");

                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
        public void CreateError_LongMessage_MessageTruncatedErrorCreated()
        {
            ErrorDto errorDto = new ErrorDto
            {
                Message       = "Hello World This is a Really Long Message Which is going to be over 255 characters in length when finished which will cause the end result message to be truncated with three periods as to not overflow the database. Can I confirm that this is happening? Thanks",
                ClientVersion = "0.99",
                LineNumber    = 2
            };

            NHibernateSessionManager.Instance.OpenSessionAndBeginTransaction();
            JsonServiceStackResult result = (JsonServiceStackResult)ErrorController.Create(errorDto);

            NHibernateSessionManager.Instance.CommitTransactionAndCloseSession();

            ErrorDto createdErrorDto = (ErrorDto)result.Data;

            Assert.NotNull(createdErrorDto);
            Assert.That(createdErrorDto.Message.Length == 255);
        }
Esempio n. 11
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = Convert.ToInt32(context.ActionArguments.Values.FirstOrDefault());

            var product = await _categoryService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Errors.Add($"category not found with id number{id}");

                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
Esempio n. 12
0
        public ErrorDto DeleteBand(int bandId)
        {
            using (var db = new MusicBandAppEntities())
            {
                var responseDto = new ErrorDto();
                var band        = db.Bend.Where(x => x.id_bend == bandId);

                if (band.Count() > 1)
                {
                    responseDto.ErrorCode = (int)ValidationStatusCode.ResultsetHasMoreItems;
                }
                else
                {
                    band.FirstOrDefault().tip_korisnika = 3;
                    db.SaveChanges();
                }
                return(responseDto);
            }
        }
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id      = (int)context.ActionArguments.Values.FirstOrDefault();//metotlarda tanımladığımız id leri yakalayacak.
            var product = await _categoryService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();
                //api den farklı olarak json döndürmeyeceğiz
                errorDto.Error.Add($"Id'si {id} olan kategori veritabanında bulunamadı!");
                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
                //object dönmek yerine sayfa yönlendiricez bu mvc side
                //error actionu, home controller sayfasındaki , errordtosunuda göster diyoruz.
            }
        }
Esempio n. 14
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var res = await _service.GetByIdAsync(id);

            ErrorDto errorDto = new ErrorDto();

            if (res != null)
            {
                await next();
            }
            else
            {
                errorDto.Status = 404;
                errorDto.Errors.Add($"{id} id'li departman veritabınında bulunamadı.");
                context.Result = new NotFoundObjectResult(errorDto);
            }
        }
        // READ ALL
        public List <Item> GetAllItems(out ErrorDto error)
        {
            error = null;

            using (var db = _shoppingContext) {
                List <Item> i = db.Items.ToList();

                if (!i.Any())
                {
                    error = new ErrorDto {
                        ErrorMsg  = NotFoundMsg(DomainNamePlural),
                        ErrorWhen = "when attempting to get all item entities from database",
                        ClassType = typeof(ItemRepository),
                        ErrorType = ErrorType.EmptyTableError
                    };
                }
                return(i);
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> GetDocument(string dbname, string index, string id)
        {
            if (await UserService.CheckAuthorize(Request, false, dbname) is null)
            {
                return(Unauthorized(ErrorDto.GetAuthError()));
            }
            if (Guid.TryParse(id, out var guid))
            {
                var result = await DatabaseService.FindById(new IndexModel(dbname, index), guid);

                if (result is null)
                {
                    return(NoContent());
                }
                return(Ok(DocumentMapper.MapToDto(result)));
            }

            return(BadRequest(new ErrorDto(ErrorsType.SyntaxError, $"{id} is not GUID")));
        }
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id      = (int)context.ActionArguments.Values.FirstOrDefault();//controllerdeki actionların idsini yakalar.
            var product = await _categoryService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();


                errorDto.Errors.Add($"id'si {id} olan kategori veritabanında bulunamadı.");

                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
Esempio n. 18
0
        public async Task <IActionResult> UpdateObject([FromBody] object obj, string dbname, string index, string id)
        {
            if (await UserService.CheckAuthorize(Request, false, dbname) is null)
            {
                return(Unauthorized(ErrorDto.GetAuthError()));
            }
            try
            {
                await DatabaseService.Update(new IndexModel(dbname, index), obj, id);

                _logger.Log(LogLevel.Information, $"INFO: Update object with id: {id} in {dbname}/{index}. New object: {obj}");
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, $"ERROR: error updating with id: {id}, exception: {ex}");
                return(BadRequest(new ErrorDto(ErrorsType.SystemError, $"{ex.Message}")));
            }
            return(StatusCode(202));
        }
Esempio n. 19
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Status = 400;

                IEnumerable <ModelError> modelErrors =
                    context.ModelState.Values.SelectMany(v => v.Errors);

                modelErrors.ToList().ForEach(x =>
                {
                    errorDto.Errors.Add(x.ErrorMessage);
                });

                context.Result = new BadRequestObjectResult(errorDto);
            }
        }
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _categoryApiService.GetByIdAsync(id);

            if (product != null)
            {
                await next();   //next metoduyla gelen requesti bir sonraki adıma aktarıyoruz.
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Errors.Add($"Id değeri {id} olan kategori veritabanında bulunamadı.");

                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _productService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();
                errorDto.Status = 404;
                errorDto.Errors.Add($"The product with the id {id} could not be found in the variant");

                context.Result = new NotFoundObjectResult(errorDto);
            }
        }
Esempio n. 22
0
        public async Task <ResponseDto <Customer> > SetCustomerStatus(int customerId, CustomerStatus customerStatus)
        {
            var customer = await _dbContext.Customers.FindAsync(customerId);

            if (customer == null)
            {
                var errorDto      = new ErrorDto("The customer was not found.");
                var errorResponse = new ResponseDto <Customer>(errorDto);

                return(errorResponse);
            }

            customer.Status = customerStatus;
            await _dbContext.SaveChangesAsync();

            var responseDto = new ResponseDto <Customer>(customer);

            return(responseDto);
        }
Esempio n. 23
0
        public static void UseCustomValidationResponse(this IServiceCollection services)
        {
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var errors = context.ModelState.Values.Where(x => x.Errors.Count > 0).SelectMany(x => x.Errors).Select(x => x.ErrorMessage);

                    ErrorDto errorDto = new ErrorDto();

                    errorDto.Errors.AddRange(errors);

                    errorDto.Status = 400;
                    errorDto.IsShow = true;

                    return(new BadRequestObjectResult(errorDto));
                };
            });
        }
Esempio n. 24
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _productService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }

            ErrorDto errorDto = new ErrorDto();

            errorDto.Status = 404;

            errorDto.Errors.Add($"id'si {id} olan ürün bulunamadı");

            context.Result = new NotFoundObjectResult(errorDto);
        }
Esempio n. 25
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int Id     = (int)context.ActionArguments.Values.Last();
            var result = await _service.GetByIdAsync(Id);

            if (result == null)
            {
                ErrorDto errorDto = new ErrorDto();
                errorDto.StatusCode = 400;
                errorDto.Errors.Add($"{Id} id'li nesne bulunmadı!");


                context.Result = new NotFoundObjectResult(errorDto);
            }
            else
            {
                await next();
            }
        }
Esempio n. 26
0
        public void LogException(ErrorDto error)
        {
            if (!File.Exists("ExceptionLog.xml"))
            {
                new XDocument(new XElement("root")).Save("ExceptionLog.xml");
            }

            //Xml dosyasına hatayı loglayan kodlar
            XDocument docXml = XDocument.Load("ExceptionLog.xml");

            docXml.Element("root").Add(
                new XElement("error",
                             new XElement("url", error.Url),
                             new XElement("type", error.RequestType),
                             new XElement("error", error.Exception)
                             )
                );
            docXml.Save("ExceptionLog.xml");
        }
        public IHttpActionResult GetTransactionsLog()
        {
            var transactionLog = _unitOfWork.TransactionLogs.GetAllOrderByCreationTsDesc();

            List <TransactionApiOutputDto> _transactionsApiOutputDto = new List <TransactionApiOutputDto>();

            foreach (var l in transactionLog)
            {
                var transactionId = _unitOfWork.Transactions.GetTransactionFromTransactionLog(l.Id);

                var transactionApiOutputDto = new TransactionApiOutputDto
                {
                    amount             = l.Amount,
                    card_brand         = l.Card_brand,
                    card_holder_name   = l.Card_holder_name,
                    card_number_first  = l.Card_number_first,
                    card_number_last   = l.Card_number_last,
                    creation_timestamp = l.Creation_timestamp,
                    installments       = l.Installments,
                    status_code        = l.Status_code,
                    status_reason      = l.Status_reason,
                    transaction_id     = transactionId,
                    transaction_type   = l.Transaction_type,
                    transaction_log_id = l.Id
                };

                var errorLog = _unitOfWork.ErrorLogs.GetAllErrorsFromTransactionLog(l.Id);

                List <ErrorDto> _errorsDto = new List <ErrorDto>();
                foreach (var e in errorLog)
                {
                    var errorDto = new ErrorDto(e.Error_code, e.Error_message);
                    _errorsDto.Add(errorDto);
                }

                transactionApiOutputDto.errors = _errorsDto;

                _transactionsApiOutputDto.Add(transactionApiOutputDto);
            }

            return(Ok(_transactionsApiOutputDto));
        }
        public async Task <IActionResult> MultiSearch([FromBody] MultiSearchModel searchModel, string dbname, string index)
        {
            if (await UserService.CheckAuthorize(Request, false, dbname) is null)
            {
                return(Unauthorized(ErrorDto.GetAuthError()));
            }
            try
            {
                var docs = await _searcher.MultiSearch(new IndexModel(dbname, index), searchModel);

                var result = docs.Select(DocumentMapper.MapToDto);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, $"ERROR: Search {searchModel.QueryType} in {dbname}/{index}, Error: {ex}");
                return(BadRequest(new ErrorDto(ErrorsType.SystemError, ex.Message)));
            }
        }
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var user = await _movieService.GetByIdAsync(id);

            if (user != null)
            {
                await next();
            }

            else
            {
                ErrorDto error = new ErrorDto();
                error.Status = 404;
                error.Errors.Add("Böyle id de film veritabanında bulunmamaktadır");

                context.Result = new NotFoundObjectResult(error);
            }
        }
Esempio n. 30
0
        public async Task <IActionResult> DeleteIndex(string dbname, string index)
        {
            if (await UserService.CheckAuthorize(Request, true) is null)
            {
                return(Unauthorized(ErrorDto.GetAuthError()));
            }
            try
            {
                await DatabaseService.DeleteIndex(new IndexModel(dbname, index));

                _logger.Log(LogLevel.Information, $"INFO: Delete index {dbname}/{index}");
            }
            catch (FileNotFoundException)
            {
                _logger.Log(LogLevel.Error, $"ERROR: index {dbname}/{index} not found");
                return(NoContent());
            }

            return(Ok());
        }
Esempio n. 31
0
        private ErrorDto MapToResponseError(Exception exception)
        {
            ErrorDto error;

            if (exception is DefaultException ex)
            {
                error = _mapper.Map <ErrorDto>(ex);
            }
            else
            {
                error = new ErrorDto()
                {
                    Message = exception.Message,
                    Source  = exception.Source
                };
            }

            error.StackTrace = _env.IsDevelopment() ? exception.StackTrace : null;
            return(error);
        }
Esempio n. 32
0
        public static void UseCustomExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(config => {
                config.Run(async context => {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "application/json";

                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        var ex = error.Error;

                        ErrorDto errorDto = new ErrorDto();
                        errorDto.Errors.Add(ex.Message);

                        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorDto));
                    }
                });
            });
        }
Esempio n. 33
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id      = (int)context.ActionArguments.Values.FirstOrDefault();
            var product = await _categoryService.GetByIdAysnc(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto
                {
                    StatusCode = 404
                };
                errorDto.Errors.Add($"Category not found : id({id}) ");

                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
        // READ PER ID
        public Item GetItem(int itemId, out ErrorDto error)
        {
            error = null;

            using (var db = _shoppingContext) {
                var item = db.Items
                           .Where(i => i.ItemId == itemId);

                if (!item.Any())
                {
                    error = new ErrorDto {
                        ErrorMsg  = NotFoundMsg(DomainNameSingular, itemId.ToString()),
                        ErrorWhen = "when attempting to get item with id: " + itemId,
                        ErrorType = ErrorType.EntryNotFoundError,
                        ClassType = _classType
                    };
                }
                return(item.First());
            }
        }