I am using SqlDependecy
with signalR
to push notifications to client browser when there is some database changes, I followed this and this post an
In shared hosting because they restrict some features, so i was unable to use SqlDependency
, but here is my solution to Play notifications without SqlDependency in asp mvc
If you are new signalR
, then first try this post to create simple chat web application.
My requirement was to play notifications when new sales happens in shops
1. Create SignalR Server Hub
SignalR server hub class that sends messages to all clients browser.
[HubName("PascalCaseNewSalesHub")]
public class NewSalesHub : Hub
{
public void Send(string shopid)
{
// Call the alertNewSalesToPage method to update clients.
Clients.All.alertNewSalesToPage(shopid);
}
}
2. Javascript Send Method in PlaceOrder View
When a customer places new order for this shop then the following javascript code Calls the Send method on the server hub to update clients.
<script>
$(function ()
{
// Reference the auto-generated proxy for the hub.
var chat = $.connection.PascalCaseNewSalesHub;
var thisShopID = @(ViewBag.ShopID);
// Start the connection.
$.connection.hub.start().done(function () {
// Call the Send method on the hub to send this shops ID
chat.server.send(thisShopID);
});
});
3. Javascript Client Call Back Method in ShopSales View
The hub class on the server calls this javascript function to push content updates to each client.
<script type="text/javascript">
$(function ()
{
console.log('Page loaded');
// Declare a proxy to reference the hub.
var notifications = $.connection.PascalCaseNewSalesHub;
if (notifications != null)
{
console.log('connected to SalesHUB proxy');
}
var thisShopID = @(ViewBag.ShopID);
// Create a function that the hub can call back to alert new sales.
notifications.client.alertNewSalesToPage = function (shopid)
{
// check if sales happened for this shop then play notification
if (shopid == thisShopID)
{
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
$('#loading').show();
// Partial View to Update LatestSales for this Shop
$("#new-Sales").load('@Url.Action("GetLatestSales", "Shop")')
$('#loading').hide();
console.log('New Sale happened, Notification Played');
}
};
// Start the connection.
$.connection.hub.start().done(function () {
console.log('signalR connection started');
}).fail(function (e) {
alert(e);
});
});
</script>
Used Howler.js
Plugin to play notification , check this post.
Hope helps someone.