Signalr stops doing Callbacks after some minutes - asp.net

I am using signalr 0.4 on an aspx-Page,
var hub = $.connection.FooHub;
hub.disconnected(function () {
log("Server has disconnected");
});
hub.ShowInfo = function (Info) { .... }
$("#Button1").click(function () {
hub.FooFunction('foo');
});
$.connection.hub.start();
The Hub is defined as :
public class FooHub : Hub, IDisconnect
{
~FooHub()
{
log.Debug("FooHub Destroy");
}
public FooHub()
{
log.Debug("FooHub Startup");
}
public bool FooFunction(string stuff)
{
log.Debug("Hub FooFunction");
Clients.ShowInfo(someInfo);
return true;
}
public Task Disconnect()
{
// Query the database to find the user by it's client id etc. etc.
MyController.Disconnect(Context.ConnectionId);
log.Debug("Hub Disconnnect " + Context.ConnectionId);
return null;
}
......
}
When i open the page and immediately click on Button1
it calls the Hub which in turn calls the ShowInfo-function on the page.
With Firebug i can see that signalr is using long-polling for the communcation.
So everything works as expected.
But when i then wait a couple of minutes
i see that
FooHub is destroyed
Disconnect is called in the Hub,
however on the Page there is no new connection
Firebug shows the old one still being executed
and when i then click on the Button -
FooFunction is called (i see a new connection in firebug)
FooHub is created
FooFunction is executed in the Hub (there is a line in the Log)
but ShowInfo is not executed
Is this a bug in SignalR or do i have to do something else to get the ShowInfo-call?
Update (Possible answer):
It was using a Forever-Frame and not long-polling.
In addition, the problem seems to happen mostly when using mobile internet (usb-stick) and Firefox.
Changing the transport to long-Polling seems to fix this issue.

You mention switching to long polling instead of using a forever frame but didn't say how to do that. You can specify which transports to try when starting the connection.
connection.start({ transport: ['longPolling','webSockets'] });
See https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client for more options.

Did u look at this https://github.com/SignalR/SignalR/wiki/Configuring-SignalR
Try this see. To me as per your code every thing seems to be OK. Also can you test the same in Chrome and see whats happening.

Related

Why is my signalR proxy info not generated correctly?

Ok so im using the latest version of signalR (2.10.0 at this moment in time) and I am adding a new hub to my application, I don't want to use it yet nor do I intend to in it's own right I simply want to use this hub to template some basic crud stuff so I don't have to rewrite it all the time.
The adding of this hub to my project causes signalR to fail and not correctly generate the proxy stuff on the client.
Can anyone explain why this would happen?
Here's my code ...
Existing hub:
public class NotificationHub : Hub { ... }
New hub:
public class Hub<T> : Hub { ... }
Client side code that breaks by adding new hub ...
$(function () {
var notifications = $.connection.notificationHub;
notifications.client.success = function (message) <--- js exception here
{ ... };
});
The js exception reads "cannot read property client of undefined".
EDIT:
Looking closer at the details in chromes tools I can see that the client side error is due to : "GET http://localhost/signalr/hubs 500 (Internal Server Error)"
Question is, how do I fix this as attaching the debugger does not let me handle / see where this error is occurring.
I'm guessing this is in the signalR code somewhere.
Is there an issue with generics in signalR ?
Ah ok ...
Since I never have any intention of actually creating a Hub only its sub types I made it abstract.
This appears to resolve the resolve the problem.
public abstract class Hub<T> : Hub { ... }

SignalR connect error

