public void OnException(ExceptionContext context)
        {
            var result = new ViewResult {
                ViewName = "CustomException"
            };
            var modelMetadata = new EmptyModelMetadataProvider();

            result.ViewData = new ViewDataDictionary(modelMetadata, context.ModelState);
            result.ViewData.Add("HandleException", context.Exception);
            context.Result           = result;
            context.ExceptionHandled = true;
            logger.LogInformation(context.Exception.Message.ToString());
            logger.LogInformation(context.Exception.StackTrace.ToString());
        }
Example #2
0
 public IActionResult Privacy()
 {
     try
     {
         throw new Exception("Exception Raised in Privacy and Handled in Controller");
         return(View());
     }
     catch (Exception e)
     {
         ErrorViewModel defaultpage = new ErrorViewModel();
         _logger.LogInformation(e.Message.ToString());
         _logger.LogInformation(e.StackTrace.ToString());
         return(View("Error", defaultpage));
     }
 }
Example #3
0
 public StatusResponse Get()
 {
     _logger.LogInformation("Sending status back");
     return(new StatusResponse {
         Status = "OK", Version = "0.1.0"
     });
 }
        public IEnumerable <WeatherForecast> Get()
        {
            try
            {
                _loggerManager.LogEnter();
                _loggerManager.LogDebug("Log Debug");
                _loggerManager.LogInformation("Log info");
                _loggerManager.LogWarning("Log warning");
                int i = 5;
                int d = 0;
                //Console.WriteLine((i / d).ToString());

                var rng = new Random();
                return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                       .ToArray());
            }
            finally
            {
                _loggerManager.LogExit();
            }
        }
Example #5
0
        public IEnumerable <string> Get()
        {
            _logger.LogDebug("Test debug message from the controller");
            _logger.LogError("Test error message from the controller");
            _logger.LogWarning("Test warning message from the controller");
            _logger.LogInformation("Test information message from the controller");

            return(new string[] { "value1", "value2" });
        }
Example #6
0
        public IActionResult Index()
        {
            //Traza personzalido Mensaje Tipo Informativo
            _logger.LogInformation("Metodo Informativo");

            //Traza personzalido Mensaje Tipo Advertencia
            _logger.LogAdvertencia("Metodo Warning");

            //Traza personzalido Mensaje Tipo Error
            _logger.LogError("Metodo Error");

            //Traza con el Nombre del Metodo, Mensaje de Excepcion y Mensaje Tipo Informativo
            _logger.LogInformation(System.Reflection.MethodBase.GetCurrentMethod().Name, new Exception("Mensaje Excepcion Info"));

            //Traza con el Nombre del Metodo, Mensaje de Excepcion y Mensaje Tipo Advertencia
            _logger.LogAdvertencia(System.Reflection.MethodBase.GetCurrentMethod().Name, new Exception("Mensaje Excepcion Advertencia"));

            //Traza con el Nombre del Metodo, Mensaje de Excepcion y Mensaje Tipo Error
            _logger.LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, new Exception("Mensaje Excepcion Error"));


            return(View());
        }
 public IActionResult Index()
 {
     throw new Exception("Error happened in index");
     _logger.LogInformation("Running Home/Index");
     return(View());
 }
 public IActionResult Index()
 {
     _logger.LogInformation("Logger Logging Information...");
     return(View());
 }
Example #9
0
 public void OnException(ExceptionContext context)
 {
     _logger.LogInformation(context.Exception.ToString());
 }
Example #10
0
        public async Task <ActionResult <Purchase> > PurchaseCurrency(PurchaseDto purchaseDto)
        {
            try
            {
                double exchange            = 0;
                double totalAmountPurchase = 0;

                if (purchaseDto == null)
                {
                    _logger.LogError("Purchase object sent from client is null.");
                    return(BadRequest("Purchase object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid purchase object sent from client.");

                    return(BadRequest("Invalid model object"));
                }

                var purchase = new Purchase
                {
                    UserId   = purchaseDto.userId,
                    Amount   = double.Parse(purchaseDto.amount),
                    Currency = purchaseDto.currency.ToLower(),
                    Month    = DateTime.Today.Month,
                    Year     = DateTime.Today.Year
                };

                // valid amount
                if (purchase.Amount <= 0)
                {
                    _logger.LogError("Invalid purchase amount sent from client.");

                    return(NotFound(new NotFoundError("Invalid amount")));
                }

                // check if is a valid currency.
                if (purchase.Currency != "dolar" && purchase.Currency != "real")
                {
                    _logger.LogError("Invalid purchase currency sent from client.");

                    return(NotFound(new NotFoundError("The currency was not found")));
                }

                // get all purchase for this user in this month with this currency.
                var purchaseByMonthList = _purchaseService.GetByUserIdAndMonthAndCurrency(purchase);

                foreach (var purchaseByMonth in purchaseByMonthList)
                {
                    totalAmountPurchase = totalAmountPurchase + purchaseByMonth.Amount;
                }

                // check if exceeds the minimal amount.
                if ((totalAmountPurchase >= 200 && purchase.Currency == "dolar") || (totalAmountPurchase >= 300 && purchase.Currency == "real"))
                {
                    _logger.LogError("Invalid purchase because the user exceeds monthly purchase limit.");

                    return(NotFound(new NotFoundError("The user exceeds monthly purchase limit")));
                }

                var exchangeResponse = await _exchangeController.ExchangeRate(purchase.Currency);

                if (exchangeResponse is OkObjectResult exchangeRate && exchangeRate.Value != null)
                {
                    // get the exchange rate sold.
                    var sold = exchangeRate.Value.GetType().GetProperty("sold").GetValue(exchangeRate.Value).ToString();

                    exchange            = double.Parse(sold);
                    purchase.Amount     = purchase.Amount / exchange;
                    totalAmountPurchase = totalAmountPurchase + purchase.Amount;

                    if ((totalAmountPurchase >= 200 && purchase.Currency == "dolar") || (totalAmountPurchase >= 300 && purchase.Currency == "real"))
                    {
                        _logger.LogError("Invalid purchase because the user exceeds monthly purchase limit.");

                        return(NotFound(new NotFoundError("The user exceeds monthly purchase limit")));
                    }

                    _purchaseService.Create(purchase);

                    _logger.LogInformation($"The creation of a purchase was successfully.");

                    return(CreatedAtRoute("GetPurchase", new { id = purchase.Id }, purchase));
                }

                return(BadRequest(new InternalServerError("The external service don't response")));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Faild Create purchase. Message: {ex.Message}");

                return(BadRequest(new InternalServerError()));
            }
        }