SignalR refusing connections - c#

I'm trying to configure my signalR demo to my project
framework : 4.0 ,
SignalR version : 1.1.3
Here's my code
$(function () {
var connection = $.hubConnection('http://localhost:32555/');
var chat = connection.createHubProxy('myChatHub');
chat.on('send', function (message) {
$('#chat').html($('#chat').html() + "\r\n" + message);
});
connection.logging = true;
connection.start().done(function () {
alert("Connection Complete");
$('#sendBtn').click(function () {
chat.invoke('send', $('#message').val());
});
}).fail(function (param) {
console.log(param);
});
});
Global.asax
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
}
.Cs
namespace vPortal
{
[HubName("myChatHub")]
public class LetsChat : Hub
{
public void send(string message,string userid,string Name)
{
Clients.All.addMessage(message, userid, Name);
}
}
}
When I tried to run the page I got this error
SignalR: Error during negotiation request:
But, I have enabled proxy in the global.asax I have tried upgrading my signalR to version 2.2.3.
But, my project packages are incompatible with the current version so I installed version 1.1.3.
I don't know what I'm doing wrong here I see there is a connection but can not establish.

A lots of credit goes to this man.
he made my problem easy to solve.
See, first of all my all the references were to 4.0 then So I used Signalr Older version 1.1.4
Here's is my errors scenario:
SignalR could not connect:
I removed this error by adding the lines RouteTable.Routes.MapHubs(); in my Global.asax file.
Negotiation of request: There was a silly mistake done by me the namespace was different in the my chat.aspx page.
Version Conflicts: See, I got previous libraries which were incompatible with the current version (2.3.2) of signalR. So, I had to stick to previous version of it (1.1.3) the steps are given here and its pretty neat.
Again,I was pretty sure about my code signalR will work fine:
So, run my chat and my first message was succeed then Again there was an error after sometime and the error was
the added or subtracted value results in an un-representable datetime. signlar
So, this was the big headache for me.This is definately nothing do with the signalR
I got the clue from frebin and I realized that in my web.config
<httpRuntime executionTimeout="180" maxRequestLength="512000" />
The executionTimeout previous value was 9999999999
i changed to 180 and its works fine!!!
I have added all the scenarios for the future preferences.

Related

How to trigger a SignalR command outside of the front end

I feel like I'm either missing the point of the SignalR service or I've got the architecture of it wrong.
Using an Azure SignalR service I've got the front-end to front-end communication working as such;
Startup.cs
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
app.MapAzureSignalR(this.GetType().FullName);
}
Hub.cs
private void BroadcastMessage(string message)
{
Clients.All.broadcastMessage(message);
}
Index.html
hubName.client.broadcastMessage = function (message) {
alert(message);
};
$('#btn').click(function () {
hubName.server.broadcastMessage("Hello World");
});
This is fine, and when I need the back-end to trigger a message I am using the following;
Functions.cs
HubConnection signalr = new HubConnection("http://localhost:57690/");
IHubProxy hub = null;
if (signalr.State == ConnectionState.Disconnected)
{
hub = signalr.CreateHubProxy(hubName);
signalr.Start().Wait();
}
hub.Invoke(functionName, args);
signalr.Stop();
While this works it leaves me wondering if I have implemented it wrong as this leaves http://localhost:57690/signalr/hubs open to posts from any source.
In the front-end, I have to provide the Endpoint=https://appName.service.signalr.net;AccessKey=xxxxx setting but not from the back-end.
As well as a security concern, this leaves me questioning what purpose the SignalR service has in this.
Surely there must be a better way to invoke signalr from the back-end.
Many Thanks,
Tom
In the Startup.cs you gotta have a line of code like this
services.AddSignalR().AddAzureSignalR();
By not passing a parameter to AddAzureSignalR(), this code uses the default configuration key, Azure:SignalR:ConnectionString, for the SignalR Service resource connection string.
You can find more info in this article

How to debug SignalR server event that fails to fire from client?

When I copy the code from this tutorial into my current project, I have no problems using their Send method.
However, in my own code, my server Send method never fires.
Server code:
public class ModelingHub : Hub
{
public void Send(string message) // my breakpoint is never hit here
{
Clients.All.broadcastMessage(message);
}
}
Client Code
$(function () {
var modelHub = $.connection.modelingHub;
modelHub.client.broadcastMessage = function(response) {
alert(response);
};
$.connection.hub.start().done(function () {
alert(1); // this fires
$("body").on("click", function () {
alert(2); // this fires too
modelHub.server.send("test"); // never fires
});
});
});
I don't want to go messing with the library code from SignalR, but I'm not sure how to debug this any further.
I can't call the method from the console either:
>$.connection.modelingHub.server.send("test")
Note that when I implement OnConnected and OnDisconnected events in my ModelingHub subclass, they work fine. I've taken them out to debug the Send failure.
Your issue stems from your class, you do the following:
public class ModelingHub : Hub
{
public void Send(string message)
{
var call = message;
}
}
But you aren't actually doing anything with your message, you need your hub to actually broadcast the data. You would need to add code similar or this below your variable call.
Clients.All.broadcastMessage(call);
If you don't sanitize your data, the method body could be:
public void Send(string message) => Clients.All.broadcastMessage(message);
Also, if I recall that tutorial has an interface called Send which expects two parameters, you may want to also check there to ensure you modified to accept your single parameter.
Make sure that you reference the correct version of SignalR. The tutorial references version 2.2.1 but the current version is 2.2.2 so that is a potential issue.
Check the browser console to see if you have any errors and make sure the version numbers of the references match up with what you have in your project.