I use SignalR 2.0.0 Win2012 iis8 with two environment with two different ips.
one environment service is up and second is down(purposely)
use websocket protocol.
i have the following scenario:
When i connect to first environment and want to connect to the second.
i disconnected from first environment and try connect to second environment i get error(its correct behavior)
i try to reconnect back to the first environment but I get still the same error.
the error is "Error during negotiation request."
after refresh the browser i can connect success again to first environment.
What am i doing wrong?
this is part of my code:
function connect(host)
{
var hubConnection = $.hubConnection.('');
hubConnection.url = host;
hubConnection.start()
.done(open)
.fail(error);
}
function open()
{
console.log('login success')
}
function disconnect()
{
var self = this,
hubConnection = $.hubConnection("");
console.log('disconnect ')
hubConnection.stop(true, true);
}
function error(error)
{
var self = this,
hubConnection = $.hubConnection("");
console.log('connection error ')
if(error && hubConnection.state !== $.connection.connectionState.connected)
{
.....
.....
//logic detemninate wich environment ip was previous
connect(environment ip)
}
}
//occured when button disconnect clicked
function disconnectFromFirstEnvironmentAndConnectToSecond()
{
disconect();
connect(second environment ip);
}
.....
.....
connect(first environment ip);
You're not retaining your first connection reference.
Aka you create a HubConnection and then never capture it in a scope that can be used later; therefore when you disconnect later the connection.stop does nothing because it's not calling stop on the HubConnection that was originally started.
This could ultimately lead to you having too many concurrently open requests which will then not allow you to negotiate with a server hence your error.
I'd recommend fixing how you stop/start connections. Next if the issue still occurs I'd inspect the network traffic to ensure that valid requests are being made.

Signalr (1.0.0-alpha2) Hubs - Can you add client functions after connection has been started?

Using Signalr (1.0.0-alpha2), I want to know if it is possible to add client functions after a connection has been started.
Say I create my connection and grab the proxy. Then I add some Server Fired client functions to the hub to do a few things. Then I start my connection. I then want to add some more Server Fired functions to my hub object. Is this possible?
var myHub= $.connection.myHub;
myHub.SomeClientFunction = function() {
alert("serverside called 'Clients.SomeClientFunction()'");
};
$.connection.hub.start()
.done(function() {
myHub.SomeNewClientFunction = function() {
alert("serverside called 'Clients.SomeNewClientFunction()'");
}
})
This example is not realistic, but I basically want to send my 'myHub' variable to a different object after the hub is started to subscribe to new events that the original code did not care for.
Real Life Example: A dashboard with a number of different hub events (new site visits, chat message, site error). I 'subscribe' after the connection has started and then pass my hub proxy to all of my different UI components to handle their specific 'message types'. Should I create separate Hubs for these or should I be able to add more Server Fired client functions on the fly?
Yes you can. Use the .on method.
Example:
myHub.on('somethingNew', function() {
alert("This was called after the connection started!");
});
If you want to remove it later on use the .off method.
I have the exact same situation. You might want to consider adding another layout of abstraction if you're trying to call it from multiple places.
Here's a preliminary version of what I've come up with (typescript).
I'll start with the usage. SignalRManager is my 'manager' class that abstracts my debuggingHub hub. I have a client method fooChanged that is triggered on the server.
Somewhere in the module that is using SignalR I just call the start method, which is not re-started if already started.
// ensure signalR is started
SignalRManager.start().done(() =>
{
$.connection.debuggingHub.server.init();
});
Your 'module' simply registers its callback through the manager class and whenever the SignalR client method is triggered your handler is called.
// handler for foo changed
SignalRManager.onFooChanged((guid: string) =>
{
if (this.currentSession().guid == guid)
{
alert('changed');
}
});
This is a simple version of SignalRManager that uses jQuery $.Callbacks to pass on the request to as many modules as you have. Of course you could use any mechanism you wanted, but this seems to be the simplest.
module RR
{
export class SignalRManager
{
// the original promise returned when calling hub.Start
static _start: JQueryPromise<any>;
private static _fooChangedCallback = $.Callbacks();
// add callback for 'fooChanged' callback
static onfooChanged(callback: (guid: string) => any)
{
SignalRManager._fooChangedCallback.add(callback);
}
static start(): JQueryPromise<any>
{
if (!SignalRManager._start)
{
// callback for fooChanged
$.connection.debuggingHub.client.fooChanged = (guid: string) =>
{
console.log('foo Changed ' + guid);
SignalRManager._fooChangedCallback.fire.apply(arguments);
};
// start hub and save the promise returned
SignalRManager._start = $.connection.hub.start().done(() =>
{
console.log('Signal R initialized');
});
}
return SignalRManager._start;
}
}
}
Note: there may be extra work involved to handle disconnections or connections lost.

