ASP.NET XSOCKETS Messenger Project Does Not Work - c#

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.

Related

Call js generated from typescript in blazor using IJSObjectReference

Hi I have a question about using Blazor and typescript.
My typescript:
namespace JSInteropWithTypeScript {
export class Generator {
public showAlert(): void {
alert("INTEROP");
}
}
export function Load(): void {
window['generator'] = new Generator();
}
}
JSInteropWithTypeScript.Load();
And here is generated JS:
var JSInteropWithTypeScript;
(function (JSInteropWithTypeScript) {
var Generator = /** #class */ (function () {
function Generator() {
}
Generator.prototype.showAlert = function () {
alert("INTEROP");
};
return Generator;
}());
JSInteropWithTypeScript.Generator = Generator;
function Load() {
window['generator'] = new Generator();
}
JSInteropWithTypeScript.Load = Load;
})(JSInteropWithTypeScript || (JSInteropWithTypeScript = {}));
JSInteropWithTypeScript.Load();
//# sourceMappingURL=generator.js.map
Next I want to call compiled js script so I have a simple component with button:
#namespace Components.Reports.Components.Generator
#inherits ControlsBase
<button class="btn btn-success" #onclick="ShowAlert"> BUTON </button>
In base class for this component I want to lazy load (so i do not need to add every script in _Host just use them when they are needed) this script file and call this function, so I made this contraption:
public class ControlsBase : ComponentBase, IAsyncDisposable
{
private readonly Lazy<Task<IJSObjectReference>> moduleTask;
[Inject]
protected IJSRuntime JsRuntime { get; set; }
public ControlsBase()
{
Task<IJSObjectReference> jsInvokes() => this.JsRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/Components/js/generator.js").AsTask();
this. moduleTask = new Lazy<Task<IJSObjectReference>>(jsInvokes);
}
public async Task ShowAlert()
{
try
{
var module = await moduleTask.Value;
await module.InvokeVoidAsync("showAlert");
}
catch (JSException jsException)
{
logger.Error($"Problem with js interop {jsException}");
}
}
public async ValueTask DisposeAsync()
{
if (moduleTask.IsValueCreated)
{
var module = await moduleTask.Value;
await module.DisposeAsync();
}
}
}
So now I want to call this, my problem/question is when I call compiled js script I am getting
Could not find 'showAlert' ('showAlert' was undefined).
When i use vanilla code like:
export function showAlert() {
alert("INTEROP");
}
it works.
So what am I doing wrong with typescript?
EDIT
Using #Haytam guide I remade my ts to simple:
namespace JSInteropWithTypeScript {
export class Generator {
public ShowAlert(): void {
alert("INTEROP");
}
}
}
function showAlert(): void {
let generator = new JSInteropWithTypeScript.Generator();
generator.ShowAlert();
}
And it compiles to js:
var JSInteropWithTypeScript;
(function (JSInteropWithTypeScript) {
var Generator = /** #class */ (function () {
function Generator() {
}
Generator.prototype.ShowAlert = function () {
alert("INTEROP");
};
return Generator;
}());
JSInteropWithTypeScript.Generator = Generator;
})(JSInteropWithTypeScript || (JSInteropWithTypeScript = {}));
function showAlert() {
var generator = new JSInteropWithTypeScript.Generator();
generator.ShowAlert();
}
But to work properly I need to manually add export before function in js.I know that the cause for this error is that TypeScript, by default, produces JavaScript code that is designed for use through various package managers that cater to the exports and modules. Such tools are usully Node.js or WebPack. I can turn it off by using tsconfig:
{
"compilerOptions": {
"module": "none"
}
}
But still js interop works only when function is marked as export in js. Any ideas how to handle that?
EDIT2:
I think problem lays in lazy loding, added generated js script as static resource:
<script src="_content/Components/js/generator.js"></script>
and used code:
public async Task OnClick()
{
try
{
await this.JsRuntime.InvokeVoidAsync("showAlert");
}
catch (JSException jsException)
{
logger.Error($"Problem with js interop {jsException}");
}
}
In my component base and it is alive, but still just for curiosity I want to make n this lazy loading. Any suggestions would be appreciated.
I see two problems here:
Blazor JS Isolation works with JavaScript Modules. Putting functions in window is not required anymore, that's why they added this isolation in the first place.
Since Blazor JS Isolation works with JS modules, it expects exported functions directly. I believe no matter what you try, the generated JS from using TS classes will not work.
I think you should try to export the functions directly.
EDIT
Based on your latest edit, doesn't this work?
export function showAlert(): void {
let generator = new JSInteropWithTypeScript.Generator();
generator.ShowAlert();
}

Signal Refresh issue on some clients in asp.net mvc

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();
});

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

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