public static async Task Main(string[] args)
 {
     try
     {
         await BuildWebHost(args).RunAsync().ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         Logger.Error(ex, LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.EXCEPTION), ex.Message);
     }
 }
Exemple #2
0
 public static void Main()
 {
     try
     {
         BuildWebHost(Array.Empty <string>()).Run();
     }
     catch (Exception ex)
     {
         Logger.Error(ex, LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.EXCEPTION), ex.Message);
     }
 }
Exemple #3
0
        private void OnDataReceived(DataReceivedEventArgs e)
        {
            try
            {
                while (true)
                {
                    if (e.Message.Position >= e.Message.Length)
                    {
                        break;
                    }

                    OnMessageReceived(e.Message.ReadMessage(), e.SendOption);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Exception caught in client data handler.");
                Connection.Send(new Message1DisconnectReason(DisconnectReason.Custom, DisconnectMessages.Error));
            }
        }
 public async Task InvokeAsync(HttpContext httpContext)
 {
     try
     {
         await _next(httpContext);
     }
     catch (Exception ex)
     {
         _logger.Error($"Something went wrong: {ex.Message}");
         await HandleGlobalExceptionAsync(httpContext, ex);
     }
 }
Exemple #5
0
        public IActionResult Error()
        {
            var exceptionFeature = this.HttpContext.Features.Get <IExceptionHandlerPathFeature>();

            if (exceptionFeature != null)
            {
                _logger.Error(exceptionFeature.Error, $"ERROR IN MVC CAUGHT for user {this.User?.Identity?.Name}");
            }
            return(View(new ErrorViewModel {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            }));
        }
Exemple #6
0
        public IActionResult Authentication([FromBody] LoginInfo loginInfo)
        {
            try
            {
                TokenInfo tokenInfo = new TokenInfo();

                var apiUserInfo = this.apikeyValidService.Validate(loginInfo.APIKey);


                logger.Debug("apiUserInfo : {apiUserInfo}", JsonConvert.SerializeObject(apiUserInfo));

                if (apiUserInfo == null)
                {
                    return(NotFound("유효한 apiKey가 아닙니다."));
                }

                var user = this.loginService.Login(loginInfo.Id, loginInfo.Password);

                logger.Debug("user : {@user}", JsonConvert.SerializeObject(user));

                if (user == null)
                {
                    return(NotFound("아이디 또는 패스워드가 올바르지 않습니다."));
                }

                tokenInfo = this.tokenService.GetToken(user, apiUserInfo);

                if (tokenInfo == null)
                {
                    return(NotFound("토큰 발급에 실패했습니다."));
                }

                return(Ok(tokenInfo));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "인증에 실패했습니다.");
                return(NotFound("인증에 실패했습니다."));
            }
        }
 public virtual void DiscardChanges()
 {
     try
     {
         foreach (var contextManager in this.contextList)
         {
             if (contextManager.HasContext)
             {
                 contextManager.Context.Dispose();
             }
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message, ex);
         throw;
     }
 }
Exemple #8
0
        public SextantHost(string basePath, string pluginName, bool configureLogging = true)
        {
            _pluginName = pluginName;
            if (configureLogging)
            {
                InitializeLogging();
            }
            else
            {
                _logger = Log.Logger;
            }


            try
            {
                new Bootstrapper().Bootstrap(basePath, container);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Exception during bootstrapping");
            }
        }
        public void LogException(Exception exception, ExceptionSeverity severity)
        {
            switch (severity)
            {
            case ExceptionSeverity.Severe:
                serilogLogger.Fatal(exception, string.Empty);
                break;

            default:
                serilogLogger.Error(exception, string.Empty);
                break;
            }
        }
Exemple #10
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var files = Directory.EnumerateFiles(directorioSensores, "*.txt");

                    foreach (string file in files)
                    {
                        var fileName = new FileInfo(file).Name;

                        string payload = GetData(fileName);
                        if (!string.IsNullOrEmpty(payload))
                        {
                            var result = client.Post(payload);

                            if (result.StatusCode.ToString() == "Changed")
                            {
                                _logger.Information($"WORKER (ExecuteAsync) - La informacion del fichero {fileName} se ha insertado correctamente");

                                File.Delete(file); //elimina el fichero
                            }
                            else
                            {
                                _logger.Error($"ERR. WORKER (ExecuteAsync) - No se ha podido insertar la información del fichero {fileName}");
                                File.Delete(file); //elimina el fichero
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"ERR WORKER (ExecuteAsync) - {ex.Message}");
                }

                await Task.Delay(tiempoEnvio * 1000, stoppingToken);
            }
        }
        private void TraceAsync(HttpContext context, Exception ex)
        {
            var body = context.Items["body"].ToString();

            //TODO: Save log to chosen datastore
            var trace         = JsonConvert.SerializeObject(ex);;
            var cai           = context.Items["unique"].ToString();
            var elapsedMs     = 34;
            var requestId     = context.Items["id"].ToString();
            var requestPath   = context.Request.Path.ToString();
            var requestScheme = $"{context.Request.Scheme} {context.Request.Host}{context.Request.Path} {context.Request.QueryString} {body}";

            Logg.Error("Executed {@requestId} {@requestPath} {@requestScheme} {@trace} in {Elapsed:000} ms. by {unique} {type}",
                       requestId, requestPath, requestScheme, trace, elapsedMs, cai, EFLogType.EXCEPTION.GetDescription());
        }