Get full URL inside SignalR hub

I'm developing an user tracking solution using SignalR, as a fun project to learn SignalR, for ASP.NET MVC applications.
Currently i can track logged users and how long are they on a specific page. If they move to another page i track that also and the timer that SignalR is updating resets... Many other features are implemented or partially implemented.
The problem i'm facing is how to get the full url Controller/Action/Parameters
inside SignalR hub?
When i use HttpContext.Current.Request.Url the url is always /signalr/connect.
NOTE:
var hub = $.connection.myHub;
$.connection.hub.start();
is in the _Layout.cshtml.
UPDATE:
I've tried to use
var location = '#HttpContext.Current.Request.Url';
var hub = $.connection.myHub;
$.connection.hub.start().done(function () {
hub.setLocation(location);
});
And the location is passed correctly but I need it on the Connect() task not later.
Is it possible to do this?
UPDATE 2:
This approach doesn't work
var hub = $.connection.myHub;
$.connection.hub.start(function(){hub.setLocation(location)});
as the Connect() is called before.
In my hub i have several methods but i would like pass a value (in my case a location) to the Connect(), is that possible?
public class MyHub : Hub, IDisconnect, IConnected
{
public Task Connect()
{
//do stuff here
//and i would like to have the **location** value
}
public Task Disconnect()
{
//do stuff here
}
}
Update 3
Use QueryString to pass data before the Connect() occurs.
var location = '#HttpContext.Current.Request.Url';
var hub = $.connection.myHub;
$.connection.hub.qs = "location= + location;
$.connection.hub.start();
Passing data like your location value to Connect() is possible via a querystring parameter: SignalR: How to send data to IConnected.Connect()
Using query-string is not very secure, cause a hacker can forge JS code and send you wrong location breaking whatever logic you have behind it.
You can try to get this from owin-enviromment variables
var underlyingHttpContext =
Context.Request.Environment[typeof(HttpContextBase).FullName] as HttpContextBase;
Then extract whatever you need.
It will work on IIS, for non-IIS hosting look for other OWIN stuff https://github.com/aspnet/AspNetKatana/wiki/OWIN-Keys
You could pass it from your client js call to your hub as a parameter.

How to pass message between client & server over the web using SignalR

I heard SignalR is a good messaging library. I got some code for SignalR but I am not able to understand how it works.
JS
var hooking;
$(function() {
hooking = $.connection.hooking;
hooking.removeLead = function(ref) {
$("lead" + ref).remove();
};
$.connection.hub.start();
});
C#
// Hooking.cs (placed in application root)
public class Hooking : Hub
{
public void Submit(string jsonString)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Deserialize<HookingLeadResult>(jsonString);
Clients.removeLead(json.Ref); // Remove lead from client hooking windows
// update lead gen
}
}
I have questions about the above code.
What does hooking mean ins $.connection.hooking;
Where is removeLead in hooking.removeLead
What will this do $.connection.hub.start(); ? What does it start? Which method it will invoke at the server side?
Who & how Submit method will be called at the server side? how to pass data from client side to server side. If possible please give me a url for good start for SignalR library.
The Javascript function hooking.removeLead will be invoked whenever you call Clients.removeLead(). All the bindings are done dynamically, between Javascript to C# and between C# and Javascript.
$.connection.hub.start() is actually the connect function. It will connect your client to the server. No messages can be sent or received until you do. The start function allows you to define a callback to be called when it's done connecting.
The Submit method at the server will be called whenever you do a hooking.submit(json) call on your client. For instance, as a result of the user filling in some form and clicking a button.
I recommend starting with the SignalR official wiki: http://www.asp.net/signalr

Resources