Path not found error - c#

I installed SignalR 2.0-rc1, and:
1: Created a hub:
public class Socials : Hub
{
public void PublicChat(string message)
{
Clients.All.PublicChat(new { message });
}
}
2: Created a startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
3: Registered it in web.config:
<add key="owin:AppStartup" value="Scyk.Startup, Scyk"/> //Scyk is my main namespace, also a project name, I placed Startup class in there.
Now, https://myhost.com/signalr/hubs is generating javascript file properly, but when I open developer console in my browser, I see that it has not connected, but:
There is an asp error saying that path /signalr/connect was not found (why is it trying to access /signalr/connect? Is that normal? If so, then this must be purely routing problem, how do I solve it?)
In my console, I see that there is a EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. error. I am not sure if this is related, but it started to show up today, wasn't there before.
What am I doing wrong?

Any path beginning with /signalr should be routed through OWIN so signalr can handle the request.
It is normal for the client to try to access /signalr/connect after accessing /signalr/negotiate. /signalr/connect is the endpoint where SignalR establishes its WebSockets/Server-Sent Events/Forever Frame/Long Polling connections.

Related

c# 4.0 service as client to connect a signalr(1.2.2) hub

I worte a server class as DLTransMonCore.cs using C# .Net 4.0.
DLTransMonCore.cs in DLTransMonCore DLL Project
public void MonStart() {
var client = new WebSignalrClient();
client.HubUrl = "http://10.20.30.40/MyApp";
client.HubName = "MyAppHub";
client.InitialSignalrHub();
}
WebSignalrClient.cs in WebSignalrClient DLL Project
public string HubUrl;
public string HubName;
public void InitialSignalrHub() {
var hubConnection = new HubConnection(HubUrl);
var hubProxy = hubConnection.CreateHubProxy(HubName);
hubConnection.Start().Wait();
}
This server will connect to a web site by using signalr(1.2.2). And listen some ports use socket as a socket server.
1st Scenario,
I use a console application (Program.cs) to instance the DLTransMonCore class and start it.
Everything is work fine.
Program.cs
static void Main(string[] args) {
var core = new DLTransMonCore();
core.MonStart();
Console.Readkey();
}
2nd Scenario,
I make a windows service (Service1.cs) to instance DLTransMonCore class and start it. When I try to launch the "Service1" in Windows Services, the "Service1" will start for about 10 seconds and then auto stopped by Windows.
Service1.cs
protected override void OnStart(string[] args) {
var core = new DLTransMonCore();
core.MonStart();
}
I wrote a log file to find which line last executed was:
hubConnection.Start().Wait(); (in WebSignalrClient.cs),
and it never reach the next line.
3rd Scenario,
I make another windows service (Service2.cs) to instance WebSignalrClient directly. And this "Service2" start successfully. (hubConnection.Start().Wait(); is executed successfully and reach the next line)
Service2.cs
protected override void OnStart(string[] args) {
var client = new WebSignalrClient();
client.HubUrl = "http://10.20.30.40/MyApp";
client.HubName = "MyAppHub";
client.InitialSignalrHub();
}
Why the Service1 be fail and the Service2 be success?
Any comment will be appreciate!
Edit:
The description of this post is simplify from my "Original Solution". The Original Solution has lots of Models, Repositories, Interfaces, Utilities, Extensions, Projects...etc.
So I have to simplify it to describe my problem.
But I just created another "New Solution", with the minimized code to test Scenario2 and Scenario3.
Then I found the "New Solution" were worked. It's really bother me...
Now I have to retest and review my code in the "Original Solution".
But if you have any suggestions or comments, please still comment it.
Thank you!
Edit 2:
Dear all, This pattern is no problem.
I found my problem in the "Original Solution".
The problem is : NullReferenceException.
The reason is : When Windows starts the Service, the working directory IS NOT where your Service.exe existed.
In my solution, I have my customize configuration file in that Service's location. And the Service will get the configuration by using the filename directly. Then, the Service will got a null object, and the NullReferenceException when Service Starting is trying to access the config.
I can't explain why but i had the same issue as i wanted a self hosted server using windows service and i never figured out why it was so unstable, what i can suggest is to use Owin selfhost as i switched to it using signalR and it's much more reliable than windows service.

How to connect Hub if Hub is in different project SignalR?

