/// <summary>
        /// Stops the hosted service by first disposing of any <c>IDisposable</c> instances that are created during
        /// service startup.
        /// </summary>
        /// <param name="cancellationToken"/>
        /// <returns/>
        public virtual Task StopAsync(CancellationToken cancellationToken)
        {
            _logger?.LogInformation($"RabbitMqService {_rmqConfig.Id} is stopping.");

            if (!cancellationToken.IsCancellationRequested)
            {
                var serviceTypeName = _isConsumer ? nameof(RabbitMqConsumer <T>) : nameof(RabbitMqProducer <T>);

                try
                {
                    _disposables.ForEach(subscription => subscription.Dispose());
                }
                catch (Exception exception)
                {
                    _logger?.LogCritical(
                        $"Duplicate IDisposable disposal on {serviceTypeName} termination: " +
                        $"{exception.Message}\n" +
                        exception.StackTrace);
                }

                try
                {
                    Bus.Dispose();
                }
                catch (Exception exception)
                {
                    _logger?.LogCritical(
                        $"Could not dispose {nameof(IAdvancedBus)} on {serviceTypeName} termination: " +
                        $"{exception.Message}\n" +
                        exception.StackTrace);
                }
            }

            return(Task.CompletedTask);
        }
        // TODO: THIS USE OF REFLECTION IS FRAGILE AND MUST BE RECONSIDERED
        private static IModel?ExtractModelFromInternalConsumer(IConsumer consumer, ILogger?logger)
        {
            IModel?model        = null;
            var    consumerType = consumer.GetType();

            var internalConsumersField =
                consumerType.GetField("internalConsumers", BindingFlags.Instance | BindingFlags.NonPublic);

            if (internalConsumersField != null)
            {
                var internalConsumers = (ConcurrentSet <IInternalConsumer>)internalConsumersField.GetValue(consumer);
                // ReSharper disable once AssignNullToNotNullAttribute
                // ReSharper disable once ConstantConditionalAccessQualifier
                model = ((InternalConsumer)internalConsumers.FirstOrDefault())?.Model;
            }

            var internalConsumerField =
                consumerType.GetField("internalConsumer", BindingFlags.Instance | BindingFlags.NonPublic);

            if (internalConsumerField != null)
            {
                var internalConsumer = (IInternalConsumer)internalConsumerField.GetValue(consumer);
                // ReSharper disable once ConstantConditionalAccessQualifier
                model = ((InternalConsumer)internalConsumer)?.Model;
            }

            if (model == null)
            {
                logger?.LogCritical(
                    $"Could not extract a non null {nameof(IModel)} " +
                    $"from the provided {nameof(IConsumer)}.");
            }

            return(model);
        }
 public StudentsController(IOptions<RedisConfig> redisConfig, ILogger<StudentsController> logger)
 {
     String redisConnection = redisConfig.Value.RedisConnection;
     _logger = logger;
     _logger.LogCritical("logging redis connection: " + redisConnection);
     _studentRepository = new StudentRepository(ConnectionMultiplexer.Connect(redisConnection).GetDatabase(0));
     _classRepository = new ClassRepository(ConnectionMultiplexer.Connect(redisConnection).GetDatabase(0));
 }
Exemple #4
0
 public void Dispose()
 {
     if (_disposed)
     {
         return;
     }
     _disposed = true;
     try {
         _connection.Dispose();
     } catch (Exception ex) {
         _logger?.LogCritical(ex.ToString());
     }
 }
