Signalr server method is not calling using objHub.server - javascript

I am already googled about this but not found any solution.
My hub's methods are like this
public string Test(string hello)
{
return hello;
}
public override System.Threading.Tasks.Task OnConnected()
{
return base.OnConnected();
}
and my client side is
var objHub = $.connection.myHub;
$.connection.hub.start().done(function () {
objHub.server.test('test');
}).fail(function () {
/.....
})
OnConnected is calling perfectly but objHub.server.test is not calling.
Even I have checked in console for server side methods mapping to hub object and here is all server methods are registered with hub object
Why my server side methods are not calling?
Update
Now what I am seeing
Server is requesting to
http://localhost:83/signalr/connect?transport=longPolling&clientProtocol=1.5&connectionToken=MUM0NzA5MDI3QTEyRjM5RDM4QjEzNDhGRTFEMjJGNzI3QTcyQTRDM0ZDOTE3MTRCRUYwQkVCOUI3OEQ3Q0MxREY1NzNEQkUzQjAxM0QzMzlCRDIzQUY0OUJDNThENDVCMDUzQ0RENEMwQTUzNkNFMzEyNDY2QTkyMjExRkE4REVDMUZGRUE2RTdFNTNDRkM2NDg5NjEzMUIyMzQzNDI4Njk3RjRBNTdEMDlEQ0U1MUJGQ0I4RjE4Njg3NjU5NTBFRURGQTZCNzBGMzUwRjA0MzdFOERENkQ1NTFEQ0JCNEJDN0U3NDUyNA%3D%3D&connectionData=%5B%5D
And getting this error
Method not found: System.Threading.Tasks.Task 1<Microsoft.Owin.IFormCollection> Microsoft.Owin.OwinRequest.ReadFormAsync()
Thanks

Yes I updated my Microsoft.AspNet.SignalR2.2.2 when I revert to Microsoft.AspNet.SignalR2.2.0 then it working........

Related

Angular Js and SignalR not working when called from WebAPI and Hub

I am working on signalR implementation with Angular JS. When i tried to call SignalR event from API or Hub to ui client side.. it is not working as expected.
WebAPI Call
I am not getting any response in browser for SignalR request.
ServiceCreated for SignalR
[Resposne On Event at client side][3]
I am not getting any resposne in test event for SignalR(Working some times in chrome).
Thanks for advance. Really Appreciate you quick answer.
You have to start the connection, additional to that you have to write your the "test" - function on the client which the server calls.
Here you see a sample:
Client Code:
<script>
$(function () {
var connection = $.hubConnection("http://localhost:27709/signalr");
var chatHubProxy = connection.createHubProxy('chatHub');
chatHubProxy.on('newMessageAdded', function (name, message) {
$("#messages").append("<li>" + name + message + "</li>");
console.log(name + ' ' + message);
});
connection.start({ transport: 'longPolling' }).done(function () {
$('#btnSend').click(function () {
chatHubProxy.invoke('newMessage', "Stephan", $('#msg').val());
$('#msg').val('').focus();
});
});
});
</script>
Server:
public class ChatHub : Hub
{
public void NewMessage(string name, string message)
{
Clients.All.newMessageAdded(name, message);
}
}
It's important that the you write the methode/function on server and client side same (no spelling mistakes).
Attention on Pascal and Camelcase of hubs, methods, ...:
- On the client the proxy name is a camel-cased version of the Hub class name.
By the way: Why you're not using the generated proxy?

SignalR callback does not trigger in JQuery UI widget

I am trying to create a JQuery UI widget that receives realtime updates from a server using SignalR (2.2.0). Invoking a method on the server works just fine, however invoking a client callback from the server does not trigger on the client.
I have enabled logging on the client as is suggested here: SignalR Troubleshooting and I can see in the console that the connection is setup just fine but the client method is never invoked. There is no error message of any kind. I have also defined the client method on the hub proxy before starting the connection like so:
_bindClientCallbacks: function () {
theHub.client.broadCastToClient = function (message) {
twr.log(message);
};
}
and afterwards I start the hub connection like so:
_startSignalRClient: function () {
$.connection.hub.logging = true;
$.connection.hub.start()
.done(function () {
twr.log("Connected to SignalR hub, id=" + $.connection.hub.id);
})
.fail(function () {
});
}
These methods are called in the '_create()' function in the JQuery widget like so:
_create: function () {
theHub = $.connection.DataImportHub;
this._bindClientCallbacks();
this._startSignalRClient();
}
This works fine and I can get a valid connection with an id. I can also call a server method from the client. But when I try to invoke the broadCastToClient method on the client from the server like so:
public void BroadCastToClient(string userId, string message)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<DataImportHub>();
foreach (var connectionId in _connections.GetConnections(userId))
{
hubContext.Clients.Client(connectionId).broadCastToClient(message);
}
}
Nothing happens on the client.. even though the server does find a valid connection that corresponds to the connection id I got on the client.
What am I missing here?
Just found out the solution by reading this post. Apparently having a custom SignalR dependency resolver setup in the Owin startup class breaks javascript callbacks. Moving the dependency resolver setup code to Application_Start in Global.asax does the trick. Why this happens really is beyond me...
Bad DI setup in Startup.cs
app.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
Resolver = new NinjectSignalRDependencyResolver(new StandardKernel())
};
map.RunSignalR(hubConfiguration);
});
Good DI setup in Global.asax
protected void Application_Start()
{
GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(new StandardKernel());
}

