SignalR client hangs on start() on the second session - winforms

I have a ASP.Net core web-app published to IIS, the web-app uses SignalR to display notifications. I also have a desktop windows forms application is used to connect to a fingerprint device and is also used to send notification to the web-app that a person just entered so i can display a notification on the web-app about that person.
And everything works fine with one session of the web-app, but if i open another tab for example or browse the web-app from another computer the second one hangs on the connection.start() until i close the first session. and this drives me crazy.
Here is the code.
ASP.net core Hub
public class SignalRServer : Hub
{
public async Task displayNotification()
{
await Clients.All.SendAsync("displayNotification");
}
}
Javascript client code
let connection = new signalR.HubConnectionBuilder()
.withUrl("/SignalRServer")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("displayNotification", () => {
getLatestNotification();
});
connection.start();
The windows forms app has two projects the first one is .NET framework 4.5 which uses the fingerprint device API to connect to the device. And the second project is .NET standard which contains the SignalR HubConnection code to connect to server, and HubConnection is used in the first project to connect and send notifications.
windows forms app Hub connection code in .NET standard
public class HubNotification
{
HubConnection connection;
public HubNotification(string Ip)
{
connection = new HubConnectionBuilder()
.WithUrl(Ip + "/SignalRServer")
.Build();
connection.StartAsync();
}
public async Task ConnectAsync()
{
await connection.StartAsync();
}
public void SendNotAsync()
{
connection.InvokeAsync("displayNotification");
}
}
then in the first project i use ConnectAsync and SendNotAsync to send notification when i person enters.
I don't think there is a problem with the desktop app but i posted the code anyway.
I have read that there is a problem with signalR and multiple session but didn't find any solution.

Related

Disconnect from SignalR at the time of logout - ReactJS & Entity Framework

I'm facing the issue regarding to disconnecting from signalR. I want to know that is there some way to disconnect the connection that is established between my frontend and the backend when i logout from the app.
Following npm package of signalR we are using on frontend:
#aspnet/signalr: 1.1.4
U can send stop connection from client side like this
const logoutBtn=()=>{
connection.stop() // This line will send a disconnected call to the server
Logout()
}
// Server code
public override async Task OnDisconnectedAsync(Exception? exception)
{
Context.ConnectionId // U will get the connection id that is disconnected
}

Identity server registration doesn't redirect back to React app

I have an ASP.NET Core backend with a React frontend hosted in different origins.
The ASP.NET core backend is configured to use the inbuilt identity server:
// Startup
public void ConfigureServices(IServiceCollection services)
{
...
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
...
}
I have added the OidcConfigurationController that the identity server expects:
public class OidcConfigurationController : Controller
{
public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider)
{
ClientRequestParametersProvider = clientRequestParametersProvider;
}
public IClientRequestParametersProvider ClientRequestParametersProvider { get; }
[HttpGet("_configuration/{clientId}")]
public IActionResult GetClientRequestParameters([FromRoute]string clientId)
{
var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId);
return Ok(parameters);
}
}
I have also added the following settings in appsettings.json that the identity server reads:
...
"IdentityServer": {
"Clients": {
"WebApplication1": {
"Profile": "SPA",
"RedirectUri": "http://localhost:3000/authentication/login-callback",
"LogoutUri": "http://localhost:3000/authentication/logout-callback"
}
}
},
...
The React app is hosted at http://localhost:3000 and uses oidc-client to interact with the ASP.NET Core server. The frontend code appears to correctly request a sign in passing the correct return url:
The ASP.NET Core authentication pages are successfully shown:
But if you post a new registration, ASP.NET Core redirects to its root rather than http://localhost:3000:
Is there anything I've missed or does the inbuilt ASP.NET identity only work if the client is hosted in the same origin?
Any help appreciated.
You just miss your return url during roundtrip to Account/Register. That has nothing to do with origins. Check with a pure signin -- that should work out of the box.
New account registration is not what Identityserver is responsible for. You have to handle that yourself. You need to pass through your return url each time you redirect, starting from the "Register" button on your login form and ending at your [HttpPost]Register action. Most likely you would like to keep that url even when you user cancels the registration in the middle and decides to signin with an existing account.
See this question/answer for the reference.

Azure Mobile Service with on-premise SQL Server for Cordova application