Exemple #5
0
        public async Task Invoke(HttpContext httpContext,
                                 IDbConnection dbConnection,
                                 IHostApplicationLifetime appLifetime,
                                 ILogger <FirstRunMiddleware> logger)
        {
            var initFlag = AppDomain.CurrentDomain.GetData(Token);

            if (initFlag is not null)
            {
                // Don't need to check bool true or false, exists means everything
                await _next(httpContext);

                return;
            }

            var setupHelper = new SetupRunner(dbConnection);

            if (!setupHelper.TestDatabaseConnection(exception =>
            {
                logger?.LogCritical(exception, $"Error {nameof(SetupRunner.TestDatabaseConnection)}, connection string: {dbConnection}");
            }))
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await httpContext.Response.WriteAsync("Database connection failed. Please see error log, fix it and RESTART this application.");

                appLifetime?.StopApplication();
            }
            else
            {
                if (setupHelper.IsFirstRun())
                {
                    try
                    {
                        logger.LogInformation("Initializing first run configuration...");
                        setupHelper.InitFirstRun();
                        logger.LogInformation("Database setup successfully.");
                    }
                    catch (Exception e)
                    {
                        logger.LogCritical(e, e.Message);
                        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        await httpContext.Response.WriteAsync("Error initializing first run, please check error log.");

                        appLifetime.StopApplication();
                    }
                }

                AppDomain.CurrentDomain.SetData(Token, true);
                await _next(httpContext);
            }
        }
        public IActionResult GetAirPortJson()
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(GetAirPortJson));

            Functions      functions;
            List <AirPort> ListAirports;

            try
            {
                functions = new Functions();

                ListAirports = new List <AirPort>();

                ListAirports = functions.AriPortsList();

                return(new ObjectResult(ListAirports));
            }
            catch (Exception ex)
            {
                Logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(GetAirPortJson), ex.Message);
                return(BadRequest(ex.Message));
            }
        }
        public async Task <TestCaseResponce> DeleteAsync(int id)
        {
            var existingtestCase = await _testCaseRepository.FindByIdAsync(id);

            if (existingtestCase == null)
            {
                return(new TestCaseResponce("Testcase not found."));
            }

            try
            {
                _testCaseRepository.Remove(existingtestCase);
                await _unitOfWork.CompleteAsync();

                return(new TestCaseResponce(existingtestCase));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                _logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(DeleteAsync), ex);
                return(new TestCaseResponce($"An error occurred when deleting the folder: {ex.Message}"));
            }
        }
Exemple #8
0
        private string Get(string key, string defaultValue = null)
        {
#if DEBUG_DOCKER
            var envVar = GetEnvVar(key);
            var config = GetConfig(key);
            var docker = GetDockerSecret(key);
            var rval   = envVar ?? config ?? docker ?? defaultValue;
            _logger?.LogCritical($"'{rval}' = Get('{key}') => env:'{envVar ?? "<null>"}' ?? cfg:'{config ?? "<null>"}' ?? docker:'{docker ?? "<null>"}' ?? def:'{defaultValue ?? "<null>"}'");

            return(rval);
#else
            return(GetEnvVar(key) ?? GetConfig(key) ?? GetDockerSecret(key) ?? defaultValue);
#endif
        }
Exemple #9
0
 private void StartAsync()
 {
     foreach (var message in _messageQueue.GetConsumingEnumerable())
     {
         try
         {
             _mlogClient.RegisterEvent(message);
         }
         catch (Exception ex)
         {
             _errorLogger?.LogCritical(ex, "Error on sending logs to MLog");
         }
     }
 }
        public void DoSomething(string theParam)
        {
            _logger?.LogInformation($"DoSomething with {theParam}");

            Thread.Sleep(1000);

            // Test logs at each level
            _logger?.LogTrace("DoSometing TRACE message");
            _logger?.LogDebug("DoSometing DEBUG message");
            _logger?.LogInformation("DoSometing INFO message");
            _logger?.LogWarning("DoSometing WARN message");
            _logger?.LogError("DoSometing ERROR message");
            _logger?.LogCritical("DoSometing CRITICAL message");
        }