How to call function on javascript page from ASP.NET 5 WebAPI

Okay, maybe I'm doing this all wrong, but here goes:
I have a ASP.NET 5 WebAPI project running on dnxcore50. It has one very simple controller, which only implements the Get() method:
public class Data : Controller {
public JsonResult Get(){
return Json(/*some data from EF*/);
}
}
Additionally, I have index.html and myscripts.js files which host a very simple webpage.
When running the project, it opens on http://localhost:5000, I can browse to index.html and can call
$.getJSON('/api/Data', function(data){
/*do stuff*/
});
All of this works, on all OSX and Windows. So far so good!
Now, what I want: when the API is called (for example a POST by another client), it should send a message to the javascript to display an event.
What have I tried:
setting a flag in the API and polling from the javascript. This seems sub-optimal, but works.
playing around with socket.io, but I cannot find a dnxcore50 compatible way to communicate with it from the controller.
playing around with HTML5 WebSockets, but can't seem to establish communication from the controller.
How can I communicate from ASP.NET 5 (dnxcore50) to a javascript page?
OK after some research, I got it working using SignalR, as #Liam suggested.
This is how I got SignalR working with ASP.NET Core 1.0.
In Nuget.config in project root, add repository for SignalR:
<add key="AspNetVNext" value="https://www.myget.org/F/aspnetmaster/api/v3/index.json" />
In project.json add reference for SignalR:
"dependencies":{
...
"Microsoft.AspNet.SignalR.Server": "3.0.0-*"
}
In Startup.cs, register SignalR:
public void ConfigureServices(IServiceCollection services)
{
/* ...other services...*/
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
/*...other configs...*/
app.UseSignalR();
}
Create a new Hub class:
public class EventHub : Hub { }
From for example a controller, call the hub:
private readonly IHubContext hub;
public ProjectQualityController(IConnectionManager connectionManager)
{
hub = connectionManager.GetHubContext<EventHub>();
}
public void SendMessage(string value)
{
hub.Clients.All.sendMessage(value);
}
In the javascript file, register to the sendMessage event:
<script src="scripts/jquery.signalR.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.eventHub;
chat.client.sendMessage = function (message) {
var encodedMsg = $('<div />').text(message).html();
alert(encodedMsg)
};
// Start the connection.
$.connection.hub.logging = true;
$.connection.hub.start()
.done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })
.fail(function(){ console.log('Could not Connect!'); });
});
</script>
Hope this helps someone!

Issue when creating cross-domain SignalR connection

I have sites on 2 domains:
a.com
b.com
b.com hosts the SignalR Hub, and a.com tries to create a connection to b.com.
client JS:
var connection = $.hubConnection('http://b.com/');
var notificationHubProxy = connection.createHubProxy('notificationHub');
$.connection.hub.logging = true;
notificationHubProxy.client.resultReceived = function (result) {
console.log(result);object.
}
server eventHub:
public class NotificationHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
public string Echo()
{
return "Notification hub is running normally";
}
}
But I always get the following error on the client page:
SCRIPT5007: Unable to set property 'resultReceived' of undefined or
null reference.
As I checked, the 'notificationHubProxy.client' is undefined.
Where is wrong?
This is not a cross-domain issue. You are mixing the dynamic proxy and proxyless approaches. $.hubConnection and createHubProxy are from the proxyless API, but .client is available only with dynamic proxies. Check the documentation about both and you will be able to fix it (I don't go further with code because I do not know which approach you really want to use).

How do I fix: InvalidOperationException upon Session timeout in Ajax WebService call

We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like:
// The function to alter the server side state object and set the selected node for the case tree.
function JSMethod(caseId, url)
{
Sample.XYZ.Method(param1, param2, OnMethodReturn);
}
function OnMethodReturn(result)
{
var sessionExpiry = CheckForSessionExpiry(result);
var error = CheckForErrors(result);
... process result
}
And on the server side in the ".asmx.cs" file:
namespace Sample
[ScriptService]
class XYZ : WebService
{
[WebMethod(EnableSession = true)]
public string Method(string param1, string param2)
{
if (SessionExpired())
{
return sessionExpiredMessage;
}
.
.
.
}
}
The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked,
then the following error is obtained:
Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed.
This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd":
function Sys$Net$WebServiceProxy$invoke
{
.
.
.
{
// In debug mode, if no error was registered, display some trace information
var error;
if (result && errorObj) {
// If we got a result, we're likely dealing with an error in the method itself
error = result.get_exceptionType() + "-- " + result.get_message();
}
else {
// Otherwise, it's probably a 'top-level' error, in which case we dump the
// whole response in the trace
error = response.get_responseData();
}
// DevDiv 89485: throw, not alert()
throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error));
}
So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem
You have a callback method (OnMethodReturn) specified in the WebMethod call, but not an error handler method. You need to create one and pass it into as you do the callback method. Then you can handle your failed WebMethod calls in there.
This problem occurs even before the Ajax framework can invoke the target method, it fails while creating the web proxy. Anyway I solved the problem by enabling Anonymous access to the Web Service folder and checking for Session explicitly in the Web Service methods
Why not use, try { } catch { } around your JS method call?
try this one...use "static"
[WebMethod(EnableSession = true)]
public static string Method(string param1, string param2)

Categories

Resources