I saw similar questions on internet but no solution helps.
I'm working on web forms.
Installed SignalR 2.2.2 and jQuery 3.3.1.
my script
<script src='<%: ResolveClientUrl("/Scripts/jquery-3.3.1.min.js") %>'></script>
<script src='<%: ResolveClientUrl("/Scripts/jquery.signalR-2.2.2.min.js") %>'></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var alpha = $.connection.alphaHub;
// Create a function that the hub can call to broadcast messages.
alpha.client.broadcastMessage = function (message) {
alert(message);
//// Html encode display name and message.
//var encodedName = $('<div />').text(name).html();
//var encodedMsg = $('<div />').text(message).html();
//// Add the message to the page.
//$('#discussion').append('<li><strong>' + encodedName
// + '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
alpha.server.display($("parameters here"));
});
});
});
</script>
Error is this
localhost:8888/signalr/hubs not found
Startup.cs (in the same directory as Default.aspx file)
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
Hub class
public class AlphaHub : Hub
{
public void Display(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
I tested same code. Built separate project and it worked there. The problem is in my current project.
Related
The process is : When the .post-thread is clicked, it calls the server through the hub, returns a <p data-id = id class = 'take-thread'>, and appends on foo div. Then I click the <p>, it should run TakeThread at server side.
However, when I click on the newly appended <p>, console.log('test') doesn't fire until I added the code in the star rectangle. I don't understand why. There is already a listener in the Hub.start().done() to trigger the click. Why do I have to do it in the hub client function ?
JS:
var chat = $.connection.chatHub;
chat.client.updateThings(id){
$('.foo').append('<p data-id = "id" class = "take-thread"></p>');
// Why do I need to these code below?
************************************************
* $('.take-thread').on('click', function () { *
* console.log("test"); *
* chat.server.takeThread("blah..."); *
* }); *
************************************************
}
$.connection.hub.start().done(function () {
$('.post-thread').on('click', function () {
chat.server.postThread("Test"); // works
});
$('.take-thread').on('click', function () {
console.log("test");
chat.server.takeThread("blah...");
});
}
C# Hub:
public void PostThread(string title) {
var id = someCalculation();
Clients.All.updateThings(id);
}
public void TakeThread(string title) {
// do things
}
This is a binding problem. Dynamic elements added to the page after document.ready is called do not automatically get rebound. This is what you were doing when you added the second on click event to the updateThings function.
You need to us .on() with a static parentSelector that is there on document.ready (.foo) together with a selector of your dynamic element being added by the SignalR callback (.take-thread).
See this example using standard alerts in place of SignalR: http://jsfiddle.net/kspearrin/0zyoqyxL/
In the end, your Javascript should be updated to the following:
var chat = $.connection.chatHub;
chat.client.updateThings(id){
$('.foo').append('<p data-id="id" class="take-thread"></p>');
}
$.connection.hub.start().done(function () {
$('.post-thread').on('click', function () {
chat.server.postThread("Test"); // works
});
$('.foo').on('click', '.take-thread', function () {
console.log("test");
chat.server.takeThread("blah...");
});
}
Now I am developing server desktop application in c#(visual Studio 2012) using SignalR.
Client Application using Mosync Mobile application(Mobile Platform Independent)
When server application and client application is on same machine(localhost), communication is successfully created and data feed from server to client is working fine. But When i put server application in remote server, Mosync client application is not communicate with server. Could any one help me?
Server side code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.Cors;
using Microsoft.Owin;
using Owin;
namespace SampleSignalRServer
{
public partial class Form1 : Form
{
private IDisposable signalR { get; set; }
const string ServerURI = "http://localhost:8080";
MyHub h = new MyHub();
public Form1()
{
InitializeComponent();
}
private void btnServerStart_Click(object sender, EventArgs e)
{
writeToConsole("Starting server...");
btnServerStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
signalR = WebApp.Start(ServerURI);
}
catch (TargetInvocationException)
{
writeToConsole("Server failed to start. A server is already running on" + ServerURI);
this.Invoke((Action)(() => btnServerStart.Enabled = true));
return;
}
this.Invoke((Action)(() => btnServerStart.Enabled = true));
writeToConsole("Server started at" + ServerURI);
}
public void writeToConsole(string message)
{
if (RichTextBoxConsole.InvokeRequired)
{
this.Invoke((Action)(() => writeToConsole(message)));
return;
}
RichTextBoxConsole.AppendText(message + Environment.NewLine);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (signalR != null)
{
signalR.Dispose();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string msg = txtMessage.Text;
h.Receive(msg);
}
private void timer1_Tick(object sender, EventArgs e)
{
string message = "hi";
// h.Receive(message);
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
Program.mainform.writeToConsole(name + " : " + message);
}
public void Receive(string msg)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.addMessage("Admin", msg);
}
public override Task OnConnected()
{
Program.mainform.writeToConsole("Client Connected:" + Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Program.mainform.writeToConsole("Client DisConnected: " + Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
}
Client mobile application Code(MOsync- Html + Javascript)
<!DOCTYPE html>
<!--
* #file index.html
*
* Template application that shows examples of how to access
* device services from JavaScript using the Wormhole library.
-->
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
<meta name="viewport" content="width=320, user-scalable=no">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Wormhole Template App</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="js/wormhole.js"></script>
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.signalR-2.0.3.min.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script type="text/javascript">
function StartConnection()
{
alert("Start Button Clicked");
$.connection.hub.url = "http://localhost:8080/signalr";
var chats = $.connection.myHub;
alert(chats);
chats.client.addMessage = function (name, message)
{
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
chats.server.send($('#displayname').val(), $('#message').val());
$('#message').val('').focus();
});
});
}
// Register event listeners.
// The "deviceready" event is sent when the system
// has finished loading.
document.addEventListener(
"deviceready",
displayDeviceInfo,
true);
// Close the application when the back key is pressed.
document.addEventListener(
"backbutton",
function() { mosync.app.exit(); },
true);
</script>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="button" id="sendmessagfe" value="localhost:8080" />
<input type="hidden" id="displayname" />
<input type="button" value="Start" onclick="StartConnection()"/>
<ul id="discussion"></ul>
</div>
</body>
</html>
Assuming your code is ok, which it does at first glance, then it is probably either an IIS or network/infrastructure issue. Have you investigated this possibility?
SignalR is supported on IIS 7.0 and 7.5, but support for extensionless
URLs must be added. To add support for extensionless URLs, see
http://support.microsoft.com/kb/980368
I am trying to run my first SignalR v2 project but with no luck, $.connection is undefined.
Here is the error from web console:
Uncaught TypeError: Cannot read property 'chatHub' of undefined (anonymous function)
k
l.fireWith
p.extend.ready
D
My hub:
using Microsoft.AspNet.SignalR;
namespace InstantMessage
{
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
}
}
Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(InstantMessage.Startup))]
namespace InstantMessage
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Fontend:
<head>
.....
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
</head>
<body>
<h2>Instant Message Demo</h2>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
console.log($.connection);
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</body>
It seems like the js code in /signalr/hubs is correct, chathub is there and the autogeneration of the file works fine.
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs();
}).disconnected(function () {
// Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
// (instance, shouldSubscribe)
registerHubProxies(proxies, false);
});
proxies.chatHub = this.createHubProxy('chatHub');
proxies.chatHub.client = { };
proxies.chatHub.server = {
hello: function () {
return proxies.chatHub.invoke.apply(proxies.chatHub, $.merge(["Hello"], $.makeArray(arguments)));
}
};
return proxies;
};
Should also mention that I installed Signalr from nuget and I am using VS2012.
Removing BundleConfig.RegisterBundles(BundleTable.Bundles); from Global.asax.cs fixed this for me. I encountered this problem because jQuery was being included twice.
Place a metatag like the following just before your ChatHub Class definition
[HubName("chatHub")]
Is your reference to jquery correct? The SignalR package currently installs 1.6.4--
I'm trying to work up a simple example of a SignalR self hosted server on a Mono solution to demo to our executive department. I've followed the github example code, and I have half of the functionality working. When the 'broadcast' button is pushed, the message in the text box is echoed in the server console, but it does not get broadcast back to the client.
The server code:
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
//Initialize your application
new AppHost().Init();
WebApplication.Start<Startup>("http://127.0.0.1:10000");
}
protected void Application_BeginRequest(object src, EventArgs e)
{
this.Context.Response.AddHeader("Access-Control-Allow-Headers", "accept,origin,authorization,content-type");
#if DEBUG
Profiler.Start();
#endif
}
protected void Application_EndRequest(object src, EventArgs e)
{
#if DEBUG
Profiler.Stop();
#endif
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapHubs(new HubConfiguration { EnableCrossDomain = true });
}
}
public class Chat : Hub
{
public void Send(string message)
{
Console.WriteLine(message);
Clients.All.addMessage(message);
}
}
}
The client code:
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"> </script>
<script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<!-- If this is an MVC project then use the following -->
<!-- <script src="~/signalr/hubs" type="text/javascript"></script> -->
<script src="http://127.0.0.1:10000/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://127.0.0.1:10000/signalr";
$.connection.hub.logging = true;
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
// Start the connection
$.connection.hub.start({ jsonp: true }).done(function() {
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val());
});
});
});
</script>
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
</div>
When I start the client up, I do get a strange error in the negotiation process, which seems strange since the client can successfully push messages to the server.
[17:13:54 GMT-0400 (EDT)] SignalR: Auto detected cross domain url. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Negotiating with 'http://127.0.0.1:10000/signalr/negotiate'. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: SignalR: Initializing long polling connection with server. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Attempting to connect to 'http://127.0.0.1:10000/signalr/connect?transport=longPolling&connectionToke…kjVpNzqCLDXzDDRkE&connectionData=%5B%7B%22name%22%3A%22chat%22%7D%5D&tid=2' using longPolling. jquery.signalR.min.js:10
GET http://127.0.0.1:10000/signalr/connect?transport=longPolling&connectionToke…D&tid=2&callback=jQuery191021586751635186374_1366665233871&_=1366665233874 500 (Internal Server Error) jquery-1.9.1.min.js:5
send jquery-1.9.1.min.js:5
b.extend.ajax jquery-1.9.1.min.js:5
s jquery.signalR.min.js:10
(anonymous function) jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Longpolling connected
Any help would be greatly appreciated.
I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project.
The thing is, I want to call a C# method in javascript.
I am curious, is there a way to do this?
Just like below:
C# part:
private GeckoWebBrowser weBrowser;
public browser()
{
InitializeComponent();
Gecko.Xpcom.Initialize("xulrunner");
weBrowser = new GeckoWebBrowser();
weBrowser.Parent = this;
weBrowser.Dock = DockStyle.Fill;
weBrowser.Navigate("test.html");
}
public string loadData(){
//load data from local file.
return str;
}
javascript part:
<script type='text/javascript'>
var data = window.loadData();
alert(data);
</script>
I am new in this area, I’ll appreciate if it is possible!
Important update:
Currently code with event.initMessageEvent does not work because this construction has been replaced on
var event = new MessageEvent('yourEventName', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:
[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.
Hope that helps.
You can add message event listener to your web browser and call your method like this:
private void load()
{
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
#"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
...
private void showMessage(string s)
{
MessageBox.Show(s);
}
Now you can add more msg events to your msg listener (if you need to) and fire them all in the same way.