Exemple #11
0
        private void Initialize()
        {
            Header = ReadHeader();
            _logger?.LogDebug("File seed: {fileSeed}", Header.Seed);
            _logger?.LogDebug("File version: {version}", Header.Version);

            if (Header.Version < 2 || Header.Version > 5)
            {
                _logger?.LogCritical("Unsupported version: {version}", Header.Version);
                throw new NotSupportedException("Unsupported version");
            }

            Endian = GetEndian(Header.Version);
        }
        public IActionResult Authenticate([FromBody] UserViewModel userViewModel)
        {
            _logger?.LogDebug("'{0}' has been invoked", MethodBase.GetCurrentMethod().DeclaringType);

            var response = new UserViewModel();

            try
            {
                _logger?.LogInformation("{0} has been retrieved successfully.", MethodBase.GetCurrentMethod().Name);

                var serviceResponse = _userService.AuthenticateAsync(userViewModel.Username, userViewModel.Password.Encrypt()).Result;

                if (serviceResponse == null)
                {
                    return(BadRequest(new { message = "Username or password is incorrect" }));
                }

                // authentication successful so generate jwt token
                var tokenHandler = new JwtSecurityTokenHandler();

                var key = Encoding.ASCII.GetBytes(_appSettings.Value.Secret);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, serviceResponse.UniqueId.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };

                var jwtToken = tokenHandler.CreateToken(tokenDescriptor);
                serviceResponse.Token = tokenHandler.WriteToken(jwtToken);

                response = _mapper.Map <UserViewModel>(serviceResponse);
            }
            catch (Exception ex)
            {
                _logger?.LogCritical("There was an error on '{0}' invocation: {1}", MethodBase.GetCurrentMethod().DeclaringType, ex);

                response = new UserViewModel {
                    ErrorMessage = new string[] { ex.Message }
                };

                return(Ok(response));
            }

            return(Ok(response));
        }
Exemple #13
0
        public async Task Invoke(HttpContext httpContext,
                                 AppDataConnection dataConnection,
                                 IHostApplicationLifetime appLifetime,
                                 ILogger <FirstRunMiddleware> logger)
        {
            var initFlag = AppDomain.CurrentDomain.GetData(Token);

            if (initFlag is not null)
            {
                if ((bool)initFlag)
                {
                    await _next(httpContext);

                    return;
                }
            }

            if (!dataConnection.TestDatabaseConnection(exception =>
            {
                logger?.LogCritical(exception, $"Error {nameof(dataConnection.TestDatabaseConnection)}, connection string: {dataConnection.ConnectionString}");
            }))
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await httpContext.Response.WriteAsync("Database connection failed. Please see error log, fix it and RESTART this application.");

                appLifetime?.StopApplication();
            }
            else
            {
                if (dataConnection.IsFirstRun())
                {
                    try
                    {
                        dataConnection.SetupDatabase();
                    }
                    catch (Exception e)
                    {
                        logger.LogCritical(e, e.Message);
                        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        await httpContext.Response.WriteAsync("Error initializing first run, please check error log.");

                        appLifetime?.StopApplication();
                    }
                }

                AppDomain.CurrentDomain.SetData(Token, true);
                await _next(httpContext);
            }
        }
Exemple #14
0
        public void AddFailure(FailureRequest req)
        {
            var state = disabledProviders.FirstOrDefault(e => e.Name == req.ProviderName);

            if (state != null)
            {
                _logger?.LogInformation($"Tried to add additional failure to {Entity.Current.EntityKey} that is already disabled.");
                return;
            }
            // Counter  because the key will be already exist in the dictionary
            if (FailureWindow.TryGetValue(req.ProviderName, out var list))
            {
                list.Add(req);
            }
            else
            {
                FailureWindow.Add(req.ProviderName, new List <FailureRequest> {
                    req
                });
            }
            var timeWindow = TimeSpan.FromSeconds(_configOptions.Value.EmailProvidersSettings.TimeWindowInSeconds);
            var threshold  = _configOptions.Value.EmailProvidersSettings.Threshold;


            var cutoff = req.HappenedAt.Subtract(timeWindow);

            // Filter the window only to exceptions within the cutoff timespan
            FailureWindow[req.ProviderName].RemoveAll(p => p.HappenedAt < cutoff);

            // get Items to delete or postpone

            var entityKey = Entity.Current?.EntityKey ?? "";

            if (FailureWindow[req.ProviderName].Count >= threshold)
            {
                _logger?.LogCritical($"{entityKey} Stop using email provider {req.ProviderName} because it exceeded the threshold {threshold}. Number of failure is {FailureWindow[req.ProviderName].Count}");

                emailProviders.Remove(req.ProviderName);
                var disablePeriod = _configOptions.Value.EmailProvidersSettings.DisablePeriod;
                var period        = DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(disablePeriod));
                disabledProviders.Add(new DisabledEmailProviderItem {
                    Name = req.ProviderName, DueTime = period
                });
            }
            else
            {
                _logger?.LogInformation($"{entityKey} New failure occurred for provider {req.ProviderName} but it didn't reach the threshold in the timewindow yet.");
            }
        }
