public async Task ListenToEvents(string connString) { signalRHubHelper = new SignalRHubHelper(connString); var hubUrl = signalRHubHelper.ClientUrl("default_hub"); // define a connection to receive published events signalRHubConnection = new HubConnectionBuilder().WithUrl(hubUrl, option => { option.AccessTokenProvider = () => { var token = signalRHubHelper.GenerateAccessToken(hubUrl, "user-x"); return(Task.FromResult(token)); }; }).Build(); // define an event handler for received messages signalRHubConnection.On <string, string>("StatusChanged", (deviceId, status) => { Console.WriteLine($"Device {deviceId} changed status to {status}"); }); // start listening to published events await signalRHubConnection.StartAsync(); Console.WriteLine("Listening for events..."); }
async Task InitSignalR() { var configBuilder = new ConfigurationBuilder(); configBuilder.AddUserSecrets("a0aa8545-9a28-485e-8218-9851c41dcfbb"); var config = configBuilder.Build(); // copy the CONNECTION STRING value from the Azure Portal under SingalR > [item] > Keys (under Settings) // then in the csproj dir, run dotnet user-secrets set "signalRConnString" "conn_string_value" // see https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.2&tabs=windows var connStr = config["signalRConnString"]; if (string.IsNullOrEmpty(connStr)) { throw new ArgumentNullException(nameof(connStr), "set the CONNECTION STRING value from the Azure Portal under SingalR > [item] > Keys (under Settings)"); } signalRHubHelper = new SignalRHubHelper(connStr); signalRApiHttpClient = new HttpClient(); signalRApiClient = new SignalRApiClient(signalRApiHttpClient, signalRHubHelper); var hubUrl = signalRHubHelper.ClientUrl(hubName: "default"); signalRHubConnection = new HubConnectionBuilder().WithUrl(hubUrl, option => { option.AccessTokenProvider = () => { var token = signalRHubHelper.GenerateAccessToken(hubUrl, "user-x"); return(Task.FromResult(token)); }; }).Build(); signalRHubConnection.On <int, string>("StatusChanged", (tableId, status) => { Dispatcher.Invoke(() => { if (tblControlsById.TryGetValue(tableId, out TableStatusControl tblControl)) { tblControl.Status = status; lblLastAction.Content = $"Status updated on {DateTime.Now}"; } }); }); SetupConnectionRetry(); await signalRHubConnection.StartAsync(); lblConnStatus.Content = "Online"; lblConnStatus.Background = Brushes.SeaGreen; lblLastAction.Content = $"Connected on {DateTime.Now}"; }