I'm working with SignalR project, in which I want to use Hub in WebApi project as well as Web project. So I've created one class library project and implemented Hub over there.
My project structure looks like:
-ChatHub
-Hub
-Webapi
-Website
Here is my Hub:
[HubName("chathub")]
public class ChatHub : Hub
{
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
}
When I calling Hub from my website it's working well.
<script src="~/signalr/hubs"></script>
var chatHub = $.connection.chathub;
Here is how I connect Hub from outside(Android):
mHubConnection = new HubConnection(http://{IpAddress}/ChatApp/);
mHubProxy = mHubConnection.createHubProxy(chathub);
API:
public IHttpActionResult LoginUser([FromBody]LoginModel model)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
//chatUser logic here
hubContext.Clients.Client(chatUser.ConnectionId).receiver(response);
}
But it gives me an error:
java.util.concurrent.ExecutionException:
microsoft.aspnet.signalr.client.transport.NegotiationException: There
was a problem in the negotiation with the server
10-13 18:15:54.074 18686-18686/com.chatapp.android W/System.err:
Caused by:
microsoft.aspnet.signalr.client.http.InvalidHttpStatusCodeException:
Invalid status code: 404
How can we connect Hub if my Hub is out side of API project?
I've gone through Sharing a SignalR hub between a WebApi and MVC project but didn't get the answer they were provided.
Are you calling mHubConnection.Start() after setting up the connection and the proxy to the hub? Also is the url being passed into the HubConnection constructor the correct location for the hub? Here are a couple of links that might be helpful, if you haven't already been through them: Access hub from .NET client, configure signalr url

SignalR 404 error when trying to negotiate