Exemple #15
0
        public async Task <string> RenderToStringAsync([NotNull] string viewWebPath, object model)
        {
            var httpContext = new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            using (var sw = new StringWriter())
            {
                try
                {
                    var absPath  = _webPathTranslator.ToFileSystemPath("~/");
                    var viewPath = _webPathTranslator.ToFileSystemPath(viewWebPath);
                    var vv       = viewWebPath.Replace("~", "");

                    var vResult = _razorViewEngine.GetView(absPath, vv, false);



                    if (vResult.View == null)
                    {
                        throw new ArgumentNullException($"{vv} does not match any available view");
                    }

                    var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                    {
                        Model = model
                    };

                    var viewContext = new ViewContext(
                        actionContext,
                        vResult.View,
                        viewDictionary,
                        new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                        sw,
                        new HtmlHelperOptions()
                        );

                    await vResult.View.RenderAsync(viewContext);

                    return(sw.ToString());
                }
                catch (Exception e)
                {
                    _logger?.LogCritical(e, $"Unable to render view '{viewWebPath}': {e.Message}");
                    throw;
                }
            }
        }
Exemple #16
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            if (!optionsBuilder.IsConfigured)
            {
                // devenv$ docker run -d --name pg -p 5432:5432 --restart always postgres:alpine

                var cfg = _settingsProvider;
                LogSql = LogSql ?? cfg.LogSql;

                var cb     = new NpgsqlConnectionStringBuilder(cfg.PgConnectionString);
                var pgHost = cfg.PgHost;
                if (pgHost != null)
                {
                    var ips = Dns.GetHostAddresses(pgHost);
#if DEBUG_DOCKER
                    _logger?.LogCritical($"Resolving: {pgHost} -> {string.Join(", ", ips.Select(i => i.ToString()))}");
#endif
                    if (ips.Any())
                    {
                        pgHost = ips.First().ToString();
                    }
                    cb.Host = pgHost;
                }
                var connStr = cb.ToString();
                optionsBuilder.UseNpgsql(connStr);
                if (LogSql ?? cfg.LogSql)
                {
                    optionsBuilder.UseLoggerFactory(new ConsoleLoggerFactory());
                    optionsBuilder.EnableSensitiveDataLogging();
#if DEBUG_DOCKER
                    _logger?.LogCritical($"connectionString: {connStr}");
#endif
                }
            }
        }
        public async Task <IActionResult> GetStockItemsAsync(int pageSize = 10, int pageNumber       = 1, int?lastEditedBy  = null,
                                                             int?colorID  = null, int?outerPackageID = null, int?supplierID = null, int?unitPackageID = null)
        {
            Logger?.LogDebug("'{0}' foi chamada", nameof(GetStockItemsAsync));

            var response = new PagedResponse <StockItem>();

            try
            {
                // Get da query "proposta" do repositório
                var query = _context.GetStockItems();

                // Seta o valor das páginas
                response.PageSize   = pageSize;
                response.PageNumber = pageNumber;

                // Get o total de linhas
                response.ItemsCount = await query.CountAsync();

                // Get a página expecífica do banco
                response.Model = await query.Paging(pageSize, pageNumber).ToListAsync();

                response.Message = string.Format("Página {0} de {1}, Total de produtos: {2}.", pageNumber, response.PageCount, response.ItemsCount);

                Logger?.LogInformation("Os itens foram trazidos com sucesso.");
            }
            catch (Exception ex)
            {
                response.DidError     = true;
                response.ErrorMessage = "Houve um erro interno, por favor contate o suporte.";

                Logger?.LogCritical("Houve um erro na chamada '{0}' invocando: {1} ", nameof(GetStockItemsAsync), ex);
            }

            return(response.ToHttpResponse());
        }
        public async Task <IActionResult> AddCartItem(string id, int itemId)
        {
            _logger?.LogTrace("Add Item {itemId} to cart {id}", itemId, id);
            var cart = await DbContext.Carts
                       .Include(g => g.CartItems)
                       .FirstOrDefaultAsync(c => c.CartId == id);

            if (cart == null)
            {
                _logger?.LogCritical("Cart not found!");
                return(NotFound());
            }

            var cartItem = cart.CartItems.SingleOrDefault(item => item.ItemKey == itemId);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new CartItem
                {
                    ItemKey     = itemId,
                    CartId      = id,
                    Count       = 1,
                    DateCreated = DateTime.Now
                };

                cart.CartItems.Add(cartItem);
            }
            else
            {
                cartItem.Count++;
            }
            await DbContext.SaveChangesAsync();

            return(Ok());
        }