How to track 500 errors on WebSockets (ws://)

I'm trying to play around with WebSockets on IIS 8.5. I started off with a couple of very basic C# classes from a lesson:
using Microsoft.Web.WebSockets;
using System.Web;
public class ChatHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new WebSocketChatHandler());
}
public bool IsReusable
{
get { return true; }
}
}
public class WebSocketChatHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["username"];
clients.Add(this);
clients.Broadcast(string.Format("{0} joined.", name));
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0}: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format("{0} left.", name));
}
}
and a simple HTML client. The project builds ok, but when I try to connect to the handler, it returns error 500. The problem is that I cannot see what the exact error is, because neither Chrome nor FF load the response body for ws:// scheme, so i cannot even see it in the Network tab of Developer Tools (though IIS provides the body, as I can see from from the response' Content-Length).
Is there a way to see the response body in this situation? Or what am I missing with WebSockets in IIS?
The problem was with web.config.
I added
<httpRuntime targetFramework="4.5.1" />
to system.web section and it finally began to work
You should be able to see the cause of the error in the Windows Event Viewer.
Fiddler will show you the connection and that it has upgraded to web socket so you can use that tool to at least show you if the connection worked or not. I'm not aware of a tool which can show you the traffic flowing over the socket once it has been upgraded although there might be one.
Better still, debug it in Visual Studio with breakpoints and 'break on exception' set. You can tell VS to use IIS as the server by right clicking the web site and going to Property Pages then Start Options. Tick Use custom server and put your URL into the textbox. Click Specific page and choose your default page.
Comparing it to my working solution using the same DLL, I don't spot any obvious issues with the handling of the socket, so I would suggest commenting out this.name = this.WebSocketContext.QueryString["username"]; for now and replacing it with this.name = "TEST"; as that appears to be about the only code which deviates from the samples. Keep it simple until its working!

SignalR cannot set property '' of undefined

I'm trying to set SignalR in my MVC4 app.
The problem is - even though when I browse to path /signalr/hubs I do see code (and fiddler shows 200OK for /signalr/hubs), it does not seem to contain any reference to my hub and client side code also doesn't see the hub and methods.
I get these errors when starting debugging (IIS Express, VS Express 2012):
Application_Start in Global.asax contains:
//RouteTable.Routes.MapHubs("/signalr", new HubConfiguration());
RouteTable.Routes.MapHubs();
RouteConfig.RegisterRoutes(RouteTable.Routes);
(I assume this generates the /signalr/hubs, this seems to work but nothing links to my actual hub. As can be seen I tried both options).
In my project I got folder "Hubs" in root with MessageHub.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace Prj.Hubs
{
[HubName("messagehub")]
public class MessageHub : Hub
{
public void MessageAll(string message)
{
Clients.All.writeMessage(message);
}
public void MessageOthers(string message)
{
Clients.Others.writeMessage(message);
}
public void MessageSingle(string message)
{
}
}
}
In my _Layout.cshtml I have just before the closing tag:
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.signalR-1.1.2.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// create proxy on the fly
var proxy = $.connection.messagehub; // this connects to our 'messageHub' Hub as above
// for SignalR to call the client side function we need to declare it with the Hub
proxy.messageAll = function (message) {
$('#messages').append('<li>' + message + ''); // when the Hub calls this function it appends a new li item with the text
};
// declare function to be called when button is clicked
$("#broadcast").click(function () {
// calls method on Hub and pass through text from textbox
proxy.messageAll($("#message").val());
});
// Start the connection
$.connection.hub.start();
});
</script>
(side note - SignalR didn't like at all the #Scripts.Render("~/bundles/jquery"), but a direct jquery script include seems to work).
So why doesn't it recognize "messagehub" exactly?
I solved this - my solution contains multiple projects, and although I had uninstalled SignalR, in some of these projects in the bin/Debug folder there were still traces of an older SignalR version that I tried months ago.
At runtime, SignalR was trying to connect some old dll's with the new references. So if you have this error then
uninstall SignalR
do a search for "SignalR" in your entire solution folder and delete everything
reinstall SignalR from Nuget Package Manager.

SignalR ASPNetHost does not exist in the current context

I've downloaded the latest SignalR code (as of 04/04/12) from GitHub as it now compiles with MonoDevelop so I can use it on OS X.
But while testing the new version with the SignalR.Sample example listed on the Getting Started page, it fails with the following error:
The name 'AspNetHost' does not exist in the current context
This occurs in StockTicker.cs here:
private static dynamic GetClients()
{
return AspNetHost.DependencyResolver.Resolve<IConnectionManager>().GetClients<StockTickerHub>();
}
Can anyone explain what has become of AspNetHost?
Suggestions on how to get the SignalR.Sample compiling would be very welcome.
I had the same problem and found that this was deprecated in SignalR 0.5. Here is an article detailing the changes.
Specific to your item, the change is from this:
public void PerformLongRunningHubOperation()
{
var clients = AspNetHost.DependencyResolver.Resolve<IConnectionManager>().GetClients<MyHub>();
clients.notify("Hello world");
}
To this in 0.5:
public void PerformLongRunningHubOperation()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.notify("Hello world");
}
You're gonna need to read the code because the source isn't in sync with the docs. The docs are for the current release, not the actively developed.
Take a look at the asp.net sample to see the current API. It's not set in stone yet though.

Categories