Exemple #12
0
        protected override void DoPost(CoapExchange exchange)
        {
            string payload = exchange.Request.PayloadString;

            if (payload != null)
            {
                try
                {
                    EntidadPeticionSegura peticionSegura = JsonConvert.DeserializeObject <EntidadPeticionSegura>(payload);  //Deserializamos la peticion en un objeto de tipo json
                    EntidadPeticion       peticion       = servicioSeguridad.ToEntidadPeticion(peticionSegura);

                    var insercion = Task.Run(async() => await servicioInsertaInformacion.InsertaPeticion(peticion));    //Lanzamos la peticion para que inserte los datos de forma asincrona

                    if (insercion.Result)
                    {
                        //log.Information($"Datos insertados: {peticion.Proyecto}-{peticion.EstacionBase}-{peticion.Sensor} ({peticion.Datos.Count()})");
                        exchange.Respond(CoAP.StatusCode.Changed);
                    }
                    else
                    {
                        log.Error("ERR RECURSOPETICION (DoPost) - No se ha podido insertar la información en la base de datos.");
                        exchange.Respond(CoAP.StatusCode.BadRequest);
                    }
                }
                catch (Exception ex)
                {
                    log.Error($"ERR RECURSOPETICION (DoPost) - {ex.Message}");
                    exchange.Respond(CoAP.StatusCode.BadRequest);
                }
            }
            else
            {
                log.Error("ERR RECURSOPETICION (DoPost) - La petición está vacía.");
                exchange.Respond(CoAP.StatusCode.BadRequest);
            }
        }
        public void Log(LogType logType, string text)
        {
            switch (logType)
            {
            case LogType.Error:
                serilogLogger.Error(text);
                break;

            case LogType.Information:
                serilogLogger.Information(text);
                break;

            default:
                throw new InvalidOperationException("Not such log type.");
            }
        }
        public static Action <IApplicationBuilder> HandleApiException(Serilog.ILogger logger)
        {
            return(appBuilder =>
            {
                appBuilder.Run(async context =>
                {
                    var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>();
                    if (exceptionHandlerFeature != null)
                    {
                        logger.Error(exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message + '\n');
                    }

                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
                });
            });
        }
Exemple #15
0
 public static async Task <IActionResult> HandleQuery <TModel>(
     Func <Task <TModel> > query, Serilog.ILogger log)
 {
     try
     {
         return(new OkObjectResult(await query()));
     }
     catch (Exception e)
     {
         log.Error(e, "Error handling the query");
         return(new BadRequestObjectResult(new
         {
             error = e.Message,
             stackTrace = e.StackTrace
         }));
     }
 }
Exemple #16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            Serilog.Log.Information($"Configuring: {env.ApplicationName} for env {env.EnvironmentName}");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.Use(async(context, next) =>
                {
                    try
                    {
                        await next();
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, $"Error while handleing {context?.Request?.Path}");
                        throw;
                    }
                });
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMiddleware <JwtWithCookieAuthMiddleware>();
            app.UseAuthentication();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v0/swagger.json", "orion-timetracking.api");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #17
0
 private async Task RedirectStreamUntilServerExits()
 {
     try
     {
         using (StreamWriter writer = new StreamWriter(new FileStream(LanguageServerConfig.RedirectedStreamFile,
                                                                      FileMode.OpenOrCreate, FileAccess.Write)))
         {
             Console.SetOut(writer);
             await server.WaitForExit;
         }
     }
     catch (Exception e)
     {
         string msg = Resources.LoggingMessages.could_not_redirect_outputstream + e.Message;
         msgSender.SendError(msg);
         log.Error(msg);
     }
 }