Exemple #19
0
        public static void SetError(this IResponse response, ILogger logger, string name, Exception ex)
        {
            response.DidError = true;

            if (ex is ApiException cast)
            {
                response.ErrorMessage = ex.Message;
            }
            else
            {
                response.ErrorMessage = "There was an internal error, please contact to technical support.";
            }

            logger?.LogCritical("There was an error on '{0}': {1}", name, ex);
        }
        public async Task <IActionResult> EnumerateAsync(string domain_name)
        {
            _logger?.LogDebug("'{0}' has been invoked.", nameof(EnumerateAsync));

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                EnumerateResponse response = await _subdomainService.EnumerateAsync(domain_name);

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(EnumerateAsync), ex);

                return(StatusCode(StatusCodes.Status500InternalServerError, new IpAddressesResponse {
                    ErrorMessage = ex.Message
                }));
            }
        }
Exemple #21
0
        public StoresController(IStoreService storeService, IMapper mapper, IOptions <AppSettings> appSettings, ILoggerFactory loggerFactory)
        {
            try
            {
                _storeService = storeService;

                _mapper      = mapper;
                _appSettings = appSettings?.Value;
                _logger      = loggerFactory.CreateLogger(typeof(UsersController));
            }
            catch (Exception ex)
            {
                _logger?.LogCritical($"{ex}");
            }
        }
        public static void SetError(this IResponse response, Exception ex, ILogger logger)
        {
            response.DidError = true;

            if (ex is BlogException blogEx)
            {
                logger?.LogCritical(blogEx.ToString());
                response.ErrorMessage = "There was an internal error.";
            }
            else
            {
                logger?.LogError(ex.Message);
                response.ErrorMessage = ex.Message;
            }
        }
