network-resurrector/NetworkResurrector.Application/CommandHandlers/PingMachineHandler.cs

41 lines
1.5 KiB
C#

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<PingMachine, MachinePinged>
{
private readonly ILogger<PingMachineHandler> _logger;
private readonly IPingService _pingService;
public PingMachineHandler(ILogger<PingMachineHandler> logger, IPingService pingService)
{
_logger = logger;
_pingService = pingService;
}
public async Task<MachinePinged> Handle(PingMachine command, CancellationToken cancellationToken)
{
try
{
_logger.LogDebug($"Start pinging '{command.IPAddressOrMachineName}'.");
var (success, status) = await _pingService.PingMachine(command.IPAddressOrMachineName);
_logger.LogDebug($"Pinging on '{command.IPAddressOrMachineName}' 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}");
}
}
}
}