using Microsoft.AspNetCore.SignalR; namespace Zentral.API.Hubs; /// /// Hub SignalR per la sincronizzazione in tempo reale dei dati tra client /// public class DataHub : Hub { /// /// Notifica tutti i client che un'entità è stata modificata /// public async Task NotifyDataChanged(string entityType, string action, object? data = null) { try { await Clients.Others.SendAsync("DataChanged", entityType, action, data); } catch (Exception ex) { Console.WriteLine($"[DataHub] Error in NotifyDataChanged: {ex.Message}"); } } public override async Task OnConnectedAsync() { try { Console.WriteLine($"[DataHub] Client connecting: {Context.ConnectionId}"); await base.OnConnectedAsync(); Console.WriteLine($"[DataHub] Client connected: {Context.ConnectionId}"); } catch (Exception ex) { Console.WriteLine($"[DataHub] Error in OnConnectedAsync: {ex.Message}"); throw; } } public override async Task OnDisconnectedAsync(Exception? exception) { try { if (exception != null) { Console.WriteLine($"[DataHub] Client disconnected with error: {Context.ConnectionId} - {exception.Message}"); } else { Console.WriteLine($"[DataHub] Client disconnected: {Context.ConnectionId}"); } await base.OnDisconnectedAsync(exception); } catch (Exception ex) { Console.WriteLine($"[DataHub] Error in OnDisconnectedAsync: {ex.Message}"); throw; } } } /// /// Servizio per inviare notifiche dal backend ai client /// public class DataNotificationService { private readonly IHubContext _hubContext; public DataNotificationService(IHubContext hubContext) { _hubContext = hubContext; } public async Task NotifyCreated(string entityType, T entity) { await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "created", entity); } public async Task NotifyUpdated(string entityType, T entity) { await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "updated", entity); } public async Task NotifyDeleted(string entityType, int id) { await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "deleted", new { id }); } public async Task NotifyBulkChange(string entityType) { await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "bulk", null); } }