HttpClientException when connecting to working hub from SignalR .NET Client - signalr

I have a working SignalR application that allows me to connect multiple JavaScript clients and exchange data. When I tried to connect with a .NET client I get the following error:
An exception of type 'Microsoft.AspNet.SignalR.Client.HttpClientException' occurred in mscorlib.dll but was not handled in user code
Additional information: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcRGFycmVuXERlc2t0b3BcQ29uc29sZUFwcGxpY2F0aW9uMVxXZWJBcHBsaWNhdGlvbjFcc2lnbmFsclxuZWdvdGlhdGU=?=
Cache-Control: private
Date: Thu, 28 May 2015 09:13:06 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Type: text/html; charset=utf-8
}
To remove as many variables as possible I copied the Hub into an brand new web application and copied the .NET client code into a console application. I still get the same exception. Here is my client code:
Dim hubConnection As HubConnection
Dim chatHubProxy As IHubProxy
Public Async Sub RunTest()
System.Net.ServicePointManager.DefaultConnectionLimit = 10
hubConnection = New HubConnection("http://localhost:64400")
hubConnection.Credentials = Net.CredentialCache.DefaultCredentials
hubConnection.TraceLevel = TraceLevels.All
hubConnection.TraceWriter = Console.Out
chatHubProxy = hubConnection.CreateHubProxy("Chat")
AddHandler hubConnection.StateChanged, Sub(stateChange) Console.WriteLine("[" & DateTime.Now & "]: " & stateChange.OldState.ToString() & " => " & stateChange.NewState.ToString() & " " & hubConnection.ConnectionId)
chatHubProxy.On(Of String, String)("ReceiveMessage", Sub(from, message) Console.WriteLine(message))
Await hubConnection.Start()
End Sub
Here is the console output:
09:21:54.3952161 - null - ChangeState(Disconnected, Connecting)
[28/05/2015 10:21:54]: Disconnected => Connecting
[28/05/2015 10:21:56]: Connecting => Disconnected
09:21:56.8448452 - null - Disconnected
09:21:56.8458461 - null - Transport.Dispose()
09:21:56.8468465 - null - Closed
And here is my hub code:
public class ChatHub : Hub
{
public void SendMessage(string name, string message)
{
Clients.All.ReceiveMessage(name, message);
}
}

This turned out to be a trivial mistake, but the error message was so useless I'm sure others will be stumped by the same issue. The name of the hub was wrong. I used "Chat" when I should have used "ChatHub".
If the exception had been 404, or "Hub not found" or something like that it would have been an easy fix rather than a couple of wasted hours!

#Michael Tiller's comment in #Darren's answer turned out to be the solution for my problem, so I think it's fair to make this into its own answer:
Changing the Hub class to public solved my problem. I followed an example and missed the text that said to create a PUBLIC class that inherits from Hub, and when adding a new class in Visual Studio, by default it creates it as
class TestHub
{
}
...which is technically internal (see here). More careful reading on my part would have prevented this, but in case someone else got in too big of a hurry like I did... :)

Real issue was resolved but i think it's important to realise that SignalR server returning status 500 (Internal Server Error) (not very informative error indeed) is security feature.
If you need more information on server errors, you can do following:
1) Enable tracing on server
and\or
2) Enable detailed exception messages send to client (don't do that in production!):
SignalR 1.x:
RouteTable.Routes.MapHubs(new HubConfiguration { EnableDetailedErrors = true });
SignalR 2.x
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration
{
#if DEBUG
EnableDetailedErrors = true
#else
EnableDetailedErrors = false
#endif
};
app.MapSignalR(hubConfiguration);
}

I was doing similar trivial mistake took few hours to figure it out.
[HubName("Hostsync")] // Missed to add this attribute in Hub of SignalR Self Host
public class ChatHub : Hub
{
}
But i was trying to connect by defining the proxy name in Client.
HostProxyName = "Hostsync";
Just make sure there is no such kind of mistakes. Since you will not be getting the exact detailed exception during the connection establishment.
The following link helped me to address few things
Stackoverflow Question Answer Link
Hope this helps.,

I had the same issue. I found out that the SignalR Jquery extension version was older than the referenced SignalR library. I corrected the script version and problem solved. If you have recently upgraded the SignalR to newer version, you would probably face the same issue like me.

Related

Realm doesn’t work with xUnite and .net core