Exemple #18
0
        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exceptionToCodeMap.TryGetValue(exception.GetType(), out var code) == false)
            {
                code = HttpStatusCode.InternalServerError;
            }

            logger.Error(exception, $"Request {context.Request.Path} execution failed");

#if DEBUG
            var result = JsonConvert.SerializeObject(new { error = exception.Message });
#else
            var result = JsonConvert.SerializeObject(new { error = "Unexpected Error" });
#endif
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }
Exemple #19
0
        private async Task LogErrorExceptionWithRequestBody(HttpContext context, Exception exception)
        {
            context.Request.EnableBuffering();
            context.Request.Body.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(context.Request.Body))
            {
                var body = await reader.ReadToEndAsync();

                _logger.Error(
                    exception,
                    $"WebApi exception, Method: {{method}}, Content: {{faultMessage}}",
                    $"{context.Request.Method} {context.Request.GetDisplayUrl()}",
                    JsonConvert.SerializeObject(body));

                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }
        }
        protected internal virtual async void SendReminder(EventTaskAssignmentModel eventTaskAssignment)
        {
            var guild        = _client.GetGuild(eventTaskAssignment.Id);
            var reminderType = (ReminderTypes)eventTaskAssignment.AssignmentType;
            var logChannelId = GetReminderChannelForType(guild, reminderType);

            if (logChannelId == null)
            {
                //Check if the guild has that type of channel set
                ReminderServiceLog.Error($"Could not send reminder. {guild.Name} is likely missing a {reminderType} reminder channel");
            }
            else
            {
                //Send the reminder
                var reminderChannel = (IMessageChannel)_client.GetChannel((ulong)logChannelId);
                await reminderChannel.SendMessageAsync(eventTaskAssignment.ReminderText);
            }
        }
Exemple #21
0
        public static void Main()
        {
            var host = BuildWebHost(null);

            //// ReSharper disable PossibleNullReferenceException
            (host.ServerFeatures[typeof(IServerAddressesFeature)] as IServerAddressesFeature).Addresses.Add(
                (host.Services.GetService(typeof(IServerAddressesFeature)) as IServerAddressesFeature)?.Addresses
                .First());
            //// ReSharper enable PossibleNullReferenceException
            try
            {
                host.Run();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.EXCEPTION), ex.Message);
            }
        }
