SignalR 2.0.0.0: $.connection is undefined - c#

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--

Related

signalr/hubs file does not get generated

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.

C# SignalR push notification real-time from Controller doesnt work

I've been trying to run several procedural code on server with parameter that i put on form and execute with MVC Controller. I want every step (method / function) on controller that have been called will update information to the client Web real-time.
I've been trying to use SignalR to update realtime push notification / information to client, its work with client trigger but when i trying to call hub from controller it doest work.
here is my Controller Code :
[HttpPost]
public string data (Models.ExModel data)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub1>();
//Execute Code
//send to client
hub.Clients.All.Message(data.apaAja);
return "success";
}
here is my client code :
<h2>Index</h2>
#Ajax.BeginForm("data", "Home", FormMethod.Post, null) {
<div class="input-group">
<span>Apa Aja</span>
#Html.EditorFor(model => model.apaAja, new { htmlhtmlAttributes = new { #id = "apaAja" } })
</div>
<div class="input-group">
<span> Boleh </span>
#Html.EditorFor(model => model.boleh, new { htmlhtmlAttributes = new { #id = "boleh" } })
</div>
<button id="subm" type="submit">Submit</button>
<div id="container">
</div>
#section scripts{
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(document).ready(function () {
var c = $.connection.myHub1;
c.client.messageSend = function (message) {
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#container').append('<li> < strong >' + 'Info Message : ' +
'</strong >: ' + encodedMsg + '</li >');
};
$.connection.hub.start();
});
</script>
and here is my Hub Class :
namespace SignalR1.Hubs
{
public class MyHub1 : Hub
{
public void Message(string message)
{
Clients.All.messageSend(message);
}
}
}
You have a client-side callback called messageSend, then in your hub you rightly have Clients.All.messageSend, however when you use the GlobalHost.ConnectionManager.GetHubContext you are accessing the hub context not the hub class itself.
So change it to:
var hub = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub1>();
//you don't actually have access to the MyHub1 class at this point
// instead of
// hub.Clients.All.Message(data.apaAja);
// you need
hub.Clients.All.messageSend(data.apaAja);
In fact, the hub class method becomes slightly redundant when using this mechanism. I normally use the hub class for managing connections and clients using the overrides for onconnected etc...

How to populate dropdownlist using WCF Rest AngularJs

How to populate dropdownlist using WCF Rest Service:
First, this is my code to get service:
service.js
(function (app) {
app.service("GetCategoryService", function ($http) {
this.GetCategory = function () {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetCategory/");
};
});
})(angular.module('entry'));
Entry.Ctrl
(function (app) {
'use strict';
app.controller('entryCtrl', entryCtrl);
entryCtrl.$inject = ['$scope'];
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
//To Get Category
$scope.Category = function () {
var promiseGet = GetCategoryService.GetCategory();
promiseGet.then(function (pl) { $scope.GetCategory = pl.data },
function (errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
}
})(angular.module('entry'));
This is entry.html
<div class="dropdown">
<select ng-model="Category" ng-options="item.ITEM_TEXT for item in Category"></select>
</div>
WCF Output JSON like:
[{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}]
I don't know how to passing this to html, what I'm doing like this is not working. please help. thank
Make sure you have set ng-model different from the array name, also inject the service into your controller,
entryCtrl.$inject = ['$scope', 'GetCategoryService'];
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Category = [{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}];
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select ng-model="selected" ng-init="selected = Category[0]" ng-options="item.ITEM_TEXT for item in Category"></select>
</body>
</html>

SignalR Server Desktop application with Mosync mobile client application

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

500 Internal Server error when trying to pass messages between SignalR self-hosted server and client

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.

Categories

Resources