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

46 lines
1.7 KiB
C#
Raw Normal View History

2020-11-28 20:06:43 +02:00
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<ShutdownMachine, MachineShutdown>
{
private readonly ILogger<ShutdownMachineHandler> _logger;
private readonly IShutdownService _shutdownService;
public ShutdownMachineHandler(ILogger<ShutdownMachineHandler> logger, IShutdownService shutdownService)
{
_logger = logger;
_shutdownService = shutdownService;
}
public async Task<MachineShutdown> 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}");
}
}
}
}