javascript function not called signalr hub method - signalr

<code>
`public void SendChat()
{
var clients = Clients.All;
clients.sendchat();
}`
</code>
it's hub method
<code> ` var chat = $.connection.echo;
chat.client.sendchat = function () {
console.log("signalR work!"); };`
</code>
it's client method
<code>
$('#sendMessage').click(function () {
$.ajax({ type: 'POST',
url: '/InboxUI/SendMessage',
data: { friendId: friend, message: text },
success: function (sendDate) {
date = sendDate.toLocaleString('tr-TR', { timeZone:
'UTC' });} }).done(function () {
hub.server.sendChat();});
});
</code>
it's server method
this sendChat method not called echoHub's sendchat method!
Help please.

1. Read tutorial
According your code I suggest you to start with the tutorial on: https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server
Why you make an ajax call? Where did you start the connection?... With signalr you should first start the connection to the server. After that you can send messages in both directions.
2. Samplecode
According the following sample from the previous link you can make a step forward:
Serverpart:
public class ContosoChatHub : Hub
{
public void NewContosoChatMessage(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
}
Client part:
var contosoChatHubProxy = $.connection.contosoChatHub;
// Define the methods which the client can call on the server. (Must be befor start!)
contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) {
console.log(userName + ' ' + message);
};
// Important you must start the connection
$.connection.hub.start()
.done(function(){
console.log('Now connected, connection ID=' + $.connection.hub.id);
})
.fail(function(){ console.log('Could not Connect!'); });
// You can call also method from client on server like (Connection must be established first!):
contosoChatHubProxy.server.newContosoChatMessage({ UserName: userName, Message: message}).done(function () {
console.log ('Invocation of NewContosoChatMessage succeeded');
}).fail(function (error) {
console.log('Invocation of NewContosoChatMessage failed. Error: ' + error);
});

Related

Can I set up 2 SignalR connections?

