Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using RealTimeCharts.Server.DataStorage;
using RealTimeCharts.Server.HubConfig;
using RealTimeCharts.Server.TimerFeatures;

namespace RealTimeCharts.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChartController : ControllerBase
{
private readonly IHubContext<ChartHub> _hub;
private readonly TimerManager _timer;

public ChartController(IHubContext<ChartHub> hub, TimerManager timer)
{
_hub = hub;
_timer = timer;
}

[HttpGet]
public IActionResult Get()
{
if (!_timer.IsTimerStarted)
_timer.PrepareTimer(() => _hub.Clients.All.SendAsync("TransferChartData", DataManager.GetData()));
return Ok(new { Message = "Request Completed" });
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using RealTimeCharts.Server.Models;

namespace RealTimeCharts.Server.DataStorage
{
public class DataManager
{
public static List<ChartModel> GetData()
{
var r = new Random();
return new List<ChartModel>()
{
new ChartModel { Data = new List<int> { r.Next(1, 40) }, Label = "Data1", BackgroundColor = "#5491DA" },
new ChartModel { Data = new List<int> { r.Next(1, 40) }, Label = "Data2", BackgroundColor = "#E74C3C" },
new ChartModel { Data = new List<int> { r.Next(1, 40) }, Label = "Data3", BackgroundColor = "#82E0AA" },
new ChartModel { Data = new List<int> { r.Next(1, 40) }, Label = "Data4", BackgroundColor = "#E5E7E9" }
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.SignalR;
using RealTimeCharts.Server.Models;

namespace RealTimeCharts.Server.HubConfig
{
public class ChartHub : Hub
{
public async Task BroadcastChartData(List<ChartModel> data) =>
await Clients.All.SendAsync("broadcastchartdata", data);

public async Task BroadcastChartDataToClient(List<ChartModel> data, string connectionId) =>
await Clients.Client(connectionId).SendAsync("broadcastchartdata", data);

public string GetConnectionId() => Context.ConnectionId;

public async Task BroadcastToConnection(string data, string connectionId)
=> await Clients.Client(connectionId).SendAsync("broadcasttoclient", data);

public async Task BroadcastToUser(string data, string userId)
=> await Clients.User(userId).SendAsync("broadcasttouser", data);

public async Task AddToGroup(string groupName)
=> await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

public async Task RemoveFromGroup(string groupName)
=> await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);

public async Task BroadcastToGroup(string groupName) => await Clients.Group(groupName)
.SendAsync("broadcasttogroup", $"{Context.ConnectionId} has joined the group {groupName}.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace RealTimeCharts.Server.Models
{
public class ChartModel
{
public List<int> Data { get; set; }
public string? Label { get; set; }
public string? BackgroundColor { get; set; }

public ChartModel()
{
Data = new List<int>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using RealTimeCharts.Server.HubConfig;
using RealTimeCharts.Server.TimerFeatures;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});

builder.Services.AddSignalR();

builder.Services.AddSingleton<TimerManager>();

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseCors("CorsPolicy");

app.UseAuthorization();

app.MapControllers();
app.MapHub<ChartHub>("/chart");

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"profiles": {
"RealTimeCharts.Server": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace RealTimeCharts.Server.TimerFeatures
{
public class TimerManager
{
private Timer? _timer;
private Action? _action;
public DateTime TimerStarted { get; set; }
public bool IsTimerStarted { get; set; }

public void PrepareTimer(Action action)
{
_action = action;
_timer = new Timer(Execute, null, 1000, 2000);
TimerStarted = DateTime.Now;
IsTimerStarted = true;
}

public void Execute(object? stateInfo)
{
_action?.Invoke();

if ((DateTime.Now - TimerStarted).TotalSeconds > 60)
{
IsTimerStarted = false;
_timer?.Dispose();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RealTimeCharts.Server", "RealTimeCharts.Server\RealTimeCharts.Server.csproj", "{0464F2B0-B76B-4164-9E13-6F171F881DE3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|x64.ActiveCfg = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|x64.Build.0 = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|x86.ActiveCfg = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Debug|x86.Build.0 = Debug|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|Any CPU.Build.0 = Release|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|x64.ActiveCfg = Release|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|x64.Build.0 = Release|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|x86.ActiveCfg = Release|Any CPU
{0464F2B0-B76B-4164-9E13-6F171F881DE3}.Release|x86.Build.0 = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|x64.ActiveCfg = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|x64.Build.0 = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|x86.ActiveCfg = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Debug|x86.Build.0 = Debug|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|Any CPU.Build.0 = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|x64.ActiveCfg = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|x64.Build.0 = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|x86.ActiveCfg = Release|Any CPU
{FCA2A762-2CC0-456D-959E-EF8BFB0F563F}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
using Microsoft.AspNetCore.SignalR;
using Moq;
using RealTimeCharts.Server.HubConfig;
using RealTimeCharts.Server.Models;

namespace Tests
{
public class ChartHubTests
{
private const string ConnectionId = "test-connection-id";

private readonly Mock<IHubCallerClients> _clients = new();
private readonly Mock<IClientProxy> _allProxy = new();
private readonly Mock<ISingleClientProxy> _singleProxy = new();
private readonly Mock<IClientProxy> _userProxy = new();
private readonly Mock<IClientProxy> _groupProxy = new();
private readonly Mock<IGroupManager> _groups = new();
private readonly ChartHub _hub;

public ChartHubTests()
{
_clients.Setup(c => c.All).Returns(_allProxy.Object);
_clients.Setup(c => c.Client(It.IsAny<string>())).Returns(_singleProxy.Object);
_clients.Setup(c => c.User(It.IsAny<string>())).Returns(_userProxy.Object);
_clients.Setup(c => c.Group(It.IsAny<string>())).Returns(_groupProxy.Object);

var context = new Mock<HubCallerContext>();
context.Setup(c => c.ConnectionId).Returns(ConnectionId);

_hub = new ChartHub
{
Clients = _clients.Object,
Groups = _groups.Object,
Context = context.Object
};
}

[Fact]
public async Task WhenBroadcastChartDataIsCalled_ThenAllClientsReceiveTheData()
{
var data = new List<ChartModel> { new() { Label = "Data1" } };

await _hub.BroadcastChartData(data);

_allProxy.Verify(p => p.SendCoreAsync(
"broadcastchartdata",
It.Is<object?[]>(a => a.Length == 1 && ReferenceEquals(a[0], data)),
It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task WhenBroadcastChartDataToClientIsCalled_ThenOnlyThatConnectionReceivesTheData()
{
var data = new List<ChartModel> { new() { Label = "Data1" } };

await _hub.BroadcastChartDataToClient(data, ConnectionId);

_clients.Verify(c => c.Client(ConnectionId), Times.Once);
_singleProxy.Verify(p => p.SendCoreAsync(
"broadcastchartdata",
It.Is<object?[]>(a => a.Length == 1 && ReferenceEquals(a[0], data)),
It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public void WhenGetConnectionIdIsCalled_ThenTheCallerConnectionIdIsReturned()
{
Assert.Equal(ConnectionId, _hub.GetConnectionId());
}

[Fact]
public async Task WhenBroadcastToConnectionIsCalled_ThenTheNamedConnectionIsTargeted()
{
await _hub.BroadcastToConnection("payload", ConnectionId);

_clients.Verify(c => c.Client(ConnectionId), Times.Once);
_singleProxy.Verify(p => p.SendCoreAsync(
"broadcasttoclient",
It.Is<object?[]>(a => a.Length == 1 && (string)a[0]! == "payload"),
It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task WhenBroadcastToUserIsCalled_ThenEveryConnectionOfThatUserIsTargeted()
{
await _hub.BroadcastToUser("payload", "user-1");

_clients.Verify(c => c.User("user-1"), Times.Once);
_userProxy.Verify(p => p.SendCoreAsync(
"broadcasttouser",
It.Is<object?[]>(a => a.Length == 1 && (string)a[0]! == "payload"),
It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task WhenAddToGroupAndRemoveFromGroupAreCalled_ThenTheCallerConnectionIsMoved()
{
await _hub.AddToGroup("room-1");
await _hub.RemoveFromGroup("room-1");

_groups.Verify(g => g.AddToGroupAsync(ConnectionId, "room-1", It.IsAny<CancellationToken>()), Times.Once);
_groups.Verify(g => g.RemoveFromGroupAsync(ConnectionId, "room-1", It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public async Task WhenBroadcastToGroupIsCalled_ThenTheGroupReceivesTheJoinMessage()
{
await _hub.BroadcastToGroup("room-1");

_clients.Verify(c => c.Group("room-1"), Times.Once);
_groupProxy.Verify(p => p.SendCoreAsync(
"broadcasttogroup",
It.Is<object?[]>(a => a.Length == 1
&& (string)a[0]! == $"{ConnectionId} has joined the group room-1."),
It.IsAny<CancellationToken>()), Times.Once);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
Loading
Loading