Exemple #23
0
        /// <summary>
        /// Expects CF_INSTANCE_CERT and CF_INSTANCE_KEY to be set in the environment (automatically set by DIEGO in cloud foundry)
        /// </summary>
        /// <param name="credHubOptions">CredHub client configuration values</param>
        /// <param name="logger">Pass in a logger if you want logs</param>
        /// <param name="httpClient">Optionally override the http client used to talk to credhub - added for tests only</param>
        /// <returns>An initialized CredHub client (using mTLS)</returns>
        public static async Task <CredHubClient> CreateMTLSClientAsync(CredHubOptions credHubOptions, ILogger logger = null, HttpClient httpClient = null)
        {
            _logger         = logger;
            _baseCredHubUrl = credHubOptions.CredHubUrl;

            var cfInstanceCert = Environment.GetEnvironmentVariable("CF_INSTANCE_CERT") ?? string.Empty;
            var cfInstanceKey  = Environment.GetEnvironmentVariable("CF_INSTANCE_KEY");

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && cfInstanceCert.StartsWith("/"))
            {
                _logger?.LogTrace("Detected Windows OS and root-relative paths for application credentials: converting to app-relative paths");
                cfInstanceCert = ".." + cfInstanceCert;
                cfInstanceKey  = ".." + cfInstanceKey;
            }

            if (string.IsNullOrEmpty(cfInstanceCert) || string.IsNullOrEmpty(cfInstanceKey))
            {
                _logger?.LogCritical("Cloud Foundry application credentials not found in the environment");
                throw new ArgumentException("Application Credentials not found (Missing ENV variable for Instance Cert and/or Key)");
            }

            _logger?.LogTrace("Application certificate: " + cfInstanceCert);
            _logger?.LogTrace("Application key: " + cfInstanceKey);
            if (File.Exists(cfInstanceCert) && File.Exists(cfInstanceKey))
            {
                var client = new CredHubClient(credHubOptions.ValidateCertificates);
                _httpClientHandler = new HttpClientHandler()
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual
                };
                var certBytes      = File.ReadAllBytes(cfInstanceCert);
                var keyBytes       = File.ReadAllBytes(cfInstanceKey);
                var appCredentials = CertificateHelpers.GetX509FromBytes(certBytes, keyBytes);
                if (!appCredentials.HasPrivateKey)
                {
                    throw new Exception("Private key is missing, mTLS won't work");
                }

                _httpClientHandler.ClientCertificates.Add(appCredentials);
                _httpClient = httpClient ?? client.InitializeHttpClient(_httpClientHandler);

                return(await client.InitializeAsync());
            }
            else
            {
                throw new Exception($"Application credentials not found (Failed to load Instance Cert [{cfInstanceCert}] and/or Key [{cfInstanceKey}])");
            }
        }
Exemple #24
0
 public virtual async Task InitializeAsync(CancellationToken cancellationToken = default)
 {
     foreach (var repository in _repositories)
     {
         try
         {
             await InitializeRepositoryAsync(repository, cancellationToken);
         }
         catch (Exception ex)
         {
             //Catch and log this as we don't want issues with external services to prevent app startup
             _log?.LogCritical(ex, "Error initialising MDS client '{0}'", repository.GetType().Name);
         }
     }
     _initialized = true;
 }
Exemple #25
0
        public FileContainer(string filePath, ILogger logger = null)
        {
            FilePath = filePath;
            _logger  = logger;


            if (!File.Exists(FilePath))
            {
                _logger?.LogCritical("File not found: {filePath}.", filePath);
                throw new FileNotFoundException("File not found.", filePath);
            }

            Initialize();

            _decryptor = new Decryptor(Header.Seed);
        }
Exemple #26
0
        public static void Setup(string configFilePath, ILoggerFactory loggerFactory, bool isDevelopment = false)
        {
            logger = loggerFactory?.CreateLogger("ConfigurationManager");
            ConfigurationManager.isDevelopment = isDevelopment;

            if (!File.Exists(configFilePath))
            {
                var ex = new ArgumentException($"The config file not exists in path: {configFilePath}.");
                logger?.LogCritical(new EventId(), ex, "Reload config file failed.");
                throw ex;
            }

            WatchConfigFile(configFilePath);

            Load(configFilePath);
        }
Exemple #27
0
        public async Task <IActionResult> Index()
        {
            //throw new Exception("No pasaran!");

            _logger?.LogInformation("index action requested");
            _logger?.LogTrace("trace! winter is coming!");
            _logger?.LogInformation("info! winter is coming!");
            _logger?.LogWarning("warning! winter is coming!");
            _logger?.LogDebug("debug! winter is coming!");
            _logger?.LogError("error! winter is coming!");
            _logger?.LogCritical("critical! winter is coming!");

            var values = await _valueService.GetAsync();

            return(View(values));
        }
