Manarah/Manarah.App/Services/ServerService.cs

61 lines
1.8 KiB
C#
Raw Normal View History

using Manarah.App.Data;
using Manarah.Domain;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.EntityFrameworkCore;
using System.Net.NetworkInformation;
namespace Manarah.App.Services
{
public class ServerService : BaseService
{
public ServerService(ManarahContext context) : base(context)
{
}
public void AddServer(Server server)
{
_context.Servers.Add(server);
_context.SaveChanges();
}
public async Task<IEnumerable<ServerDto>> GetServersAsync()
{
var serverList = await _context.Servers.Select(s => new ServerDto
{
IPAddress = s.IPAddress,
Description = s.Description
}).ToListAsync();
using var ping = GetPingInstance();
serverList.ForEach(server =>
{
PingReply reply = ping.Send(server.IPAddress, 500); // Timeout after 500ms
server.IsReachable = reply.Status == IPStatus.Success;
});
return serverList;
}
public async Task<IEnumerable<ServerAggregationDto>> GetServersDashboardAsync()
{
var ping = GetPingInstance();
var serverList = await _context.Servers.Select(s => s.IPAddress).ToListAsync();
List<ServerAggregationDto> serverAggregations = new();
serverList.ForEach(server =>
{
PingReply reply = ping.Send(server, 500); // Timeout after 500ms
serverAggregations.Add(new ServerAggregationDto
{
IsReachable= reply.Status == IPStatus.Success,
});
});
return serverAggregations;
}
Ping GetPingInstance()
{
return new Ping();
}
}
}