SignalR Service
This example demonstrates real-time data update in a DataGrid bound to a SignalR service. Access to the service is configured in a CustomStore.
The CustomStore fetches the remote dataset at launch and keeps its local copy. Whenever the remote dataset changes, the server calls a client-side function that updates the local copy of the dataset (updateStockPrices
in this demo). This function uses the store's push(changes) method.
For server-side configuration, refer to the ASP.NET MVC version of this demo.
For more information about integration with push services, refer to the following help topic: Integration with Push Services.
NOTE
Data used in this demo is for demonstration purposes only.
Feel free to share demo-related thoughts here.
If you have technical questions, please create a support ticket in the DevExpress Support Center.
Thank you for the feedback!
If you have technical questions, please create a support ticket in the DevExpress Support Center.
Backend API
<template>
<div v-if="connectionStarted">
<DxDataGrid
id="gridContainer"
:data-source="dataSource"
:repaint-changes-only="true"
:highlight-changes="true"
:show-borders="true"
>
<DxColumn
:width="115"
data-field="lastUpdate"
data-type="date"
format="longTime"
/>
<DxColumn
data-field="symbol"
/>
<DxColumn
data-field="price"
data-type="number"
format="#0.####"
cell-template="priceCellTemplate"
/>
<DxColumn
:width="140"
data-field="change"
data-type="number"
format="#0.####"
cell-template="changeCellTemplate"
/>
<DxColumn
data-field="dayOpen"
data-type="number"
format="#0.####"
/>
<DxColumn
data-field="dayMin"
data-type="number"
format="#0.####"
/>
<DxColumn
data-field="dayMax"
data-type="number"
format="#0.####"
/>
<template #priceCellTemplate="{ data: cellData }">
<PriceCell :cell-data="cellData"/>
</template>
<template #changeCellTemplate="{ data: cellData }">
<ChangeCell :cell-data="cellData"/>
</template>
</DxDataGrid>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import {
DxDataGrid,
DxColumn,
} from 'devextreme-vue/data-grid';
import CustomStore from 'devextreme/data/custom_store';
import { HubConnectionBuilder, HttpTransportType } from '@aspnet/signalr';
import PriceCell from './PriceCell.vue';
import ChangeCell from './ChangeCell.vue';
const connectionStarted = ref(false);
const dataSource = ref<CustomStore | null>(null);
onMounted(() => {
const hubConnection = new HubConnectionBuilder()
.withUrl('https://js.devexpress.com/Demos/NetCore/liveUpdateSignalRHub', {
skipNegotiation: true,
transport: HttpTransportType.WebSockets,
})
.build();
const store = new CustomStore({
load: () => hubConnection.invoke('getAllStocks'),
key: 'symbol',
});
hubConnection
.start()
.then(() => {
hubConnection.on('updateStockPrice', (data) => {
store.push([{ type: 'update', key: data.symbol, data }]);
});
dataSource.value = store;
connectionStarted.value = true;
});
});
</script>
<style>
#gridContainer span.current-value {
display: inline-block;
margin-right: 5px;
}
#gridContainer span.diff {
width: 50px;
display: inline-block;
}
#gridContainer .inc {
color: #2ab71b;
}
#gridContainer .dec {
color: #f00;
}
#gridContainer .inc .arrow,
#gridContainer .dec .arrow {
display: inline-block;
height: 10px;
width: 10px;
background-repeat: no-repeat;
background-size: 10px 10px;
}
#gridContainer .inc .arrow {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADKSURBVHjaYtTaLs1ABEiG0nPRJa56PEHhsxBhmCUQT4OyrwHxcXyKmQgYJgHE64CYDYrXQcXIMhCbAcgWkGzgNKh38QUB0QamIUUErkhKI9ZAGyCeTERkTYaqxWsgKA2txhdG6GGsvUNGGpeBRMUiGhCFGsqGzUBQQJsxkA5AemaiG5hDIBIIgQSgK0FmMDACs549kN5FZLjhA7+A2A2U9YSAOBeLAk4gnoBDczoOcSFGPIUDPxB/wCHHiKtwYGKgMhg1cBAaCBBgAJTUIL3ToPZfAAAAAElFTkSuQmCC');
}
#gridContainer .dec .arrow {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADJSURBVHjaYvzPgBfgkhYA4o8QFahKmBioDEYNHIQGsgBxIBCLkqgvAYi/g1mMjMjir0EJzR6If/6HpChKMMgMe3DKBeIcKhiY8x/MYoDj+RQYNgdkGLqBbEB8kgzDToL1YjEQhKWB+BUJhj0H64Eahs1AELYhMpJ+gtUiGYbLQBBOI8LANLBaIg1kAAc0vkiAqSPBQFAkHcNi2DGoHMkGgrAENOCRI0ECRQ2JBoKwJTQCfkLZDPgMZPxPXN5NhtJzMSsJVBMAAgwAyWSY2svfmrwAAAAASUVORK5CYII=');
}
</style>
<template>
<div :class="{ inc: cellData.data.change > 0, dec: cellData.data.change < 0 }">
<span class="current-value">{{ cellData.text }}</span>
<span class="arrow"/>
<span class="diff">{{ cellData.data.percentChange.toFixed(2) }}%</span>
</div>
</template>
<script setup lang="ts">
import { ColumnCellTemplateData } from 'devextreme/ui/data_grid';
defineProps<{
cellData: ColumnCellTemplateData
}>();
</script>
<template>
<div :class="{ inc: cellData.data.change > 0, dec: cellData.data.change < 0 }">
<span>{{ cellData.text }}</span>
</div>
</template>
<script setup lang="ts">
import { ColumnCellTemplateData } from 'devextreme/ui/data_grid';
defineProps<{
cellData: ColumnCellTemplateData
}>();
</script>
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
<!DOCTYPE html>
<html>
<head>
<title>DevExtreme Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/23.1.5/css/dx.light.css" />
<script type="module">
import * as vueCompilerSFC from "https://unpkg.com/@vue/compiler-sfc@3.3.4/dist/compiler-sfc.esm-browser.js";
window.vueCompilerSFC = vueCompilerSFC;
</script>
<script src="https://unpkg.com/typescript@3.9.10/lib/typescript.js"></script>
<script src="https://unpkg.com/core-js@2.6.12/client/shim.min.js"></script>
<script src="https://unpkg.com/systemjs@0.21.3/dist/system.js"></script>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript">
System.import("./index.js");
</script>
</head>
<body class="dx-viewport">
<div class="demo-container">
<div id="app"> </div>
</div>
</body>
</html>
window.exports = window.exports || {};
window.config = {
transpiler: 'plugin-babel',
meta: {
'*.vue': {
loader: 'vue-loader',
},
'*.ts': {
loader: 'demo-ts-loader',
},
'*.svg': {
loader: 'svg-loader',
},
'devextreme/localization.js': {
'esModule': true,
},
},
paths: {
'root:': '../../../../../',
'npm:': 'https://unpkg.com/',
},
map: {
'vue': 'npm:vue@3.3.4/dist/vue.esm-browser.js',
'vue-loader': 'npm:dx-systemjs-vue-browser@1.1.1/index.js',
'demo-ts-loader': 'root:utils/demo-ts-loader.js',
'svg-loader': 'root:utils/svg-loader.js',
'@aspnet/signalr': 'npm:@aspnet/signalr@1.0.27/dist/cjs',
'tslib': 'npm:tslib@2.3.1/tslib.js',
'mitt': 'npm:mitt/dist/mitt.umd.js',
'rrule': 'npm:rrule@2.6.4/dist/es5/rrule.js',
'luxon': 'npm:luxon@1.28.1/build/global/luxon.min.js',
'es6-object-assign': 'npm:es6-object-assign@1.1.0',
'devextreme': 'npm:devextreme@23.1.6/cjs',
'devextreme-vue': 'npm:devextreme-vue@23.1.6',
'jszip': 'npm:jszip@3.7.1/dist/jszip.min.js',
'devextreme-quill': 'npm:devextreme-quill@1.6.2/dist/dx-quill.min.js',
'devexpress-diagram': 'npm:devexpress-diagram@2.2.2/dist/dx-diagram.js',
'devexpress-gantt': 'npm:devexpress-gantt@4.1.49/dist/dx-gantt.js',
'@devextreme/runtime': 'npm:@devextreme/runtime@3.0.12',
'inferno': 'npm:inferno@7.4.11/dist/inferno.min.js',
'inferno-compat': 'npm:inferno-compat/dist/inferno-compat.min.js',
'inferno-create-element': 'npm:inferno-create-element@7.4.11/dist/inferno-create-element.min.js',
'inferno-dom': 'npm:inferno-dom/dist/inferno-dom.min.js',
'inferno-hydrate': 'npm:inferno-hydrate@7.4.11/dist/inferno-hydrate.min.js',
'inferno-clone-vnode': 'npm:inferno-clone-vnode/dist/inferno-clone-vnode.min.js',
'inferno-create-class': 'npm:inferno-create-class/dist/inferno-create-class.min.js',
'inferno-extras': 'npm:inferno-extras/dist/inferno-extras.min.js',
'plugin-babel': 'npm:systemjs-plugin-babel@0.0.25/plugin-babel.js',
'systemjs-babel-build': 'npm:systemjs-plugin-babel@0.0.25/systemjs-babel-browser.js',
// Prettier
'prettier/standalone': 'npm:prettier@2.8.4/standalone.js',
'prettier/parser-html': 'npm:prettier@2.8.4/parser-html.js',
},
packages: {
'devextreme-vue': {
main: 'index.js',
},
'devextreme': {
defaultExtension: 'js',
},
'devextreme/events/utils': {
main: 'index',
},
'devextreme/events': {
main: 'index',
},
'@aspnet/signalr': {
main: 'index.js',
defaultExtension: 'js',
},
'es6-object-assign': {
main: './index.js',
defaultExtension: 'js',
},
},
packageConfigPaths: [
'npm:@devextreme/*/package.json',
'npm:@devextreme/runtime@3.0.12/inferno/package.json',
],
babelOptions: {
sourceMaps: false,
stage0: true,
},
};
System.config(window.config);
using System.Collections.Generic;
using DevExtreme.MVC.Demos.Models.SignalR;
using Microsoft.AspNet.SignalR;
namespace DevExtreme.MVC.Demos.Hubs {
public class LiveUpdateSignalRHub : Hub {
private readonly StockTicker _stockTicker;
public LiveUpdateSignalRHub() {
_stockTicker = StockTicker.Instance;
}
public IEnumerable<Stock> GetAllStocks() {
return _stockTicker.GetAllStocks();
}
}
}
using System;
using System.Collections.Generic;
using System.Threading;
using DevExtreme.MVC.Demos.Hubs;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace DevExtreme.MVC.Demos.Models.SignalR {
public class StockTicker {
public readonly static StockTicker Instance = new StockTicker(GlobalHost.ConnectionManager.GetHubContext<LiveUpdateSignalRHub>().Clients);
private readonly IEnumerable<Stock> _stocks;
private IHubConnectionContext<dynamic> Clients { get; set; }
private readonly TimeSpan _updateInterval = TimeSpan.FromMilliseconds(500);
private readonly Random _updateOrNotRandom = new Random();
private readonly Timer _timer;
private readonly object _updateStockPricesLock = new object();
static readonly Random random = new Random();
private StockTicker(IHubConnectionContext<dynamic> clients) {
Clients = clients;
_stocks = GenerateStocks();
_timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
}
public IEnumerable<Stock> GetAllStocks() {
return _stocks;
}
static IEnumerable<Stock> GenerateStocks() {
return new[] {
new Stock(37.95M) { Symbol = "MSFT", DayOpen=36.5M, LastUpdate = DateTime.Now },
new Stock(24.85M) { Symbol = "INTC", DayOpen=24.9M, LastUpdate = DateTime.Now },
new Stock(22.99M){ Symbol = "CSCO", DayOpen=22.7M, LastUpdate = DateTime.Now },
new Stock(30.71M){ Symbol = "SIRI", DayOpen=30.7M, LastUpdate = DateTime.Now },
new Stock(58.73M){ Symbol = "AAPL", DayOpen=54.9M, LastUpdate = DateTime.Now },
new Stock(110M){ Symbol = "HOKU", DayOpen=121.2M, LastUpdate = DateTime.Now },
new Stock(38.11M){ Symbol = "ORCL", DayOpen=37.9M, LastUpdate = DateTime.Now },
new Stock(17.61M) { Symbol = "AMAT", DayOpen=17.5M, LastUpdate = DateTime.Now },
new Stock(40.80M){ Symbol = "YHOO", DayOpen=39.9M, LastUpdate = DateTime.Now },
new Stock(31.85M){ Symbol = "LVLT", DayOpen=32.9M, LastUpdate = DateTime.Now },
new Stock(20.63M){ Symbol = "DELL", DayOpen=17.9M, LastUpdate = DateTime.Now },
new Stock(63.70M) { Symbol = "GOOG", DayOpen=55.9M, LastUpdate = DateTime.Now }
};
}
private void UpdateStockPrices(object state) {
lock(_updateStockPricesLock) {
foreach(var stock in _stocks) {
if(TryUpdateStockPrice(stock)) {
BroadcastStockPrice(stock);
}
}
}
}
private bool TryUpdateStockPrice(Stock stock) {
var r = _updateOrNotRandom.NextDouble();
if(r > .1) {
return false;
}
stock.Update();
return true;
}
private void BroadcastStockPrice(Stock stock) {
Clients.All.updateStockPrice(stock);
}
}
}
using System;
namespace DevExtreme.MVC.Demos.Models.SignalR {
public class Stock {
readonly decimal _initPrice;
public Stock(decimal price) {
Price = price;
DayMax = price;
DayMin = price;
_initPrice = Price;
}
public string Symbol { get; set; }
public decimal Price { get; set; }
public decimal DayMax { get; set; }
public decimal DayMin { get; set; }
public decimal DayOpen { get; set; }
public DateTime LastUpdate { get; set; }
public decimal Change {
get {
return Price - DayOpen;
}
}
public double PercentChange {
get {
return (double)Math.Round(Change * 100 / DayOpen, 2);
}
}
public void Update() {
var isNewDay = LastUpdate.Day != DateTime.Now.Day;
var change = GenerateChange();
var newPrice = _initPrice + _initPrice * change;
Price = newPrice;
LastUpdate = DateTime.Now;
if(Price > DayMax || isNewDay)
DayMax = Price;
if(Price < DayMin || isNewDay)
DayMin = Price;
}
static Random random = new Random();
decimal GenerateChange() {
return (decimal)random.Next(-200, 200) / 10000;
}
}
}