Exemple #28
0
        public static async Task <SiteInfo> GetSiteInfo(this HttpContext context)
        {
            var services = context.RequestServices;
            var session  = new SiteInfo();

            session.UserAgent = context.Request.Headers["User-Agent"];

            // very paranoid version to be sure no error escape this code - required until geoloc error has not been not found
            string  ipList = "";   // only for debug
            string  fwdfor = "";
            ILogger logger = null; // only for debug,

            try
            {
                var geoLoc = services.GetService <ICreyService <GeoLocationQuery> >();
                logger = context.RequestServices.GetRequiredService <ILogger <SiteInfo> >();
                IEnumerable <IPAddress> ipAddresses = context.GetRemoteIPAddresses();
                ipList = string.Join(",", ipAddresses.Select(x => x.ToString()));
                if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
                {
                    fwdfor = context.Request.Headers["X-Forwarded-For"];
                }

                if (!ipAddresses.Any())
                {
                    session.Country = "";
                    session.Ip      = "";
                    logger?.LogWarning($"geo location was unable to get infor for: [{fwdfor}] [{ipList}]");
                }
                else
                {
                    var ip  = ipAddresses.First();
                    var loc = await geoLoc.Value.GetLocation(ip);

                    session.Country = loc.CountryCode;
                    session.Ip      = loc.YourIp;
                }
            }
            catch (Exception ex)
            {
                session.Country = "";
                session.Ip      = "";
                logger?.LogCritical(ex, $"geo location is still not working: [{fwdfor}] [{ipList}]");
            }

            return(session);
        }
Exemple #29
0
        public static void SetError(this IResponse response, Exception ex, ILogger logger)
        {
            response.DidError = true;

            var cast = ex as StoreException;

            if (cast == null)
            {
                logger?.LogCritical(ex.ToString());
                response.ErrorMessage = "There was an internal error, please contact to technical support.";
            }
            else
            {
                logger?.LogError(ex.Message);
                response.ErrorMessage = ex.Message;
            }
        }
        public static void SetError(this IResponse response, Exception ex, ILogger logger)
        {
            response.IsError = true;

            var cast = ex as FlmException;

            if (cast == null)
            {
                response.ErrorMessage = DefaultErrorMessage;
                logger?.LogCritical(ex.ToString());
            }
            else
            {
                response.ErrorMessage = ex.Message;
                logger?.LogError(ex.Message);
            }
        }
Exemple #31
0
 public ActionResult <List <ClientsModel> > Get()
 {
     try
     {
         List <ClientsModel> clientsModel = _clientService.GetClientDetails();
         return(Ok(clientsModel));
     }
     catch (ArgumentNullException ane)
     {
         return(BadRequest(ane.Message));
     }
     catch (Exception ex)
     {
         _logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(Get), ex);
         return(new StatusCodeResult((int)HttpStatusCode.InternalServerError));
     }
 }
        public HabitService(GetHabitsContext dbContext, IHttpContextAccessor httpContextAccessor, ILoggerFactory loggerFactory, ApplicationHelper appHelper)
        {
            _dbContext = dbContext;
            _httpContext = httpContextAccessor.HttpContext;
            _logger = loggerFactory.CreateLogger<HabitService>();
            _appHelper = appHelper;

            var claimUserId = _httpContext.User.FindFirst(appHelper.TypeClaimUserId);

            if (claimUserId == null)
            {
                _logger.LogCritical("HttpContext doesn't contain UserId claim");
                _userId = Guid.NewGuid().ToString();
            }
            else
            {
                _userId = claimUserId.Value;
            }
        }
 public TestController(ILogger<TestController> logger)
 {
   _logger = logger;
   _logger.LogCritical("Logger: TestController constructor");
 }