So I am very new to SignalR, in fact I've only been using it for a couple of days now. Anyway, I am getting the error below when my application first starts up:
The code for the application in question is located in two projects, a Web API and a Single Page Application (SPA). The first one has my backend code (C#) and the second one my client-side code (AngularJS). I think the problem might be due to the fact that the projects in question run on different ports. The Web API, where my SignalR hub lives, is on port 60161 and the SPA is on 60813. My hub is declared like so:
public class ReportHub : Hub
{
public void SendReportProgress(IList<ReportProgress> reportProgress)
{
this.Clients.All.broadcastReportProgress(reportProgress);
}
public override Task OnConnected()
{
this.Clients.All.newConnection();
return base.OnConnected();
}
}
and then in my Startup.cs file for my Web API I initialize SignalR like this:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IHttpControllerActivator), new NinjectFactory());
config.MessageHandlers.Add(new MessageHandler());
//set up OAuth and Cors
this.ConfigureOAuth(app);
config.EnableCors();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Setting up SignalR
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.RunSignalR(new HubConfiguration { EnableJSONP = true });
});
//set up json formatters
FormatterConfig.RegisterFormatters(config.Formatters);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
For my client-side code I use an Angular SignalR API called angular-signalr-hub (Angular-signalr-hub). The client-side follows:
angular
.module("mainApp")
.factory("reportHubService", ["$rootScope", "Hub", reportHubService]);
/// The factory function
function reportHubService($rootScope, Hub) {
var vm = this;
vm.reportName = "None";
// Setting up the SignalR hub
var hub = new Hub("reportHub", {
listeners: {
'newConnection': function(id) {
vm.reportName = "SignalR connected!";
$rootScope.$apply();
},
'broadcastReportProgress': function (reportProgress) {
vm.reportName = reportProgress.reportName;
$rootScope.$apply();
}
},
errorHandler: function(error) {
},
hubDisconnected: function () {
if (hub.connection.lastError) {
hub.connection.start();
}
},
transport: 'webSockets',
logging: true
//rootPath: 'http://localhost:60161/signalr'
});
I did some googling yesterday and one of the suggestions I came upon was to set the SignalR URL to the one of my Web API, which I did (the commented out line above). When I uncomment the line in question, that does seem to do something because if I now go to http://localhost:60161/signalr/hubs in my browser, it does show me the dynamically generated proxy file:
and when I run my application I no longer get the error above, but now it doesn't seem to connect. It gets to the negotiate line and it stops there:
I think it should look like this (this is from a SignalR tutorial I found):
In addition, none of my listeners (declared in my Angular code above) get called, so something is still now working quite right. There should be more lines in the log to the effect that connection was successfully established, etc. What could be the problem here?
UPDATE: upon further debugging i found out the problem is most likely being caused by the ProtocolVersion property being different between the client and the result here:
Because of that it seems it just exists and fails to establish connection.
I figured out what the problem was. My SignalR dependencies were out of date and because of that my client and server versions differed. All I had to do was update (via NuGet Package Manager) all SignalR dependencies to the latest version and now it works.
As a side note, SignalR was not very good at telling me what was wrong. In fact, no error message was displayed, unless of course there was some additional logging somewhere that had to be found or turned on, in addition to the logging I already had (turned on). Either way, it's either not logging certain errors or it makes it difficult to figure out how to turn on all logging. I had to go and debug the JQuery SignalR api to figure out what the problem was, which was a time consuming endeavour.

TraceListener in OWIN Self Hosting

I am using Microsoft.Owin.Hosting to host the following, very simple web app.
Here is the call to start it:
WebApp.Start<PushServerStartup>("http://localhost:8080/events");
Here is the startup class I am using:
public class PushServerStartup
{
public void Configuration(IAppBuilder app)
{
app.MapHubs();
}
}
I am running this inside a console application that does a lot of other things including routing trace writing to certain files etc. But all of a sudden (when activating the OWIN hosting) I am seeing trace messages written to the console that are normally routed somewhere else.
Obviously there are some trace listeners active in the OWIN hosting framework. How can I switch them off?
I had the same issue, I was self hosting 4 instances in one process and for each request was getting 4 lots of messages traced to console.
I simply removed the TraceListener instance
Trace.Listeners.Remove("HostingTraceListener")
"HostingTraceListener" is defined in the owin source code so I guess could change
- http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Hosting/Engine/HostingEngine.cs
I did this after
WebApp.Start(...
An alternative to the answer from meilke that works with latest Katana self-host (2.1.0):
StartOptions options = new StartOptions("http://localhost:8080/events");
// disable built-in owin tracing by using a null traceoutput
options.Settings.Add(
typeof(Microsoft.Owin.Hosting.Tracing.ITraceOutputFactory).FullName,
typeof(NullTraceOutputFactory).AssemblyQualifiedName);
using (WebApp.Start<PushServerStartup>(options))
NullTraceOutputFactory is similar to DummyFactory but using StreamWriter.Null instead of StringWriter:
public class NullTraceOutputFactory : ITraceOutputFactory
{
public TextWriter Create(string outputFile)
{
return StreamWriter.Null;
}
}
I found a solution myself. After studying the Katana source code it seems like you need to register your own ITraceOutputFactory instance to overrule the default trace listener (which is writing to the console).
Here is the new start call:
var dummyFactory = new DummyFactory();
var provider = ServicesFactory.Create(
defaultServiceProvider => defaultServiceProvider.AddInstance<ITraceOutputFactory>(dummyFactory));
using (WebApp.Start<Startup>(provider, new StartOptions("http://localhost:8090")))
{
Console.ReadLine();
}
And here is a dummy trace factory (maybe not the best solution but you can replace it with something serving your purpose a little better):
public class DummyFactory : ITraceOutputFactory
{
public TextWriter Create(string outputFile)
{
return TextWriter.Null;
}
}

How do I get the IP address of my Corba client from the sever

I have a c++ client publishing Corba messages to a c# server via omniOrb. I have registered a PortableInterceptor with the Orb at the server end and can intercept messages.
In debug I get a ServerRequestInfo message in the intercept and In debug watch window can see the all the way down to the RemoteEndPort with the IP of the client. A lot of these classes however have private members which I can't access in the code.
How do I do it?
Here is my code
// register the OrbInitialiser here in some code
omg.org.CORBA.OrbServices orb = omg.org.CORBA.OrbServices.GetSingleton();
orb.RegisterPortableInterceptorInitalizer( new LT.Quantifi.BrokerOrbInitialiser());
orb.CompleteInterceptorRegistration();
// register the Inteceptor in the OrbInitialiser here
public class BrokerOrbInitialiser : omg.org.PortableInterceptor.ORBInitializer
{
public void post_init(ORBInitInfo info)
{
BrokerRequestInterceptor serverRequests = new BrokerRequestInterceptor();
info.add_server_request_interceptor(serverRequests);
}
}
// Inteceptor catches messages here
Public class BrokerRequestInterceptor : omg.org.PortableInterceptor.ServerRequestInterceptor
{
.
.
public void receive_request_service_contexts(ServerRequestInfo ri)
{
Console.WriteLine("I catch messages here");
}
.
.
}
There is no standard way to get access to that information in CORBA. Some implementations do have a custom way to get some information, for example TAO has a transport current object you can get access to. At the moment the call has been received using IIOP you can narrow that to a IIOP Transport Current which than gives you that information. Looks you need an extension for the C# ORB to have a similar extension

Categories

Resources