Signal Refresh issue on some clients in asp.net mvc - c#

I have developed an application in ASP .NET MVC using SignalR Everything is perfect the only issue I am facing is when I perform CRUD some of the clients are updated using SignalR and some of them are not updated.
Please help me to figure out this issue
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class SettingHub : Hub
{
public static void BroadcastData()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SettingHub>();
context.Clients.All.updatedData();
}
}
$(function () {
var notificationFromHub = $.connection.settingHub;
$.connection.hub.start().done(function () {
FetchSettings();
});
notificationFromHub.client.updatedData = function () {
FetchSettings();
};
});

I just shuffle the code and it works
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class SettingHub : Hub
{
public static void BroadcastData()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SettingHub>();
context.Clients.All.updatedData();
}
}
$(function () {
var notificationFromHub = $.connection.settingHub;
notificationFromHub.client.updatedData = function () {
FetchSettings();
};
});
$.connection.hub.start().done(function () {
FetchSettings();
});

Related

Sending messages from Server to clients in SignalR 2.0

I am learning SignalR and it pretty simple. However, I am having a problem sending Messages from Server to client.
My Hub class is as follows:
public class UpdateHub : Hub
{
private readonly UpdateBroadcast _broadcaster;
public UpdateHub() : this(UpdateBroadcast.Instance) { }
public UpdateHub(UpdateBroadcast broadCaster)
{
_broadcaster = broadCaster;
}
}
And I am calling this hub in my broadcaster class like this:
public class UpdateBroadcast
{
private readonly static Lazy<UpdateBroadcast> _instance = new Lazy<UpdateBroadcast>(
() => new UpdateBroadcast(GlobalHost.ConnectionManager.GetHubContext<UpdateHub>()));
private IHubContext _context;
private UpdateBroadcast(IHubContext context)
{
_context = context;
}
public static UpdateBroadcast Instance
{
get { return _instance.Value; }
}
public void UpdatePost(Post post)
{
_context.Clients.All.updatePost(post);
}
}
In my MVC Controller I am calling the UpdatePost method:
public JsonResult AddPost(Post post)
{
UpdateBroadcast broadcaster = UpdateBroadcast.Instance;
Post result = dbFunctions.AddPost(post);
broadcaster.UpdatePost(post);
return Json(new { success = result != null }, JsonRequestBehavior.DenyGet);
}
When I debug the code, I can see that UpdatePost is executed but there is no activity on the client side. My client-side function is like this:
$(function () {
var update = $.connection.updateHub;
update.client.updatePost = function (data) {
alert("called update post");
};
});
I don't seem to understand what is causing this.
Please check below 2 links. I got really helpful with successfully implementation of signalR. Hopefully, this links help you.
https://github.com/vgheri/ChatR
http://www.codeproject.com/Articles/524066/SignalR-Simple-Chat-Application-in-Csharp

ASP.NET XSOCKETS Messenger Project Does Not Work

I make an asp.net Messenger WebProject using XSockes.
When run this project onopen and onconnected events its happens.
but wen send message does not work.
what is my fault?
Startup Code:
[assembly: OwinStartupAttribute(typeof(XsocketTest1.Startup))]
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseXSockets(true);
}
}
Starter Code:
[assembly: PreApplicationStartMethod(typeof(XsocketTest1.Starter), "Start")]
namespace XsocketTest1
{
public class Starter
{
private static IXSocketServerContainer container;
public static void Start()
{
container = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>();
container.Start();
}
}
}
Controller Code:
public class Chat : XSocketController
{
public string UserName { get; set; }
public void ChatMessage(string message)
{
this.InvokeToAll(message, "chatmessage");
}
}
And JavaScript Code:
$(function () {
try{
var controler = new XSockets.WebSocket('ws://localhost:34853', ['chat']);
var conn = controler.controller('chat');
conn.onopen = function () {
}
conn.onconnected = function () {
console.log('socket connected');
conn.controller('chat').chatmessage = function (data) {
console.log(data.Text);
};
};
}
catch(e)
{
alert(e);
}
$(document).ready(function () {
$("#btnSend").click(function () {
try{
conn.invoke('chatmessage', {
Text: 'Calling chatmessage on server and passing a part of the complex object'
});
}
catch(e)
{ alert(e);}
});
});
});
The code looks pretty weird...
Take a look here: http://xsockets.net/docs/4/installing-xsocketsnet
And you will see that you have duplicate startup classes... All you need is the "usexsockets" part if you use owin and win8+ (also mentioned in the docs).
Your JavaScript might work but is very confusing since it seems like you have misunderstood the difference between a connection and a controller in xsockets.

Dashboard Authorization (self-hosted as a Windows service)

I have a Hangfire instance hosted in a windows service using Topshelf:
static void Main()
{
HostFactory.Run(x =>
{
x.Service<Application>(s =>
{
s.ConstructUsing(name => new Application());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Hangfire Windows Service Sample");
x.SetDisplayName("Hangfire Windows Service Sample");
x.SetServiceName("hangfire-sample");
});
}
private class Application
{
private IDisposable host;
public void Start()
{
host = WebApp.Start<Startup>("http://localhost:12345");
Console.WriteLine();
Console.WriteLine("Hangfire Server started.");
Console.WriteLine("Dashboard is available at {0}/hangfire", configSettings.Jobs.EndPoint);
Console.WriteLine();
}
public void Stop()
{
host.Dispose();
}
}
My StartUp class is pretty basic:
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration.UseSqlServerStorage(
"DefaultConnection",
new SqlServerStorageOptions {QueuePollInterval = TimeSpan.FromMinutes(1)});
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
AuthorizationFilters = new[] { new AuthorizationFilter() }
});
app.UseHangfireServer();
}
I'm trying to use a custom authorization filter:
public class AuthorizationFilter : IAuthorizationFilter
{
public bool Authorize(IDictionary<string, object> owinEnvironment)
{
var context = new OwinContext(owinEnvironment);
return context.Authentication.User.Identity.IsAuthenticated;
}
}
I was hoping to use context.Authentication.User to authenticate but it always returns null.
Is there any way to make this work for a self-hosted hangfire service?

