Skip to content

Commit

Permalink
Add SignalR HUB refresh instead of polling.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alejandro Del Rincón López committed Nov 17, 2023
1 parent 317c38a commit f872995
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 12 deletions.
2 changes: 2 additions & 0 deletions BlazorApp1.Application/BlazorApp1.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.1.0" />
</ItemGroup>

<ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions BlazorApp1.Application/IWeatherForecastService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ namespace BlazorApp1.Application;
public interface IWeatherForecastService
{
Task AddForecast(WeatherForecastDto weatherForecast, CancellationToken cancellationToken = default);
ValueTask ProcessSignalRWeatherSummary(CancellationToken cancellationToken);
ValueTask ProcessWeatherSummary(WeatherForecast forecast, CancellationToken cancellationToken);
}
28 changes: 27 additions & 1 deletion BlazorApp1.Application/WeatherForecastService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
using BlazorApp1.Domain;
using BlazorApp1.Domain.Abstractions.Repositories;
using BlazorApp1.Server.Abstractions.Contracts;
using BlazorApp1.Server.Hubs;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

Expand All @@ -14,18 +18,21 @@ public class WeatherForecastService : IWeatherForecastService
private readonly IWeatherForecastSummaryRepository _weatherForecastSummaryRepository;
private readonly IMapper _mapper;
private readonly IBackgroundTaskQueue _backgroundTaskQueue;
private readonly IHubContext<WeatherForecastSummaryHub> hubContext;
private readonly ILogger<WeatherForecastService> _logger;

public WeatherForecastService(IWeatherForecastRepository weatherForecastRepository,
IWeatherForecastSummaryRepository weatherForecastSummaryRepository,
IMapper mapper,
IBackgroundTaskQueue backgroundTaskQueue,
IHubContext<WeatherForecastSummaryHub> hubContext,
ILogger<WeatherForecastService> logger)
{
_weatherForecastRepository = weatherForecastRepository;
_weatherForecastSummaryRepository = weatherForecastSummaryRepository;
_mapper = mapper;
_backgroundTaskQueue = backgroundTaskQueue;
this.hubContext = hubContext;
_logger = logger;
}

Expand All @@ -35,7 +42,24 @@ public async Task AddForecast(WeatherForecastDto weatherForecast, CancellationTo

await _weatherForecastRepository.AddWeatherForecast(forecast);

var tasktoDo = _backgroundTaskQueue.QueueBackgroundWorkItemAsync(ProcessWeatherSummary(forecast));
await _backgroundTaskQueue.QueueBackgroundWorkItemAsync(ProcessWeatherSummary(forecast));
}

private static Func<IServiceProvider, CancellationToken, ValueTask> ProcessSignalRWeatherSummary(WeatherForecast forecast)
{
return (serviceProvider, cancellationToken) =>
{
var service = serviceProvider.GetRequiredService<IWeatherForecastService>();
return service.ProcessSignalRWeatherSummary(cancellationToken);
};
}

public async ValueTask ProcessSignalRWeatherSummary(CancellationToken cancellationToken)
{
//TODO: Move to a new RepoMethod.
var forecasts = await _weatherForecastSummaryRepository.GetAllForecastSummaries();

await this.hubContext.Clients.All.SendAsync("ReceiveForecastSummaries", forecasts.ToArray());
}

private static Func<IServiceProvider, CancellationToken, ValueTask> ProcessWeatherSummary(WeatherForecast forecast)
Expand Down Expand Up @@ -70,6 +94,8 @@ public async ValueTask ProcessWeatherSummary(WeatherForecast forecast, Cancellat
await _weatherForecastSummaryRepository.AddWeatherForecastSummary(forecastSummary);
}

await _backgroundTaskQueue.QueueBackgroundWorkItemAsync(ProcessSignalRWeatherSummary(forecast));

_logger.LogInformation($"Processing ForecastSummary and added {forecast.Date}");
}
}
13 changes: 13 additions & 0 deletions BlazorApp1.Application/WeatherForecastSummaryHub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using BlazorApp1.Domain;
using BlazorApp1.Server.Abstractions.Contracts;
using Microsoft.AspNetCore.SignalR;

namespace BlazorApp1.Server.Hubs;

public class WeatherForecastSummaryHub : Hub
{
public async Task SendWeatherforecastSummaries(WeatherForecastSummaryDto[] summaries)
{
await Clients.All.SendAsync("ReceiveForecastSummaries", summaries);
}
}
22 changes: 12 additions & 10 deletions BlazorApp1/Client/Pages/FetchData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
@using BlazorApp1.Domain
@using BlazorApp1.Server.Abstractions.Contracts
@using System.Text.Json.Serialization;
@using Microsoft.AspNetCore.SignalR.Client;
@inject NavigationManager Navigation
@inject HttpClient Http

<PageTitle>Weather forecast</PageTitle>
Expand Down Expand Up @@ -74,7 +76,7 @@ else
private WeatherForecastDto[]? forecasts;
private WeatherForecastSummary[]? forecastSummaries;
private WeatherForecastDto? forecastToAdd;
private static System.Timers.Timer _timer;
private HubConnection? hubConnection;

protected override async Task OnInitializedAsync()
{
Expand All @@ -84,28 +86,28 @@ else
Date = DateTime.Now
};

_timer = new System.Timers.Timer(5000);
_timer.Elapsed += CountDownTimer;
_timer.Enabled = true;
}

public async void CountDownTimer(Object source, System.Timers.ElapsedEventArgs e)
{
forecastSummaries = await Http.GetFromJsonAsync<WeatherForecastSummary[]>("WeatherForecastSummary");
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/weatherforecastsummaryhub"))
.Build();

await InvokeAsync(async () =>
hubConnection.On<WeatherForecastSummary[]>("ReceiveForecastSummaries", (summaries) =>
{
forecastSummaries = summaries;
StateHasChanged();
});

await hubConnection.StartAsync();
}

private async Task AddForecast()
{
if (forecastToAdd != null)
{
var response = await Http.PostAsJsonAsync<WeatherForecastDto>("WeatherForecast", forecastToAdd, WeatherForecastDtoJsonContext.Default.WeatherForecastDto);
}

await ReloadDataAsync();
forecasts = await Http.GetFromJsonAsync<WeatherForecastDto[]>("WeatherForecast", WeatherForecastDtoJsonContext.Default.WeatherForecastDtoArray);
}

private async Task ReloadDataAsync()
Expand Down
2 changes: 1 addition & 1 deletion BlazorApp1/Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using BlazorApp1.Server.Profiles;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using System.Text.Encodings.Web;

var builder = WebApplication.CreateBuilder(args);

Expand Down Expand Up @@ -65,6 +64,7 @@
app.MapControllers();

app.MapHub<ChatHub>("/chathub");
app.MapHub<WeatherForecastSummaryHub>("/weatherforecastsummaryhub");

app.MapFallbackToFile("index.html");

Expand Down

0 comments on commit f872995

Please sign in to comment.