I’m having issues running realm with xUnite and Net core. Here is a very simple test that I want to run
public class UnitTest1
{
[Scenario]
public void Test1()
{
var realm = Realm.GetInstance(new InMemoryConfiguration("Test123"));
realm.Write(() =>
{
realm.Add(new Product());
});
var test = realm.All<Product>().First();
realm.Write(() => realm.RemoveAll());
}
}
I get different exceptions on different machines (Windows & Mac) on line where I try to create a Realm instace with InMemoryConfiguration.
On Mac I get the following exception
libc++abi.dylib: terminating with uncaught exception of type realm::IncorrectThreadException: Realm accessed from incorrect thread.
On Windows I get the following exception when running
ERROR Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. at
System.Net.Sockets.NetworkStream.Read(Span1 destination) at
System.Net.Sockets.NetworkStream.ReadByte() at
System.IO.BinaryReader.ReadByte() at
System.IO.BinaryReader.Read7BitEncodedInt() at
System.IO.BinaryReader.ReadString() at
Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.LengthPrefixCommunicationChannel.NotifyDataAvailable() at
Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.TcpClientExtensions.MessageLoopAsync(TcpClient client, ICommunicationChannel channel, Action1 errorHandler, CancellationToken cancellationToken) Source: System.Net.Sockets HResult: -2146232800 Inner Exception: An existing connection was forcibly closed by the remote host HResult: -2147467259
I’m using Realm 3.3.0 and xUnit 2.4.1
I’ve tried downgrading to Realm 2.2.0, and it didn’t work either.
The solution to this problem was found in this Github post
The piece of code from that helped me to solve the issue
Realm GetInstanceWithoutCapturingContext(RealmConfiguration config)
{
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(null);
Realm realm = null;
try
{
realm = Realm.GetInstance(config);
}
finally
{
SynchronizationContext.SetSynchronizationContext(context);
}
return realm;
}
Though it took a while for me to apply this to my solution.
First and foremost, instead of just setting the context to null I am using Nito.AsyncEx.AsyncContext. Because otherwise automatic changes will not be propagated through threads, as realm needs a non-null SynchronizationContext for that feature to work. So, in my case the method looks something like this
public class MockRealmFactory : IRealmFactory
{
private readonly SynchronizationContext _synchronizationContext;
private readonly string _defaultDatabaseId;
public MockRealmFactory()
{
_synchronizationContext = new AsyncContext().SynchronizationContext;
_defaultDatabaseId = Guid.NewGuid().ToString();
}
public Realm GetRealmWithPath(string realmDbPath)
{
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(_synchronizationContext);
Realm realm;
try
{
realm = Realm.GetInstance(new InMemoryConfiguration(realmDbPath));
}
finally
{
SynchronizationContext.SetSynchronizationContext(context);
}
return realm;
}
}
Further, this fixed a lot of failing unit tests. But I was still receiving that same exception - Realm accessed from incorrect thread. And I had no clue why, cause everything was set correctly. Then I found that the tests that were failing were related to methods where I was using async realm api, in particular realm.WriteAsync. After some more digging I found the following lines in the realm documentation.
It is not a problem if you have set SynchronisationContext.Current but
it will cause WriteAsync to dispatch again on the thread pool, which
may create another worker thread. So, if you are using Current in your
threads, consider calling just Write instead of WriteAsync.
In my code there was no direct need of using the async API. I removed and replaced with sync Write and all the tests became green again! I guess if I find myself in a situation that I do need to use the async API because of some kind of bulk insertions, I'd either mock that specific API, or replace with my own background thread using Task.Run instead of using Realm's version.

ASP.Net Core HTTP Request Connections getting stuck

We have a simple application in ASP.NET Core which calls a website and returns the content. The Controller method looks like this:
[HttpGet("test/get")]
public ActionResult<string> TestGet()
{
var client = new WebClient
{
BaseAddress = "http://v-dev-a"
};
return client.DownloadString("/");
}
The URL which we call is just the default page of an IIS. I am using Apache JMeter to test 1000 requests in 10 seconds. I have always the same issue, after about 300-400 requests it gets stuck for a few minutes and nothing works. The appplication which holds the controller is completely frozen.
In the performance monitor (MMC) I see that the connection are at 100%.
I tried the same code with ASP.NET 4.7.2 and it runs without any issues.
I also read about that the dispose of the WebClient does not work and I should make it static. See here
Also the deactivation of the KeepAlive did not help:
public class QPWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
((HttpWebRequest)request).KeepAlive = false;
}
return request;
}
}
The HttpClient hast the same issue, it does not change anything
With dependency injection like recommended here there is an exception throw that the web client can't handle more request at the same time.
Another unsuccessful try was to change ConnectionLimit and SetTcpKeepAlive in ServicePoint
So I am out of ideas how to solve this issue. Last idea is to move the application to ASP.NET. Does anyone of you have an idea or faced already the same issue?

SignalR self host connection issue

