using MediatR; using Microsoft.Extensions.Logging; using NetworkResurrector.Application.Commands; using NetworkResurrector.Application.Events; using NetworkResurrector.Application.Services; using System; using System.Threading; using System.Threading.Tasks; namespace NetworkResurrector.Application.CommandHandlers { public class PingMachineHandler : IRequestHandler { private readonly ILogger _logger; private readonly IPingService _pingService; public PingMachineHandler(ILogger logger, IPingService pingService) { _logger = logger; _pingService = pingService; } public async Task Handle(PingMachine command, CancellationToken cancellationToken) { try { _logger.LogDebug($"Start pinging '{command.IPAddress}'."); var (success, status) = await _pingService.PingMachine(command.IPAddress); _logger.LogDebug($"Pinging on '{command.IPAddress}' finished. Status: {status}"); return new MachinePinged(success, status); } catch (Exception ex) { var correlationIdMsg = $"CorrelationId: {command.Metadata.CorrelationId}"; _logger.LogError(ex, $"An unexpected error has occurred. {correlationIdMsg}"); return new MachinePinged(false, $"{ex.Message} {correlationIdMsg}"); } } } }