SignalR Asp.Net Core Send Async Hanging - asp.net-core

So its happened for the second time now. I believe what triggered the error was when I tried to do an update to my MongoDb server but I still don't know why this happens and I'd like to find out.
Basically I am sending json string data from a C# script to my front end with Signalr using this command:
_hubContext.Clients.All.SendAsync("ReceiveMail", json);
The issue is that my script keeps broadcasting this message (without any errors or issues) but my client side doesnt receive it (even though this broadcast has worked for weeks....). When I change the name of the broadcast to something different the data then makes its way to the client side perfectly.
Example:
//This broadcast worked fine for weeks but suddenly stopped working (without error)
_hubContext.Clients.All.SendAsync("ReceiveMail", json);
//Changed above broadcast to this and broadcast works perfectly fine again
_hubContext.Clients.All.SendAsync("ListenForMail", json);
TS Code:
constructor() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:57697/chat')
.build();
this.hubConnection
.start()
.then(() => this.table())
.catch(err => console.log('Error while establishing connection :('));
this.hubConnection.on('ReceiveMail', (mailJson: string) => {
this.loadEmail(mailJson);
});
this.hubConnection.on('ReceiveConnection', (msg: string) => {
console.log('Connection: ' + msg);
});
}
Anyone have any insight into this issue?

The method name the C# code is calling doesn't match the methods you are listening for in the TS code - but I'll assume that's a typo. If it's not, then you need to make sure the .on methods use the same method names as the C# code.
Another thing you do need to change is where you start the connection E.G.
constructor() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:57697/chat')
.build();
this.hubConnection.on('RetrieveMail', (mailJson: string) => {
this.loadEmail(mailJson);
});
this.hubConnection.on('ReceiveConnection', (msg: string) => {
console.log('Connection: ' + msg);
});
this.hubConnection
.start()
.then(() => this.table())
.catch(err => console.log('Error while establishing connection :('));
}
In the code above I have moved the .start() call to AFTER registering the on methods. You should do it this way because the hubconnection can start listening messages before the handlers are registered causing a race condition. Any messages sent won't be received if the on handler hasn't finished registering.

Related

React Native Signalr keeps saying connection needs to be initialized

I have this in my code:
useEffect(() => {
if(loaded2 == false){
connection = signalr.hubConnection('https://webambe.com/xxx');
connection.logging = true;
proxy = connection.createHubProxy('xxx');
//receives broadcast messages from a hub function, called "helloApp"
proxy.on('updateAll', (argOne) => {
setAlertNum(1);
//Here I could respond by calling something else on the server...
});
// atempt connection, and handle errors
connection.start().done(() => {
//console.log("dddd" + proxy.connectionState);
setLoaded2(true);
//console.log('Now connected, connection ID=' + connection.id);
setTrans(false);
}).fail(() => {
//console.log('Failed');
});
//connection-handling
connection.connectionSlow(() => {
//console.log('We are currently experiencing difficulties with the connection.')
});
connection.error((error) => {
const errorMessage = error.message;
let detailedError = '';
if (error.source && error.source._response) {
detailedError = error.source._response;
}
if (detailedError === 'An SSL error has occurred and a secure connection to the server cannot be made.') {
//console.log('When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14')
}
//console.debug('SignalR error: ' + errorMessage, detailedError)
});
}
});
When the code hits connection.start().done((), then the connection should be established but when I hit the send button that invokes the hub i get this error (setLoaded2(true) means that the connection is established):
Connection has not been fully initialized. Use .start().done() to run the logic after
connection has started.
But I have stated that says that connection has started here:
setLoaded2(true);
When this is called setTrans(false) is called to get rid of the transparent view so users can interact with the UI.
The hub connects successfully and I can run commands to the server and back, but I just want to know how to say when the connection is established so that the user can use the system.
I'm not sure if this is the way it shud be done but its working and staying connected when I move the connection and proxy outside my functional component:
connection = signalr.hubConnection('https://webambe.com/xxx');
connection.logging = true;
proxy = connection.createHubProxy('xxx');
when added this code outside the component the connection stays connected and no issues with signalr

How to get an extra client connection (nestjs-ioredis)

I'm using Redis on my Nestjs project. Therefor I'm making use of the package svtslv/nestjs-ioredis
I'm not very experienced yet in Nestjs (and Typescript). But I try to figure out how to get a second client connection (to the same database) because I want to work with a subscriber and publisher.
Something like next Node-implementation done in Nestjs when using this Nest-package:
const Redis = require("ioredis");
const redis = new Redis();
const pub = new Redis();
redis.subscribe("news", "music", (err, count) => {
// Now we are subscribed to both the 'news' and 'music' channels.
// `count` represents the number of channels we are currently subscribed to.
pub.publish("news", "Hello world!");
pub.publish("music", "Hello again!");
});
redis.on("message", (channel, message) => {
// Receive message Hello world! from channel news
// Receive message Hello again! from channel music
console.log("Receive message %s from channel %s", message, channel);
});
// There's also an event called 'messageBuffer', which is the same as 'message' except
// it returns buffers instead of strings.
redis.on("messageBuffer", (channel, message) => {
// Both `channel` and `message` are buffers.
});
RedisModule.forRoot({}, 'secondConnection')
#InjectRedis('secondConnection') private readonly redis: Redis
(Big thank you to the developer himself of this project)

SignalR Core call function when connection is established

When my client successfully connects to the hub, I want the client to immediately join a group. I have a method in my hub to do that, I just need an event handler for when the connection is established, just like
connection.start().done(
function () {
connection.invoke('JoinGroup', 'GroupName');
});
in SignalR for plain ASP.Net.
Can I do that or do I have to set a timer to do it after x seconds after the start(); call was made?
Edit:
I found out I can do
connection.start(
function (){
connection.invoke('JoinGroup', 'GroupName');
}
);
but it tells me that it Cannot send data if the connection is not in the 'Connected' State.
what do?
SignalR is notoriously difficult due to version mismatches etc.
Please see the following article: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio
In it, there's a section that specifies how to start (and wait for connection to be established):
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start().then(() => {
//try some stuff here :)
})
.catch(function (err) {
//failed to connect
return console.error(err.toString());
});
The javascript client uses promises that have to be resolved/rejected before you can use it.
The other option is to wrap inside async method and await the call (not sure if this will work correctly). Such as:
await connection.start();
//connection should be started now. beware of exceptions though

How to subscribe sailsjs rabbitmq-adapter

I have followed the steps explained in https://www.npmjs.com/package/sails-rabbitmq. And When I persist the data in Message DataModel, it gets saved in MongoDB as well as in RabbitMQ ( CloudAMQP.com ). But i am seeing this error message in the sails lift console.
sails-rabbitmq: waiting for orm hook to load before binding persistence handlers...
Any tips for avoiding this warning message?
As well my subscription program in api/services is not getting invoked.. For testing purpose, invoked this service from a sails controller, yet,
Message.getSubscribeSocket({ where: { stream: 'random' } })
.then(function (socket) {
socket.on('data', function (data) {
var message = JSON.parse(data);
// see, I told you it was "low-level"
// ...
});
});
Thanks in advance for your guidance

WCF, multiple async calls

I have a View in Windows Form that needs to execute multiple WCF calls async.
The problem is that when the second callback return, WCF raises an error of timeout or a generic exception. If I execute them sync everything is fine.
This is the code:
Proxy.Open();
Proxy.BeginStepOne(ar =>
{
// do something
});
//This raises an Exception
Proxy.BeginStepTwo(ar =>
{
// do something
});
Proxy.Close();
Is there a better way?