connect to signalr hub

I have created a simple SignalR hub inside a console application:
class Program
{
static void Main(string[] args)
{
using (WebApp.Start<Startup>("http://localhost:1968"))
{
Console.WriteLine("Server running!");
Console.ReadLine();
}
}
}
public static class UserHandler
{
public static HashSet<string> ConnectedIds = new HashSet<string>();
}
[HubName("echo")]
public class EchoHub : Hub
{
public void Say(string message)
{
Trace.WriteLine("hub: "+message);
Clients.All.AddMessage(message);
}
public override Task OnConnected()
{
UserHandler.ConnectedIds.Add(Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected()
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected();
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
When I try to connect this from a Silverlight App, it succeeds:
static Microsoft.AspNet.SignalR.Client.HubConnection signalR { get; set; }
public static Microsoft.AspNet.SignalR.Client.IHubProxy signalRhub { get; set; }
public static void StartSignalR()
{
var url = "http://localhost:1968";
signalR = new Microsoft.AspNet.SignalR.Client.HubConnection(url);
signalR.Received += signalR_Received;
signalRhub = signalR.CreateHubProxy("echo");
signalR.Start().Wait();
signalRhub.Invoke("Say", "hub invoked");
}
My next step is to connect the SignalR hub from jquery:
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery.signalR-2.1.0.js"></script>
<script>
$(function ()
{
var connection = $.hubConnection("http://localhost:1968");
connection.start()
.done(function () {
console.log('connected');
connection.send("success?");
})
.fail(function (a) {
console.log('not connected'+a);
});
});
</script>
When I try to run this script, it gives the error:
"XMLHttpRequest cannot load localhost:1968/signalr/negotiate?clientProtocol=1.4&_=1404978593482. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>http://localhost:55282</code> is therefore not allowed access."
Why can I connect to the hub from my Silverlight page (hosted in localhost:3926)
and fails it when I run the jquery script (hosted in localhost:55282)?
What can I do to get a working connection between my jQuery and SignalR hub?
Change
$(function ()
{
var connection = $.hubConnection("http://localhost:1968");
connection.start()
.done(function () {
console.log('connected');
connection.send("success?");
})
.fail(function (a) {
console.log('not connected'+a);
});
});
to
$(function ()
{
var connection = $.hubConnection("http://localhost:1968");
var hub = connection.createHubProxy("echo");
hub.on("AddMessage", Method);
connection.start({ jsonp: true })
.done(function () {
console.log('connected');
hub.say("success?");
})
.fail(function (a) {
console.log('not connected'+a);
});
});
function Method(messageFromHub)
{
alert(messageFromHub);
}
and
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
to
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR(new HubConfiguration() { EnableJSONP = true });}
}
It should do.
app.MapSignalR(new HubConfiguration() { EnableJSONP = true });}
and
connection.start({ jsonp: true })
Will allow cross site request
RPC on Server in SignalR with createHubProxy():
Thanks to the answer from Vishal Ravlani
But for me
hub.say("success?");
doesn't work! (Does it work for you?)
I have to write:
hub.invoke('say','success?');
And SignalR has automatically detected CrossOrigin on Client.
On Server I have used:
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.RunSignalR();
});
which was described on: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#crossdomain

No clients available in SignalR Hub context

I am new to SignalR and am experimenting with setting up a self host service that I can use to send events to other applications. I am having a problem getting a method to be called on all clients. In the code below _context.Clients.All is always empty. Any Ideas?
Test Method:
var server = new SignalRServer();
server.Start("http://localhost:8555");
var hubConnection = new HubConnection("http://localhost:8555");
var proxy = hubConnection.CreateHubProxy("testHub");
var executed = false;
proxy.On("testMethod", () =>
{
executed = true;
});
hubConnection.Start().Wait();
var hub = new TestHubContext(GlobalHost.ConnectionManager.GetHubContext<TestHub>());
hub.Test();
hubConnection.Stop();
server.Stop();
Self host server:
public class SignalRServer
{
private IDisposable _signalR;
public void Start(string url)
{
_signalR = WebApp.Start<SignalRStartup>(url);
}
public void Stop()
{
_signalR.Dispose();
}
}
public class SignalRStartup
{
public static IAppBuilder App = null;
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
Hub:
public class TestHub : Hub
{
}
public class TestHubContext
{
private IHubContext _context;
public TestHubContext(IHubContext context)
{
_context = context;
}
public void Test()
{
if (_context != null)
{
// At this poing _context.Clients.All is always empty
_context.Clients.All.testMethod();
}
}
}
I think your context / client connections are fine. Without further information I'm guessing your problem is that you are closing your connection and server too quickly after calling hub.Test()
Comment out the two .Stop() calls (and stick a Console.ReadLine in there to keep the console open) and see what happens

Categories

Resources