Fix UCSSystem status change

This commit is contained in:
Martijn Scheepers
2025-11-05 15:09:48 +01:00
parent b786455bbf
commit 5cbcc6d08f
12 changed files with 1156 additions and 164 deletions

View File

@@ -11,6 +11,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Models.Database;
using static Microsoft.ApplicationInsights.MetricDimensionNames.TelemetryContext;
namespace UCS_Status_Monitor.UnitTest.Monitor
@@ -44,6 +45,27 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
// .Build();
public static IDbContextFactory<MonitorDbContext> CreateDataBaseFactory()
{
//Runs before each test. (Optional)
Guid jitter = Guid.NewGuid();
DbContextOptions<MonitorDbContext> dbOptions = new DbContextOptionsBuilder<MonitorDbContext>()
.UseInMemoryDatabase(databaseName: $"TestDb{jitter}")
.Options;
Mock<IDbContextFactory<MonitorDbContext>> mockDbFactory = new();
mockDbFactory.Setup(f => f.CreateDbContext())
.Returns(() => new MonitorDbContext(dbOptions));
mockDbFactory.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(() => new MonitorDbContext(dbOptions));
SeedDatabase(mockDbFactory.Object.CreateDbContext());
return mockDbFactory.Object;
}
[TestInitialize]
public void Setup()
@@ -99,10 +121,28 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
private static void SeedDatabase(MonitorDbContext dbContext)
{
dbContext.UCSSystems.Add(new Models.Database.UCSSystem()
UCSSystem system = new()
{
ComputerName = "Test",
ConfigFileName = "TestConfig",
};
dbContext.UCSSystems.Add(system);
dbContext.Errors.Add(new EventLogError()
{
Index = 42,
Message = "Database Error",
TimeGenerated = new(0),
UCSSystem = system,
});
dbContext.UCSDevices.Add(new UCSDevice()
{
BoxID = "Device ID 1",
Name = "Device 1",
State = true,
Message = "OK",
UCSSystem = system
});
//dbContext.Devices.Add(new Device()

View File

@@ -1,6 +1,10 @@
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Models.Database;
using UCS_Status_Monitor.Monitor;
using UCS_Status_Monitor.Telemetry;
@@ -9,6 +13,8 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
[TestClass]
public class UCSSystemMonitorDevice_Test : MonitorTestSetup
{
public TestContext TestContext { get; set; }
[TestMethod]
public void UCSSystemMonitorDevice_Constructor_Test()
{
@@ -36,7 +42,7 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
ucsDevice.DeviceName = "Test";
using MonitorDbContext db = _dbContextFactory.CreateDbContext();
ucsDevice.SetConnectionState(true, db, default).Wait();
ucsDevice.SetConnectionState(true, db, default).Wait(TestContext.CancellationToken);
Assert.AreEqual("Test", ucsDevice.DeviceName);
Assert.AreEqual("", ucsDevice.Location);
@@ -68,7 +74,7 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
ConfigFileName = "New Config File"
};
ucsDevice.Update(packet, db, default).Wait();
ucsDevice.Update(packet, db, default).Wait(TestContext.CancellationToken);
Assert.AreEqual("New Test", ucsDevice.DeviceName);
Assert.AreEqual("", ucsDevice.Location);
@@ -98,7 +104,7 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
StartTime = "14-10-2025 08:52:00"
};
ucsDevice.Update(packet, db, default).Wait();
ucsDevice.Update(packet, db, default).Wait(TestContext.CancellationToken);
Assert.AreEqual("Test", ucsDevice.DeviceName);
Assert.AreEqual("", ucsDevice.Location);
@@ -108,5 +114,223 @@ namespace UCS_Status_Monitor.UnitTest.Monitor
Assert.HasCount(1, _testingTelegramBot.Messages);
Assert.AreEqual("Send - ♻️ <b>Test - TestConfig</b>\r\n UCS restarted", _testingTelegramBot.Messages[0]);
}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_GetUCSSystem_Test()
//{
// IDbContextFactory<MonitorDbContext> dbFactory = CreateDataBaseFactory();
// Assert.IsNotNull(dbFactory);
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystemMonitorDevice ucsDevice = new(5, dbFactory, testingTelegramBot); ;
// Assert.IsNotNull(ucsDevice);
// using MonitorDbContext db = dbFactory.CreateDbContext();
// TelemetryPacket packet = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// StartTime = "14-10-2025 08:52:00"
// };
// UCSSystem ucssystem = await ucsDevice.GetUCSSystem(packet, db, TestContext.CancellationToken);
// Assert.AreEqual("Test", ucssystem.ComputerName);
// Assert.AreEqual("TestConfig", ucssystem.ConfigFileName);
// Assert.HasCount(0, testingTelegramBot.Messages);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_GetUCSSystem_new_Test()
//{
// IDbContextFactory<MonitorDbContext> dbFactory = CreateDataBaseFactory();
// Assert.IsNotNull(dbFactory);
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystemMonitorDevice ucsDevice = new(5, dbFactory, testingTelegramBot); ;
// Assert.IsNotNull(ucsDevice);
// using MonitorDbContext db = dbFactory.CreateDbContext();
// TelemetryPacket packet = new()
// {
// ComputerName = "New Device",
// ConfigFileName = "Config File",
// StartTime = "14-10-2025 08:52:00"
// };
// UCSSystem ucssystem = await ucsDevice.GetUCSSystem(packet, db, TestContext.CancellationToken);
// Assert.AreEqual("New Device", ucssystem.ComputerName);
// Assert.AreEqual("Config File", ucssystem.ConfigFileName);
// Assert.HasCount(1, testingTelegramBot.Messages);
// Assert.AreEqual("SendDeviceAdded - New Device - Config File", testingTelegramBot.Messages[0]);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_null_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// };
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, null, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("No USB disks", system.USBDisks);
// Assert.HasCount(0, testingTelegramBot.Messages);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_empty_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// };
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, [], testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("No USB disks", system.USBDisks);
// Assert.HasCount(0, testingTelegramBot.Messages);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_NoDisk_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// };
// List<string> usbDisks = ["No USB disks"];
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("No USB disks", system.USBDisks);
// Assert.HasCount(0, testingTelegramBot.Messages);
// //Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_NoDiskUpdate_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// USBDisks = "No USB disks"
// };
// List<string> usbDisks = ["No USB disks"];
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("No USB disks", system.USBDisks);
// Assert.HasCount(0, testingTelegramBot.Messages);
// //Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_DiskRemoved_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// USBDisks = "disk 1\r\ndisk 2\r\ndisk 3"
// };
// List<string> usbDisks = ["No USB disks"];
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("No USB disks", system.USBDisks);
// Assert.HasCount(1, testingTelegramBot.Messages);
// Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Adddisks_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// };
// List<string> usbDisks = ["disk 1", "disk 2", "disk 3"];
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("disk 1\r\ndisk 2\r\ndisk 3", system.USBDisks);
// Assert.HasCount(3, testingTelegramBot.Messages);
// Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 1 detected", testingTelegramBot.Messages[0]);
// Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 2 detected", testingTelegramBot.Messages[1]);
// Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 3 detected", testingTelegramBot.Messages[2]);
//}
//[TestMethod]
//public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Update_Test()
//{
// TestingTelegramBot testingTelegramBot = new();
// Assert.IsNotNull(testingTelegramBot);
// UCSSystem? system = new()
// {
// ComputerName = "Test",
// ConfigFileName = "Config File",
// USBDisks = "disk 1\r\ndisk 2\r\ndisk 3"
// };
// List<string> usbDisks = ["disk 1", "disk 2", "disk 3"];
// system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
// Assert.IsNotNull(system);
// Assert.AreEqual("disk 1\r\ndisk 2\r\ndisk 3", system.USBDisks);
// Assert.HasCount(0, testingTelegramBot.Messages);
//}
}
}