I recently created a proof of concept console application using SignalR (self host). It worked a treat for our use. The client connected fine and I was able to send updates from the server to the client. Lovely!
I've now transferred the code from the Console application to a winforms application for a prettier UI. Now that same client won't connect to the server yet it will still connect to the old Console version.
Winforms code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
// Let the app know the server is up
}
Console code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
Client connection code:
if (!connected)
{
int i = 0;
// Try 3 times
while (i <= 2)
{
try
{
string server = Properties.Settings.Default.Server + ":" + Properties.Settings.Default.PortNumber.ToString();
connection = new HubConnection(server);
connection.StateChanged += connection_StateChanged;
hub = connection.CreateHubProxy("MyHub");
connection.Start().Wait();
hub.On<string>("addMessage", param => { UpdateAlarmStatus(param); });
return true;
}
catch (Exception)
{
i++;
}
}
return false;
}
else
{
return true;
}
The error the client is reporting is:
Exception:Thrown: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was thrown: "No connection could be made because the target machine actively refused it"
Time: 25/01/2015 15:09:23
Thread:Worker Thread[8232]
Why would the target machine (localhost) refuse itself which the Console version doesn't? I've been looking at the code over and over and I cannot see where I'm going wrong. Can anyone point me in the right direction please?
Thank you for reading.
Paul.
I suspect this is an issue with the configuration of your machine/infrastructure rather than the code itself, which looks fine at first glance.
Have you checked the console debug output in Visual Studio? I recently encountered an issue with similar symptoms and that was what gave me the initial clue to keep investigating. In my particular case, an exception was written to the console debug output that didn't make it to the client.
SignalR will normally negotiate with the server automatically to determine the best transport method to use. In a .NET client, the available options are LongPollingTransport, ServerSentEventsTransport and WebSocketTransport. So for some reason, your console app can use at least one of those methods, whereas your WinForms client cannot.
You can perhaps enable tracing to give you more information to work with. To do this, enter the below before you create the hub proxy:
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
ASP.NET doco on SignalR tracing

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 connection issues

I'm getting some issues with SignalR (1.1.2) trying to create a basic realtime chat setup and after spending about a week on it (including trawling through the SignalR source) I'm sort of at the end of what I can try...
I have (I think) a rather complicated SignalR setup consisting of:
Load balanced servers
Redis message bus
Two sites on each server (ASP.NET Webforms VB.NET desktop site and MVC3 C# mobile site)
Each of the sites includes the hub of itself and the other site, so each page can send messages to each site.
Looking into the Chrome inspector (in this example on the mobile site), the hubs are both loaded, the negotiate step for mobile is successful but the connect attempt fails after 3 seconds with the error:
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
which is of course our custom 500 error page after Microsoft.Owin.Host.SystemWeb has thrown:
The connection id is in the incorrect format.
Once this happens, most of the time this will then get into some sort of weird loop where it will continue to throw hundreds of these errors and send off lots of pings followed by a longPolling connect
The solution works perfectly well in my development environment (single IIS instance) but moving to the load balanced test environment is where I see the errors.
I don't know if there's anything else I can add that may help but I'm happy to add it.
I've added the following to the web.config files on both sites:
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
and
<add name="Access-Control-Allow-Origin" value="*"></add>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
The global.asax files have:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
RedisScaleoutConfiguration redisConfig = new RedisScaleoutConfiguration([redisIP], [port], String.Empty, "Name");
redisConfig.Database = 9;
GlobalHost.DependencyResolver.UseRedis(redisConfig);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
HubConfiguration hubConfig = new HubConfiguration();
hubConfig.EnableCrossDomain = true;
hubConfig.EnableDetailedErrors = true;
RouteTable.Routes.MapHubs(hubConfig);
<snip>
}
The JS code I have is along the lines of:
function setUpSignalR() {
//Set up the connections
webConnection = $.hubConnection(pageInfo.webUrl);
mobConnection = $.hubConnection(pageInfo.mobUrl);
//Get the hubs for web and mobile
webHub = webConnection.createHubProxies().messagingHub;
mobHub = mobConnection.createHubProxies().messagingHub;
//Hook up the call back functions
<snip>
//Now, start it up!
mobConnection.logging = true;
mobConnection.start().done(function() {
mobHub.server.joinConversation(pageInfo.conversationGuid, "mobile").fail(function (error) { console.log('JoinConversation for mobile connection failed. Error: ' + error); });
webConnection.start().done(function() {
webHub.server.joinConversation(pageInfo.conversationGuid, "mobile").fail(function (error) { console.log('JoinConversation for web connection failed. Error: ' + error); });
});
});
}
From the SignalR troubleshooting document:
"The connection ID is in the incorrect format" or "The user identity
cannot change during an active SignalR connection" error
This error may be seen if authentication is being used, and the client
is logged out before the connection is stopped. The solution is to
stop the SignalR connection before logging the client out.

Resources