I have a basic chat app set up like so:
$(function () {
// Set up references for other functions to call
chatConnection = $.connection.chatHub;
// Set up callbacks before starting server connection
chatConnection.client.addNewMessageToPage = function (name, message) {
var prettyMessage = name + ':' + message;
$('#chatHistory').append(prettyMessage);
$("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
};
// Start up connection to server, set up events
$.connection.hub.start().done(function () {
$('#sendChatButton').click(function () {
// Call the Send method on the hub.
chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
// Clear text box and reset focus for next comment.
$('#chatBox').val('').focus();
});
});
});
This calls into my ChatHub.cs server side and I am getting and passing back messages as you would expect.
public void SendMessage(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
Now I want to add functionality. I Have a new class almost identical to my ChatHub called "GameHub" and it's job is to process moves instead of processing chat. So far I have something like this:
$(function () {
// Set up references for other functions to call
chatConnection = $.connection.chatHub;
gameConnection = $.connection.gameHub;
// Set up callbacks before starting server connection
chatConnection.client.addNewMessageToPage = function (name, message) {
var prettyMessage = name + ':' + message;
$('#chatHistory').append(prettyMessage);
$("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
};
gameConnection.client.receiveMove = function (name, move){
alert(name + ' played ' + move);
};
// Start up connection to server, set up events
$.connection.hub.start().done(function () {
$('#sendChatButton').click(function () {
// Call the Send method on the hub.
chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
// Clear text box and reset focus for next comment.
$('#chatBox').val('').focus();
});
$('#sendMoveButton').click(function () {
gameConnection.server.sendMove(getMove());
});
});
});
but nothing is making it to the server. Is this because I don't have it set up correct? Can signalR even support 2 hubs or should it be a single hub and "spoke" out from there to my 2 different functional areas?
You can but given that there is no performance difference it's simpler to have those functions in one hub. All data will hit all hubs as they all share the same connection.
As documented here.
You can check, since it's not provided, your game hub and method to ensure you have them named and cased properly on the server side. Possible issues...

Alexa Node.js Skills Kit - Need to return callback data before handler is completed

I'm attempting to build a simple Alexa skill to return data from an API using the [Node.js ASK] (https://developer.amazon.com/public/community/post/Tx213D2XQIYH864/Announcing-the-Alexa-Skills-Kit-for-Node-js). I have put the http get within a handler, but Alexa completes the handler before the callback asynchronously returns the API data.
I have been searching for answers, and my thoughts are currently:
not use node.js
figure out a way to synchronously get the data
Something simple I am missing
Core of the code:
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
alexa.registerHandlers(handler);
alexa.execute();
};
var handler = Alexa.CreateStateHandler(states.x, {
'intent': function() {
var options = {
host: baseURL,
path: pathURL
};
callback = function(response) {
var str = "";
response.on('data', function(piece) {
str += piece;
});
response.on('end', function() {
//does not get executed
this.emit(':tell', str, "test");
});
}
http.request(options, callback).end();
//this does get executed if I leave this here
this.emit(':tell'...);
};
I think you are having a scope issue.
try ...
response.on('end',() => {
this.emit(':tell', str, "test");
});

push notification to client when Firebase have a new child doesn't work

The code below is listening to new child added to Firebase then push it to client using socket.io, the problem that the socket.io doesn't fire the emit, any idea of how to make it send the data to the client?
Server:
FirebaseRef.endAt().limitToLast(1).on('child_added', function (childSnapshot, prevChildKey) {
console.log('new GPS point added ' + childSnapshot.val());
io.on('connection', function (socket) {
console.log('new GPS point added 2' + childSnapshot.val());
socket.volatile.emit('GpsPoint', childSnapshot.val());
socket.on('my other event', function (data) {
console.log(data);
});
}); });
Client: (inside angular Control)
var socket = io.connect('http://localhost:8080');
socket.on('GpsPoint', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
The socket connection should be done outside the Firebase function:
var sockets=[];
io.on('connection', function (socket) {
console.log('New socket: '+ socket);
sockets.push(socket);});
Inside the Firebase function we should use the sockets that already connected to an client :
FirebaseRef.endAt().limitToLast(1).on('child_added', function (childSnapshot, prevChildKey) {
for(var i=0;i<sockets.length;++i) {
console.log('Socket'+sockets[i]);
socket=sockets[i];
socket.volatile.emit('GpsPoint', childSnapshot.val());
}});

Extracting data out of http call [duplicate]

I'm using Meteor for first time and i'm trying to have a simple http call within a method so i can call this method from the client.
The problem is that this async call it's keep running even if i put it within a wrapper.
Client side:
Meteor.call('getToken', function(error, results) {
console.log('entered');
if(error) {
console.log(error);
} else {
console.log(results);
}
});
Server Side
Meteor.methods({
getToken: function(){
// App url
var appUrl = 'myAppUrl';
// Key credentials
var apiKey = 'mykey';
var apiSecret = 'mySecret';
function asyncCall(){
Meteor.http.call(
'POST',
appUrl,
{
data: {
key: apiKey,
secret: apiSecret
}
}, function (err, res) {
if(err){
return err;
} else {
return res;
}
}
);
}
var syncCall = Meteor.wrapAsync(asyncCall);
// now you can return the result to client.
return syncCall;
}
});
I'm always getting an undefined return.
If i log the response within the http.post call i'm geting the correct response.
If i try to log the syncCall i get nothing.
I would very appreciate any help on this.
You should use the synchronous version of HTTP.post in this case. Give something like this a try:
Meteor.methods({
getToken: function() {
var appUrl = 'myAppUrl';
var data = {apiKey: 'mykey', apiSecret: 'mySecret'};
try {
var result = HTTP.post(appUrl, {data: data});
return result;
} catch (err) {
return err;
}
}
});
Instead of returning the err I'd recommend determining what kind of error was thrown and then just throw new Meteor.Error(...) so the client can see the error as its first callback argument.

Using signalR to update Winforms UI

I have a form that was created on it's own UI thread running in the system tray which I need to manipulate with a signalR connection from the server which I believe to be running on a background thread. I'm aware of the need to invoke controls when not accessing them from their UI thread. I am able to manipulate (make popup in my case) using the following code that is called on form load but would like a sanity check as I'm fairly new to async:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var backgroundTask = connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
var uiTask = backgroundTask.ContinueWith(t =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
}, uiThreadScheduler);
});
}
Does this look OK? It's working on my local machine but this has the potential to be rolled out on every user machine in our business and I need to get it right.
Technically you should hook up to all notifications (using On<T>) before you Start listening. As far as your async work I'm not quite sure what you were trying to do, but for some reason your chaining the notification to your UI in On<T> to the backgroundTask variable which is the Task that was returned to you by the call to Start. There's no reason for that to be involved there.
So this is probably what you want:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
Task.Factory.StartNew(
() =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
},
CancellationToken.None,
TaskCreationOptions.None,
uiTaskScheduler);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
}

Resources