View File

@@ -0,0 +1,274 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Models.Database;
using UCS_Status_Monitor.Monitor;
using UCS_Status_Monitor.Telemetry;
namespace UCS_Status_Monitor.UnitTest.Monitor.UCSSystemTest
{
[TestClass]
public class UpdateConnectionStates_Test : MonitorTestSetup
{
public TestContext TestContext { get; set; }
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Null_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, null, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(0, system.Devices);
Assert.HasCount(0, db.UCSDevices);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Empty_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, [], db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(0, system.Devices);
Assert.HasCount(0, db.UCSDevices);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Add_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
List<ConnectionState>? connectionstates = [new() {
ID = "ID42",
Name = "Device 42",
State = true,
Message = "Message 1",
LastStateChange = "now"
}];
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, connectionstates, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, system.Devices);
Assert.HasCount(1, db.UCSDevices);
Assert.AreEqual("ID42", db.UCSDevices.ToList()[0].BoxID);
Assert.AreEqual("Device 42", db.UCSDevices.ToList()[0].Name);
Assert.AreEqual("Message 1", db.UCSDevices.ToList()[0].Message);
Assert.IsTrue(db.UCSDevices.ToList()[0].State);
Assert.HasCount(2, testingTelegramBot.Messages);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n ID42 Device 42 Added", testingTelegramBot.Messages[0]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n Device ID 1 Device 1 Removed", testingTelegramBot.Messages[1]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Offline_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
List<ConnectionState>? connectionstates = [new() {
ID = "Device ID 1",
Name = "Device 1",
State = false,
Message = "OK",
}];
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, connectionstates, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, system.Devices);
Assert.HasCount(1, db.UCSDevices);
Assert.AreEqual("Device ID 1", db.UCSDevices.ToList()[0].BoxID);
Assert.AreEqual("Device 1", db.UCSDevices.ToList()[0].Name);
Assert.AreEqual("OK", db.UCSDevices.ToList()[0].Message);
Assert.IsFalse(db.UCSDevices.ToList()[0].State);
Assert.HasCount(1, testingTelegramBot.Messages);
Assert.AreEqual("Send - ⚠️ <b>Test - TestConfig</b>\r\n Device ID 1 Device 1 Lost Connection", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Online_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
db.UCSDevices.First().State = false;
await db.SaveChangesAsync(TestContext.CancellationToken);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
List<ConnectionState>? connectionstates = [new() {
ID = "Device ID 1",
Name = "Device 1",
State = true,
Message = "OK",
}];
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, connectionstates, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, system.Devices);
Assert.HasCount(1, db.UCSDevices);
Assert.AreEqual("Device ID 1", db.UCSDevices.ToList()[0].BoxID);
Assert.AreEqual("Device 1", db.UCSDevices.ToList()[0].Name);
Assert.AreEqual("OK", db.UCSDevices.ToList()[0].Message);
Assert.IsTrue(db.UCSDevices.ToList()[0].State);
Assert.HasCount(1, testingTelegramBot.Messages);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n Device ID 1 Device 1 Online", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_Double_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
List<ConnectionState>? connectionstates = [new() {
ID = "ID 2",
Name = "Device 2",
State = true,
Message = "OK",
}, new(){
ID = "ID 2",
Name = "Device 2",
State = true,
Message = "OK",
}];
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, connectionstates, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(2, system.Devices);
Assert.HasCount(2, db.UCSDevices);
Assert.AreEqual("ID 2", db.UCSDevices.ToList()[0].BoxID);
Assert.AreEqual("Device 2", db.UCSDevices.ToList()[0].Name);
Assert.AreEqual("OK", db.UCSDevices.ToList()[0].Message);
Assert.IsTrue(db.UCSDevices.ToList()[0].State);
Assert.AreEqual("ID 2", db.UCSDevices.ToList()[1].BoxID);
Assert.AreEqual("Device 2", db.UCSDevices.ToList()[1].Name);
Assert.AreEqual("OK", db.UCSDevices.ToList()[1].Message);
Assert.IsTrue(db.UCSDevices.ToList()[1].State);
Assert.HasCount(3, testingTelegramBot.Messages);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n ID 2 Device 2 Added", testingTelegramBot.Messages[0]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n ID 2 Device 2 Added", testingTelegramBot.Messages[1]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n Device ID 1 Device 1 Removed", testingTelegramBot.Messages[2]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateConnectionStates_DoubleCCTV_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
db.UCSDevices.Add(new UCSDevice()
{
BoxID = "rtsp://10.68.40.2:554/stream/profile0",
Name = "Camera 7",
UCSSystem = system
});
db.UCSDevices.Add(new UCSDevice()
{
BoxID = "rtsp://10.68.40.2:554/stream/profile0",
Name = "Camera 8",
UCSSystem = system
});
db.UCSDevices.Add(new UCSDevice()
{
BoxID = "rtsp://10.68.40.2:554/stream/profile0",
Name = "Camera 2",
UCSSystem = system
});
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.HasCount(4, db.UCSDevices);
List<ConnectionState>? connectionstates = [new() {
ID = "rtsp://10.68.40.2:554/stream/profile0",
Name = "Camera 2",
State = true,
Message = "OK",
}];
system = await UCSSystemMonitorDevice.UpdateConnectionStates(system, connectionstates, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, system.Devices);
Assert.HasCount(1, db.UCSDevices);
Assert.AreEqual("rtsp://10.68.40.2:554/stream/profile0", db.UCSDevices.ToList()[0].BoxID);
Assert.AreEqual("Camera 2", db.UCSDevices.ToList()[0].Name);
Assert.AreEqual("OK", db.UCSDevices.ToList()[0].Message);
Assert.IsTrue(db.UCSDevices.ToList()[0].State);
//Assert.AreEqual("ID 2", db.UCSDevices.ToList()[1].BoxID);
//Assert.AreEqual("Device 2", db.UCSDevices.ToList()[1].Name);
//Assert.AreEqual("OK", db.UCSDevices.ToList()[1].Message);
//Assert.IsTrue(db.UCSDevices.ToList()[1].State);
Assert.HasCount(4, testingTelegramBot.Messages);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n rtsp://10.68.40.2:554/stream/profile0 Camera 2 Online", testingTelegramBot.Messages[0]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n Device ID 1 Device 1 Removed", testingTelegramBot.Messages[1]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n rtsp://10.68.40.2:554/stream/profile0 Camera 7 Removed", testingTelegramBot.Messages[2]);
Assert.AreEqual("Send - ✅ <b>Test - TestConfig</b>\r\n rtsp://10.68.40.2:554/stream/profile0 Camera 8 Removed", testingTelegramBot.Messages[3]);
}
}
}