I'm trying Azure Solutions because i want to build a cordova application which can handle offline/online synchronisation with an existing MS SQL Server.
On Azure, I just created a mobile application hosting xxxx.azurewebsites.net on which i connected an on-premise MS SQL Server with Hybrid Connection and biztalk service (the hybrid connection agent is installed on my MS SQL Server), everything went fine (the status of the hybrid connection on Azure is "connected").
I built a cordova application with the plugin "cordova-plugin-ms-azure-mobile-apps" correctly installed, this is my testing code :
$(document).on("deviceready", function () {
/********** TEST SYNCHRO **********/
// WindowsAzure Mobile App Offline Synchronization
var client, // Connection to the Azure Mobile App backend
todoItemTable, // Reference to a table endpoint on backend
syncContext; // Reference to offline data sync context
client = new WindowsAzure.MobileServiceClient('http://xxxxxxxx.azurewebsites.net/');
var store = new WindowsAzure.MobileServiceSqliteStore('store.db');
store.defineTable({
name: 'Operation',
columnDefinitions: {
UID: 'string',
Nom: 'string',
Reference: 'String'
}
});
//// Get the sync context from the client
syncContext = client.getSyncContext();
//// Initialize the sync context with the store
syncContext.initialize(store).then(function () {
// Get the local table reference.
todoItemTable = client.getSyncTable('Operation');
syncContext.pushHandler = {
onConflict: function (pushError) {
// Handle the conflict.
console.log("Sync conflict! " + pushError.getError().message);
// Update failed, revert to server's copy.
pushError.cancelAndDiscard();
},
onError: function (pushError) {
// Handle the error
// In the simulated offline state, you get "Sync error! Unexpected connection failure."
console.log("Sync error! " + pushError.getError().message);
}
};
// Call a function to perform the actual sync
syncBackend();
});
function syncBackend() {
// Pull items from the Azure table after syncing to Azure.
syncContext.pull(new WindowsAzure.Query('Operation'));
}
/********** FIN TEST SYNCHRO **********/
});
When i launch the app on my smartphone i can see a 404 from this requested URL : http://xxxxxx.azurewebsites.net/tables/Operation?$filter.....
with this message : "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
Am I missing something on the backend ?
How can I make this "/tables/" API responding on my Azure Mobile App Service ?
Where do i need to setup on which database i need to connect ?? (as i only give the table name ???)
Thanks in advance !

Consuming Signal R service in Desktop application

I am new to SignalR, I want to develop a service using SingalR API’s and Host as selfhost\IIS, now my doubt is How can I consume these message in Client side my client application will be Windows(Desktop) applications.
Main intention is to send Notification from SignalR service to Clients. I would like to know is this achievable.
Please share any tutorials link or similar projects URL
Thanks in Advance
What I do is use .Net events , to wrap the SignlR client functions and connect to the desktop application call backs . like so :
public class Client
{
public delegate void OnReciveMessage(Object message);
public event OnReciveMessage MessageRecivedEvent;
public void ReciveMessage(Object message)
{
if (MessageRecivedEvent != null)
{
MessageRecivedEvent(message);
}
}
}
Yes it's possible. You can connect to a Signal R hub from webclient or winformsclient.
Useful information on this links:
SignalR Chat App in WinForm With Remote Clients
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host

How to abort controller action in play framework 2.1 when client cancel request or client socket is closed?

I am testing play framework 2.1 to check what happen when client cancel request or socket is closed from client side. I created this simple program:
package controllers;
import play.;
import play.mvc.;
import views.html.*;
public class Application extends Controller {
public static Result index() {
try{
for(int i=0;i<1000;i++){
Thread.sleep(10000);
System.out.println(i+"\n");
}
}catch(Exception e){
System.out.println("\nexcepción capturada");
}
return ok(index.render("Your new application is ready."));
}
}
If I cancel request from client (google chrome) the loop isn't aborted. I think this could be a problem in real world application, not making a loop, but doing a "heavy" query to database.
Since there was no answer I asked on the google group for play
https://groups.google.com/forum/?hl=en#!topic/play-framework/POvFA3moXug
and here is what James Roper from Typesafe said:
Play offers no such feature. However, there are other ways to achieve
the same thing, for example, if you have a long running request, you
could do it as a websockets request, which let's you easily detect
when the client navigates to a different page.
The latest release as of today is play-2.2.0-RC1 (in case they add support later).

Resources