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 ShutdownMachineHandler : IRequestHandler { private readonly ILogger _logger; private readonly IShutdownService _shutdownService; public ShutdownMachineHandler(ILogger logger, IShutdownService shutdownService) { _logger = logger; _shutdownService = shutdownService; } public async Task Handle(ShutdownMachine command, CancellationToken cancellationToken) { return await Task.Run(() => Handle(command)); } private MachineShutdown Handle(ShutdownMachine command) { try { _logger.LogDebug($"Start shutting down '{command.IPAddressOrMachineName}'."); var status = _shutdownService.ShutdownMachine(command.IPAddressOrMachineName); _logger.LogDebug($"Shutting down machine '{command.IPAddressOrMachineName}' finished. Status: {status}"); return new MachineShutdown(true, status); } catch (Exception ex) { var correlationIdMsg = $"CorrelationId: {command.Metadata.CorrelationId}"; _logger.LogError(ex, $"An unexpected error has occurred. {correlationIdMsg}"); return new MachineShutdown(false, $"{ex.Message} {correlationIdMsg}"); } } } }