View File

@@ -0,0 +1,125 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Models.Database;
using UCS_Status_Monitor.Monitor;
using UCS_Status_Monitor.Telemetry;
namespace UCS_Status_Monitor.UnitTest.Monitor.UCSSystemTest
{
[TestClass]
public class UpdateErrors_Test : MonitorTestSetup
{
public TestContext TestContext { get; set; }
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateErrors_Null_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateErrors(system, null, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.IsEmpty(system.Errors);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateErrors_Empty_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateErrors(system, [], db, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.IsEmpty(system.Errors);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateErrors_AddError_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
};
List<ErrorEventMessage>? errors = [new() {
Index = 42,
Message = "Error Message",
TimeGenerated = new(2025,11,5)
}];
system = await UCSSystemMonitorDevice.UpdateErrors(system, errors, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, system.Errors);
Assert.AreEqual(2, system.Errors.ToList()[0].Id);
Assert.AreEqual(42, system.Errors.ToList()[0].Index);
Assert.AreEqual("woensdag 5 november 2025", system.Errors.ToList()[0].TimeGenerated.ToLongDateString());
Assert.AreEqual("Error Message", system.Errors.ToList()[0].Message);
Assert.HasCount(2, db.Errors);
Assert.HasCount(1, testingTelegramBot.Messages);
Assert.AreEqual("Send - ‼️ <b>Computer - Config File</b>\r\n Error Message", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateErrors_UpdateError_Test()
{
using MonitorDbContext db = CreateDataBaseFactory().CreateDbContext();
Assert.IsNotNull(db);
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = db.UCSSystems.FirstOrDefault();
List<ErrorEventMessage>? errors = [new() {
Index = 42,
}];
system = await UCSSystemMonitorDevice.UpdateErrors(system, errors, db, testingTelegramBot, TestContext.CancellationToken);
await db.SaveChangesAsync(TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.HasCount(1, db.Errors);
Assert.HasCount(0, testingTelegramBot.Messages);
}
}
}

View File

@@ -0,0 +1,78 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Models.Database;
using UCS_Status_Monitor.Monitor;
using UCS_Status_Monitor.Telemetry;
namespace UCS_Status_Monitor.UnitTest.Monitor.UCSSystemTest
{
[TestClass]
public class UpdateStartTime_Test : MonitorTestSetup
{
public TestContext TestContext { get; set; }
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateStartTime_Null_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateStartTime(system, null, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("1-1-0001 00:00:00", system.StartTime.ToString());
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateStartTime_Empty_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateStartTime(system, "", testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("1-1-0001 00:00:00", system.StartTime.ToString());
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateStartTime_Update_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Computer",
ConfigFileName = "Config File",
StartTime = new DateTime(2025, 1, 5)
};
system = await UCSSystemMonitorDevice.UpdateStartTime(system, "31-10-2025 02:04:00", testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("31-10-2025 02:04:00", system.StartTime.ToString());
Assert.HasCount(1, testingTelegramBot.Messages);
Assert.AreEqual("Send - ♻️ <b>Computer - Config File</b>\r\n UCS restarted", testingTelegramBot.Messages[0]);
}
}
}

View File

@@ -0,0 +1,165 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Threading.Tasks;
using UCS_Status_Monitor.Models.Database;
using UCS_Status_Monitor.Monitor;
namespace UCS_Status_Monitor.UnitTest.Monitor.UCSSystemTest
{
[TestClass]
public class UpdateUSBDevices_Test : MonitorTestSetup
{
public TestContext TestContext { get; set; }
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Null_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, null, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("No USB disks", system.USBDisks);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Empty_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
};
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, [], testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("No USB disks", system.USBDisks);
Assert.HasCount(0, testingTelegramBot.Messages);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_NoDisk_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
};
List<string> usbDisks = ["No USB disks"];
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("No USB disks", system.USBDisks);
Assert.HasCount(0, testingTelegramBot.Messages);
//Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_NoDiskUpdate_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
USBDisks = "No USB disks"
};
List<string> usbDisks = ["No USB disks"];
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("No USB disks", system.USBDisks);
Assert.HasCount(0, testingTelegramBot.Messages);
//Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_DiskRemoved_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
USBDisks = "disk 1\r\ndisk 2\r\ndisk 3"
};
List<string> usbDisks = ["No USB disks"];
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("No USB disks", system.USBDisks);
Assert.HasCount(1, testingTelegramBot.Messages);
Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk removed", testingTelegramBot.Messages[0]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Adddisks_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
};
List<string> usbDisks = ["disk 1", "disk 2", "disk 3"];
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("disk 1\r\ndisk 2\r\ndisk 3", system.USBDisks);
Assert.HasCount(3, testingTelegramBot.Messages);
Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 1 detected", testingTelegramBot.Messages[0]);
Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 2 detected", testingTelegramBot.Messages[1]);
Assert.AreEqual("Send - ⚠️ <b>Test - Config File</b>\r\n USB disk disk 3 detected", testingTelegramBot.Messages[2]);
}
[TestMethod]
public async Task UCSSystemMonitorDevice_UpdateUSBDevices_Update_Test()
{
TestingTelegramBot testingTelegramBot = new();
Assert.IsNotNull(testingTelegramBot);
UCSSystem? system = new()
{
ComputerName = "Test",
ConfigFileName = "Config File",
USBDisks = "disk 1\r\ndisk 2\r\ndisk 3"
};
List<string> usbDisks = ["disk 1", "disk 2", "disk 3"];
system = await UCSSystemMonitorDevice.UpdateUSBDevices(system, usbDisks, testingTelegramBot, TestContext.CancellationToken);
Assert.IsNotNull(system);
Assert.AreEqual("disk 1\r\ndisk 2\r\ndisk 3", system.USBDisks);
Assert.HasCount(0, testingTelegramBot.Messages);
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Globalization;
namespace UCS_Status_Monitor.Extensions
@@ -46,5 +47,18 @@ namespace UCS_Status_Monitor.Extensions
}
return dt.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
public static DateTime ParseDeviceTime(this string? deviceTime)
{
if (DateTime.TryParseExact(deviceTime, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime laststate))
{
return laststate;
}
else
{
Debug.WriteLine($"Failed to parse LastStateChange");
return DateTime.MinValue;
}
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
@@ -10,10 +11,21 @@ namespace UCS_Status_Monitor.Extensions
{
ArgumentNullException.ThrowIfNull(arr);
var str = "";
foreach (var item in arr)
//foreach (var item in arr)
//{
// str += $"{item}{Environment.NewLine}";
//}
for (int i = 0; i < arr.Count; i++)
{
str += $"{item}{Environment.NewLine}";
str += arr[i];
if (i != arr.Count - 1)
{
str += Environment.NewLine;
}
}
return str;
}

View File

@@ -1,7 +1,10 @@
using Microsoft.AspNetCore.Components.Routing;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using UCS_Status_Monitor.Models.Database;
using static UCS_Status_Monitor.Monitor.UCSSystemMonitorDevice;
namespace UCS_Status_Monitor.Extensions
{

View File

@@ -26,25 +26,9 @@ namespace UCS_Status_Monitor.Models.Database
LastMessageTime = DateTime.Now;
ConnectionState = true;
if (DateTime.TryParseExact(telemetry.StartTime, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime starttime))
{
StartTime = starttime;
}
else
{
Debug.WriteLine($"Failed to parse starttime");
StartTime = DateTime.MinValue;
}
if (DateTime.TryParseExact(telemetry.Date, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime lastmessage))
{
LastMessageClient = lastmessage;
}
else
{
Debug.WriteLine($"Failed to parse Date");
LastMessageClient = DateTime.MinValue;
}
StartTime = telemetry.StartTime.ParseDeviceTime();
LastMessageClient = telemetry.Date.ParseDeviceTime();
ConfigFileName = telemetry.ConfigFileName ?? "??";
Uptime = telemetry.Uptime ?? "??";

View File

@@ -7,7 +7,7 @@ namespace UCS_Status_Monitor.Monitor
{
public interface IUCSSystemMonitorDevice
{
public Task Update(TelemetryPacket message, MonitorDbContext db, CancellationToken token);
public Task Update(TelemetryPacket telemetryPacket, MonitorDbContext db, CancellationToken token);
public Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default);
}
}

View File

@@ -1,10 +1,14 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.DirectoryServices.ActiveDirectory;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Extensions;
using UCS_Status_Monitor.Models.Database;
@@ -40,167 +44,236 @@ namespace UCS_Status_Monitor.Monitor
{
system.ConnectionState = isConnected;
db.UCSSystems.Update(system);
db.Loggings.Add(new Logging { Date = DateTime.Now, State = isConnected, UCSSystem = system });
db.Loggings.Add(new Logging { Date = DateTime.Now, State = isConnected, UCSSystem = system });
}
await TelegramBot.SendConnectionStatus($"{DeviceName} - {system?.ConfigFileName}", isConnected, token);
}
}
public async Task Update(TelemetryPacket message, MonitorDbContext db, CancellationToken token)
public async Task Update(TelemetryPacket telemetryPacket, MonitorDbContext db, CancellationToken token)
{
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(telemetryPacket);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.ComputerName ?? "??";
DeviceName = telemetryPacket.ComputerName ?? "??";
UCSSystem? system = await db.UCSSystems.Where(n => n.ComputerName == DeviceName).SingleOrDefaultAsync(token);
if (system == null)
{
//New Database ucs system
system = new UCSSystem(message);
system = new UCSSystem(telemetryPacket);
db.UCSSystems.Add(system);
await db.SaveChangesAsync(token);
await TelegramBot.SendDeviceAdded($"{DeviceName} - {system.ConfigFileName}", token);
}
//UCSSystem system = await GetUCSSystem(message, db, token);
//Update
if (message.StartTime != null)
{
//Debug.WriteLine($"{message.ComputerName} - starttime:{message.StartTime} - database:{system.StartTime}");
if (DateTime.TryParseExact(message.StartTime, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime starttime))
{
if (system.StartTime < starttime)
{
await TelegramBot.Send($"♻️ <b>{DeviceName} - {system.ConfigFileName}</b>{Environment.NewLine} UCS restarted", token);
}
}
else
{
Debug.WriteLine($"Failed to parse starttime");
}
}
system = await UpdateStartTime(system, telemetryPacket.StartTime, TelegramBot, token);
system = await UpdateUSBDevices(system, telemetryPacket.ComputerInfo?.USBDisks, TelegramBot, token);
system = await UpdateErrors(system, telemetryPacket.Errors, db, TelegramBot, token);
system = await UpdateConnectionStates(system, telemetryPacket.Connectionstates, db, TelegramBot, token);
if (message.ComputerInfo?.USBDisks?.Count > 0)
{
if (system.USBDisks != message.ComputerInfo.USBDisks.ListToString())
{
if (!message.ComputerInfo.USBDisks.ListToString().Contains("No USB disks", StringComparison.InvariantCultureIgnoreCase))
{
foreach (string disk in message.ComputerInfo.USBDisks)
{
await TelegramBot.Send($"⚠️ <b>{DeviceName} - {system.ConfigFileName}</b>{Environment.NewLine} USB disk {disk} detected", token);
}
}
}
}
if (message.Errors != null)
{
foreach (var err in message.Errors)
{
if (await db.Errors.Where(x => x.UCSSystem == system).Where(x => x.Index == err.Index).AnyAsync(token) == false)
{
var newError = new EventLogError
{
Index = err.Index ?? 0,
TimeGenerated = err.TimeGenerated ?? DateTime.Now,
Message = err.Message ?? "??",
UCSSystem = system
};
db.Errors.Add(newError);
await TelegramBot.Send($"‼️ <b>{DeviceName} - {system.ConfigFileName}</b>{Environment.NewLine} {err.Message}", token);
}
}
}
if (message.Connectionstates == null)
{
//remove all devices
IQueryable<UCSDevice> devices = db.UCSDevices.Where(s => s.UCSSystem == system);
if (devices.Any())
{
db.UCSDevices.RemoveRange(devices);
}
}
else
{
//Update all devices in connectionstate list
foreach (ConnectionState deviceState in message.Connectionstates)
{
if (deviceState.ID != null)
{
UCSDevice? dbDevice = await db.UCSDevices
.Where(d => d.BoxID == deviceState.ID)
.Where(d => d.Name == deviceState.Name)
.Where(d => d.UCSSystem == system)
.SingleOrDefaultAsync(token);
if (dbDevice == null)
{
UCSDevice newDevice = new()
{
Name = deviceState.Name ?? "??",
BoxID = deviceState.ID,
State = deviceState.State ?? false,
Message = deviceState.Message ?? string.Empty,
UCSSystem = system
};
if (DateTime.TryParseExact(deviceState.LastStateChange, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime laststate))
{
newDevice.LastStateChange = laststate;
}
else
{
Debug.WriteLine($"Failed to parse LastStateChange");
newDevice.LastStateChange = DateTime.MinValue;
}
db.UCSDevices.Add(newDevice);
}
else
{
dbDevice.Name = deviceState.Name ?? "??";
dbDevice.Message = deviceState.Message ?? string.Empty;
if (dbDevice.State != deviceState.State)
{
dbDevice.State = deviceState.State ?? false;
if (dbDevice.State)
{
await TelegramBot.Send($"✅ <b>{DeviceName} - {system.ConfigFileName}</b>{Environment.NewLine} {deviceState.ID} {dbDevice.Name} Online", token);
}
else
{
await TelegramBot.Send($"⚠️ <b>{DeviceName} - {system.ConfigFileName}</b>{Environment.NewLine} {deviceState.ID} {dbDevice.Name} Lost Connection", token);
}
}
if (DateTime.TryParseExact(deviceState.LastStateChange, "dd-MM-yyyy HH:mm:ss", null, DateTimeStyles.None, out DateTime laststate))
{
dbDevice.LastStateChange = laststate;
}
else
{
Debug.WriteLine($"Failed to parse LastStateChange");
dbDevice.LastStateChange = DateTime.MinValue;
}
db.UCSDevices.Update(dbDevice);
}
}
}
db.UCSDevices.RemoveRange(db.UCSDevices
.Where(b => b.UCSSystem == system)
.ToList()
.ExceptBy(message.Connectionstates.Select(i => i.ID).ToList(), i => i.BoxID));
}
system.Update(message);
system.Update(telemetryPacket);
db.UCSSystems.Update(system);
LastData = DateTime.UtcNow;
}
//public async Task<UCSSystem> GetUCSSystem(TelemetryPacket message, MonitorDbContext db, CancellationToken token)
//{
// ArgumentNullException.ThrowIfNull(db);
// UCSSystem? system = await db.UCSSystems.Where(n => n.ComputerName == message.ComputerName).SingleOrDefaultAsync(token);
// if (system == null)
// {
// //New Database ucs system
// system = new UCSSystem(message);
// db.UCSSystems.Add(system);
// await db.SaveChangesAsync(token);
// await TelegramBot.SendDeviceAdded($"{system.ComputerName} - {system.ConfigFileName}", token);
// }
// return system;
//}
public static async Task<UCSSystem?> UpdateStartTime(UCSSystem? system, string? starttime, ITelegramBotService telegramBot, CancellationToken token)
{
if (system != null)
{
if (!string.IsNullOrEmpty(starttime))
{
DateTime datetime = starttime.ParseDeviceTime();
if (system.StartTime < datetime)
{
if (telegramBot != null)
{
await telegramBot.Send($"♻️ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} UCS restarted", token);
}
}
system.StartTime = datetime;
}
}
return system;
}
public static async Task<UCSSystem?> UpdateUSBDevices(UCSSystem? system, List<string>? usbDisks, ITelegramBotService telegramBot, CancellationToken token)
{
if (system != null)
{
if (usbDisks?.Count > 0)
{
if (system.USBDisks != usbDisks.ListToString())
{
if (usbDisks.ListToString().Contains("No USB disks", StringComparison.InvariantCultureIgnoreCase))
{
if (!string.IsNullOrEmpty(system.USBDisks))
{
if (telegramBot != null)
{
await telegramBot.Send($"⚠️ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} USB disk removed", token);
}
}
system.USBDisks = "No USB disks";
}
else
{
foreach (string disk in usbDisks)
{
if (telegramBot != null)
{
await telegramBot.Send($"⚠️ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} USB disk {disk} detected", token);
}
}
system.USBDisks = usbDisks.ListToString();
}
}
}
else
{
system.USBDisks = "No USB disks";
}
}
return system;
}
public static async Task<UCSSystem?> UpdateErrors(UCSSystem? system, List<ErrorEventMessage>? errors, MonitorDbContext db, ITelegramBotService telegramBot, CancellationToken token)
{
if (system != null)
{
if (errors?.Count > 0)
{
foreach (var err in errors)
{
if (db != null)
{
//error already in database ?
if (await db.Errors.Where(x => x.UCSSystem == system).Where(x => x.Index == err.Index).AnyAsync(token) == false)
{
db.Errors.Add(new EventLogError
{
Index = err.Index ?? 0,
TimeGenerated = err.TimeGenerated ?? DateTime.Now,
Message = err.Message ?? "??",
UCSSystem = system
});
if (telegramBot != null)
{
await telegramBot.Send($"‼️ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} {err.Message}", token);
}
}
}
}
}
}
return system;
}
public static async Task<UCSSystem?> UpdateConnectionStates(UCSSystem? system, List<ConnectionState>? connectionstates, MonitorDbContext db, ITelegramBotService telegramBot, CancellationToken token)
{
if (system != null)
{
if (connectionstates?.Count > 0)
{
//Update all devices in connectionstate list
foreach (ConnectionState deviceState in connectionstates)
{
if (deviceState.ID != null)
{
UCSDevice? dbDevice = await db.UCSDevices
.Where(d => d.BoxID == deviceState.ID)
.Where(d => d.Name == deviceState.Name)
.Where(d => d.UCSSystem == system)
.SingleOrDefaultAsync(token);
if (dbDevice == null)
{
UCSDevice newDevice = new()
{
Name = deviceState.Name ?? "??",
BoxID = deviceState.ID,
State = deviceState.State ?? false,
Message = deviceState.Message ?? string.Empty,
UCSSystem = system,
LastStateChange = deviceState.LastStateChange.ParseDeviceTime()
};
db.UCSDevices.Add(newDevice);
if (telegramBot != null)
{
await telegramBot.Send($"✅ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} {newDevice.BoxID} {newDevice.Name} Added", token);
}
}
else
{
dbDevice.Name = deviceState.Name ?? "??";
dbDevice.Message = deviceState.Message ?? string.Empty;
if (dbDevice.State != deviceState.State)
{
dbDevice.State = deviceState.State ?? false;
if (dbDevice.State)
{
await telegramBot.Send($"✅ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} {deviceState.ID} {dbDevice.Name} Online", token);
}
else
{
await telegramBot.Send($"⚠️ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} {deviceState.ID} {dbDevice.Name} Lost Connection", token);
}
}
dbDevice.LastStateChange = deviceState.LastStateChange.ParseDeviceTime();
db.UCSDevices.Update(dbDevice);
}
}
}
foreach (var dev in db.UCSDevices.Where(u => u.UCSSystem == system))
{
//Debug.WriteLine($"database {dev.BoxID} - {dev.Name}");
if (!connectionstates.Where(d => d.ID == dev.BoxID).Where(d => d.Name == dev.Name).Any())
{
//Debug.WriteLine("Not Found");
db.UCSDevices.Remove(dev);
if (telegramBot != null)
{
await telegramBot.Send($"✅ <b>{system.ComputerName} - {system.ConfigFileName}</b>{Environment.NewLine} {dev.BoxID} {dev.Name} Removed", token);
}
}
}
}
else
{
//remove all devices
IQueryable<UCSDevice> devices = db.UCSDevices.Where(s => s.UCSSystem == system);
if (devices.Any())
{
db.UCSDevices.RemoveRange(devices);
}
}
}
return system;
}
}
}