Pages

Sunday, August 23, 2020

ASP.NET Core SignalR Chart Hub Application using Chartist.js

 https://gionkunz.github.io/chartist-js/

https://github.com/mkader/SignalRExample
 
Real time Chart Application Use Cases
  • Real-time KPI (key performance indicator) dashboard of sales figures, 
  • Stock market price ticker 
  • Shared calendar scheduler
  • Notification dashboard (like doctor in/out for a hospital ward)
IChartHubClient.cs 
using System.Threading.Tasks;

namespace RealTimeChart
{
    public interface IChartHubClient
    {
        Task ValueReceiver(double chartValue);
    }
}


RealTimeChart.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace RealTimeChart
{
    public class ChartHub : Hub<IChartHubClient>
    {
        public async Task ValueSender(double chartValue) 
        { 
            await Clients.All.ValueReceiver(chartValue); 
        }
    }
}

index.cshtml
@page  
<form>         
    <div class="form-group">         
        <label for="messageInput">Value</label>         
        <input class="form-control" placeholder="Enter a value" type="text" id="valueInput" />     
    </div>     
    <div class="form-group">         
        <input class="btn btn-primary" type="button" id="sendButton" value="Enter Value" />     
    </div> 
</form>

<div class="row">     
    <div class="col-12">         
        <hr />     
    </div> 
</div>

<div id="chartArea"> </div>


@section Scripts {
    <script src="~/js/microsoft/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chart.js"></script> } 

chartArea will display all the chart values received from the SignalR hub and plot them on the chart. 

 

Startup.cs
ConfigureServices(IServiceCollection services)
services.AddSignalR();
Configure(IApplicationBuilder app, IWebHostEnvironment env)
endpoints.MapHub<ChartHub>("/chartHub");

Shared/_Layout.cshtml 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    ...
    <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
</head>
<body>
     ...
    </footer>
    <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
            ....
</body>
</html>
Added a reference to the chartist.min.css / chartist.min.js file from the CDNJS (content delivery network – JavaScript) on GitHub

chart.js 
"use strict";

//created new line chart object using Chartist
var lineChart = new Chartist.Line('#chartArea',
    { labels: [], series: [[]] },
    { low: 0, showArea: true });

// Added in the Startup.cs file to map the incoming requests with the specified path to the specified SignalR Hub. 
var connection = new signalR.HubConnectionBuilder().withUrl("/chartHub").build();

//Disable send button until connection is established. document.getElementById("sendButton").disabled = true; 

//The ChartHub has been invoked, it in turn calls the ValueReceiver method on all connected clients. 
connection.on("ValueReceiver", function (chartValue) {
    //It checks to see if the chart value passed to it is a number and has a value. 
    if (chartValue && !isNaN(chartValue)) {
        //It then pushes this value onto the lineChart object and updates the chart. 
        lineChart.data.series[0].push(chartValue); lineChart.update();

        //Then it clears and focus to that text box, ready to receive the next value.
        document.getElementById("valueInput").value = "";
        document.getElementById("valueInput").focus();
    }
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) { return console.error(err.toString()); });

//Added an event listener on the sendButton click, will run for every click to add a value. 
document.getElementById("sendButton").addEventListener("click", function (event) {
    //Gets the text value and ensures it is parsed to a float.  
    var strValue = document.getElementById("valueInput").value;
    var chartValue = parseFloat(strValue);

     //Invokes the method on the server called ValueSender (ChartHub class). 
    connection.invoke("ValueSender", chartValue).catch(function (err) {
        return console.error(err.toString());
    }); event.preventDefault();
});

//Added an event listener on the enger key, called above sendbutton event
$('#valueInput').keypress(function (e) {
    var key = e.which; if (key === 13)  // the enter key code.     
    { $('#sendButton').click(); return false; }
});  



No comments:

Post a Comment