Exemple #22
0
        public async Task Handle(ResolvedEvent resolvedEvent)
        {
            var streamVersion = resolvedEvent.OriginalEventNumber;
            var @event        = DeserializeEvent(resolvedEvent.Event);

            try
            {
                _log.Information($"Handle event {@event.GetType().Name}:{@event.EventId}. Stream version: {streamVersion}");

                await HandleInternal(@event, streamVersion);

                _log.Information($"Event {@event.GetType().Name}:{@event.EventId} handled");
            }
            catch (Exception ex)
            {
                _log.Error(ex, $"Event {@event.GetType().Name}:{@event.EventId} handling error");
            }
        }
 //To Delete Category Item
 public async Task <bool> DeleteUrlApiHealthCheck(int id)
 {
     try
     {
         using (SystemHealthChecksDbContext shc = new SystemHealthChecksDbContext())
         {
             _logger.Information($"we called {nameof(DeleteUrlApiHealthCheck)} with {nameof(id)}: {id}");
             UrlApiHealthCheck urlApibHealthCheck = shc.UrlApiHealthCheck.Find(id);
             shc.UrlApiHealthCheck.Remove(urlApibHealthCheck);
             return(await Task.FromResult((shc.SaveChanges() > 0 ? true : false)));
         }
     }
     catch (Exception ex)
     {
         _logger.Error(nameof(DeleteUrlApiHealthCheck), ex.ToString());
         return(false);
     }
 }
        private void OnDataReceived(DataReceivedEventArgs e)
        {
            try
            {
                while (true)
                {
                    if (e.Message.Position >= e.Message.Length)
                    {
                        break;
                    }

                    OnMessageReceived(e.Message.ReadMessage());
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Exception caught in client data handler.");
            }
        }
        public byte[] ResizeImage(byte[] photoBytes)
        {
            try
            {
                using var outputStream = new MemoryStream();
                using var inputStream  = new MemoryStream(photoBytes);
                using var image        = SixLabors.ImageSharp.Image.Load(inputStream);
                image.Mutate(x => x.Resize(0, 600, KnownResamplers.Lanczos3).DrawText("ApnaBarwachiKhana", font, SixLabors.ImageSharp.Color.White, new SixLabors.ImageSharp.PointF(5, 5)));
                image.Save(outputStream, new JpegEncoder());

                return(outputStream.ToArray());
            }
            catch (Exception ee)
            {
                _logger.Error(ee, "Error Resizing Image");

                return(photoBytes);
            }
        }
Exemple #26
0
        static void Main()
        {
            _configuration = BuildConfiguration();
            _logger        = CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            AssemblyLoadContext.Default.Unloading      += OnShutdown;
            Console.CancelKeyPress += OnCancelKeyPress;

            try
            {
                _logger.Information("Starting Consumer. Press Ctrl+C to exit.");
                _logger.Debug(_configuration.Dump());

                var services = new ServiceCollection().AddHttpClient();

                var container = new Container(config =>
                {
                    config.AddRegistry(new AppRegistry(_configuration, _logger));
                    config.AddRegistry(new QueueingRegistry(_configuration));
                    config.Populate(services);
                });

#if DEBUG
                container.AssertConfigurationIsValid();
#endif

                var actorFactory = container.GetInstance <IActorFactory>();
                var dequeuer     = actorFactory.GetActor <Dequeuer>();
                dequeuer.Tell(new ReceiveCommands());

                _closing.WaitOne();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error starting Consumer.");
            }
            finally
            {
                Serilog.Log.CloseAndFlush();
            }
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            try
            {
                IEnumerable <Tour> popularTours = await tourDAL.GetTrendingToursAsync();

                if (popularTours != null)
                {
                    foreach (Tour tour in popularTours)
                    {
                        tour.Destinations = await tourDAL.FindDestinationsByTourIdAsync(tour.Id);
                    }
                }
                AppUser user = User?.Identity?.Name == null ? null : await userManager.FindByNameAsync(User.Identity.Name);

                string avatar = "https://ztourist.blob.core.windows.net/others/avatar.png";
                if (user != null)
                {
                    avatar = user.Avatar;
                }

                if (cart != null && cart.Lines.Count() > 0)
                {
                    foreach (CartLine cartLine in cart.Lines)
                    {
                        cartLine.Tour = await tourDAL.FindTourByTourIdAsync(cartLine.Tour.Id);
                    }
                }
                NavigationViewModel model = new NavigationViewModel
                {
                    Cart         = cart,
                    PopularTours = popularTours,
                    Avatar       = avatar
                };
                return(View(model));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }
        }
Exemple #28
0
        public static async Task <IActionResult> HandleCommand <T>(
            T request, Func <T, Task> handler, Serilog.ILogger log)
        {
            try
            {
                log.Debug("Handling HTTP request of type {type}", typeof(T).Name);
                await handler(request);

                return(new OkResult());
            }
            catch (Exception e)
            {
                log.Error(e, "Error handling the command");
                return(new BadRequestObjectResult(new
                {
                    error = e.Message,
                    stackTrace = e.StackTrace
                }));
            }
        }
        async Task BroadcastMarketStateChange(MarketState marketState)
        {
            _logger.Debug("[ENTER] [BroadcastMarketStateChange]: new state " + marketState + ", old state: " + MarketState);
            switch (marketState)
            {
            case MarketState.Open:
                await Hub.Clients.All.SendAsync("marketOpened");

                break;

            case MarketState.Closed:
                await Hub.Clients.All.SendAsync("marketClosed");

                break;

            default:
                _logger.Error("[BroadcastMarketStateChange]: Unknown market state: " + marketState);
                throw new Exception("Unknown market state");
            }
        }
Exemple #30
0
        private static async Task HandleServerError(HttpContext context)
        {
            var error = context.Features.Get <IExceptionHandlerFeature>()?.Error;

            if (error == null)
            {
                return;
            }

            var accessControlOriginKey = "Access-Control-Allow-Origin";

            (var errorMessage, var statusCode) = GetErrorMessageAndStatusCode(error);
            var response = new ErrorResponse
            {
                Message = errorMessage,
            };

            _logger.Error(error, error.Message);

            context.Response.ContentType = "application/json; charset=utf-8";
            context.Response.StatusCode  = (int)statusCode;

            if (!context.Response.Headers.ContainsKey(accessControlOriginKey))
            {
                context.Response.Headers.Append(accessControlOriginKey, "*");
            }

            if (_sendErrorDetails)
            {
                response.Data                  = error.Data;
                response.StackTrace            = error.StackTrace;
                response.InnerExceptionMessage = error.InnerException != null?error.GetBaseException().Message : null;
            }

            else if (error is ValidationException)
            {
                response.Data = error.Data;
            }

            await context.Response.WriteAsync(response.ToJson(true)).ConfigureAwait(false);
        }