Today we are going to learn how to create razor pages and how to send run time value to the razor page using Signal R
Create a new .NET core web application
Add Signal R library by, Add Client-Side Library dialog in the project, for Provider select "unpkg" and select the latest version from the drop down
For Library, enter @aspnet/signalr@1,
Add a new folder to the project named as Hubs
The chat hub class inherits from HUb class that manages connections and messaging
The send message is called to send the message to all the clients. MyHub.cs file contains the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
//using System.Threading.Tasks;
namespace SignalRSample.Hubs
{
public class MyHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Nest step is to configure signalR
Add using SignalRSample.Hubs to startup.cs file
//Add the following line
services.AddSignalR();
app.UseSignalR(routes =>
{
routes.MapHub<MyHub>("/MyHub");
});
I will add this in the video description section for use
In Index.chtml page
Modify the Pages\Index.cshtml to follwing code
@page
@model SignalRSample.Pages.IndexModel
@{
}
In Index.chtml.cs
namespace SignalRSample.Pages
{
public class IndexModel : PageModel
{
public IActionResult OnGet()
{
return new RedirectToPageResult("/MyViewPage");
}
}
}
Before that we will add a new page named MyViewPage
We will modify the page and add the code
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
Runtime Data1..........<input type="text" id="TimeSpan" />
<br />
Runtime Data2...<input type="text" id="CurrentTime" />
</div>
</div>
</div>
We will add the folllowing code to MyViewPage.cshtml.cs
public void OnGet()
{
}
private readonly IHubContext<MyHub> _myhubContext;
public MyViewPageModel(IHubContext<MyHub> hubcontext)
{
_myhubContext = hubcontext;
Class1.UpdateAction = ReceiveMessage;
Class1.StartTimer();
}
public async void ReceiveMessage(string message1, string messag2)
{
await _myhubContext.Clients.All.SendAsync("ReceiveMessage", message1, messag2);
}
We will add a layout page for the new page added and will give the name as MyViewPageLayout.cshtml
We will add the follwong code to it
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/MyHub.js"></script>
</body>
</html>
Now we add a java script file named MyHub.js in wwwroot/js folder
Add the shown code in the js file
"use strict";
var connection = new signalR.HubConnectionBuilder()
.withUrl("/MyHub")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", function (msg1, msg2) {
document.getElementById("TimeSpan").value = msg1;
document.getElementById("CurrentTime").value = msg2;
});
connection.start().catch(function err()
{
return console.error(err.ToString());
});
What we basically did is we updated the two text boxes in MyViewPage with the messages received from Signal R callback
Now we will add a project that basically sends time and count message from a timer event, this will be our run time value that will be
sent to the razor page. The element gets updated without refreshing the whole page.
The data class is a C# dll project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace DataSource
{
public class Class1
{
//The action takes two parameters
public static Action<string, string> UpdateAction { get; set; }
//Update action is an event that is raised from class,
public static void Update(string noOftime, string time)
{
UpdateAction.Invoke(noOftime, time);
}
private static System.Timers.Timer myTimer;
public static void StartTimer()
{
SetMyTimer();
}
private static void SetMyTimer()
{
// Create a timer with a two second interval.
myTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
myTimer.Elapsed += OnTimedEvent;
myTimer.AutoReset = true;
myTimer.Enabled = true;
}
static long count = 1;
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
count++;
Update(count.ToString(), DateTime.Now.ToString());
}
}
}
So, lets complie the project and see it in demo.The demo video is at
https://youtu.be/EZ6dNa0-XHQ
Create a new .NET core web application
Add Signal R library by, Add Client-Side Library dialog in the project, for Provider select "unpkg" and select the latest version from the drop down
For Library, enter @aspnet/signalr@1,
Add a new folder to the project named as Hubs
The chat hub class inherits from HUb class that manages connections and messaging
The send message is called to send the message to all the clients. MyHub.cs file contains the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
//using System.Threading.Tasks;
namespace SignalRSample.Hubs
{
public class MyHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Nest step is to configure signalR
Add using SignalRSample.Hubs to startup.cs file
//Add the following line
services.AddSignalR();
app.UseSignalR(routes =>
{
routes.MapHub<MyHub>("/MyHub");
});
I will add this in the video description section for use
In Index.chtml page
Modify the Pages\Index.cshtml to follwing code
@page
@model SignalRSample.Pages.IndexModel
@{
}
In Index.chtml.cs
namespace SignalRSample.Pages
{
public class IndexModel : PageModel
{
public IActionResult OnGet()
{
return new RedirectToPageResult("/MyViewPage");
}
}
}
Before that we will add a new page named MyViewPage
We will modify the page and add the code
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
Runtime Data1..........<input type="text" id="TimeSpan" />
<br />
Runtime Data2...<input type="text" id="CurrentTime" />
</div>
</div>
</div>
We will add the folllowing code to MyViewPage.cshtml.cs
public void OnGet()
{
}
private readonly IHubContext<MyHub> _myhubContext;
public MyViewPageModel(IHubContext<MyHub> hubcontext)
{
_myhubContext = hubcontext;
Class1.UpdateAction = ReceiveMessage;
Class1.StartTimer();
}
public async void ReceiveMessage(string message1, string messag2)
{
await _myhubContext.Clients.All.SendAsync("ReceiveMessage", message1, messag2);
}
We will add a layout page for the new page added and will give the name as MyViewPageLayout.cshtml
We will add the follwong code to it
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/MyHub.js"></script>
</body>
</html>
Now we add a java script file named MyHub.js in wwwroot/js folder
Add the shown code in the js file
"use strict";
var connection = new signalR.HubConnectionBuilder()
.withUrl("/MyHub")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", function (msg1, msg2) {
document.getElementById("TimeSpan").value = msg1;
document.getElementById("CurrentTime").value = msg2;
});
connection.start().catch(function err()
{
return console.error(err.ToString());
});
What we basically did is we updated the two text boxes in MyViewPage with the messages received from Signal R callback
Now we will add a project that basically sends time and count message from a timer event, this will be our run time value that will be
sent to the razor page. The element gets updated without refreshing the whole page.
The data class is a C# dll project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace DataSource
{
public class Class1
{
//The action takes two parameters
public static Action<string, string> UpdateAction { get; set; }
//Update action is an event that is raised from class,
public static void Update(string noOftime, string time)
{
UpdateAction.Invoke(noOftime, time);
}
private static System.Timers.Timer myTimer;
public static void StartTimer()
{
SetMyTimer();
}
private static void SetMyTimer()
{
// Create a timer with a two second interval.
myTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
myTimer.Elapsed += OnTimedEvent;
myTimer.AutoReset = true;
myTimer.Enabled = true;
}
static long count = 1;
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
count++;
Update(count.ToString(), DateTime.Now.ToString());
}
}
}
So, lets complie the project and see it in demo.The demo video is at
https://youtu.be/EZ6dNa0-XHQ
Comments
Post a Comment