SignalR cannot read property 'chatterHub' undefined - asp.net-mvc-4

My little chat project is barking at me "Uncaught TypeError: Cannot read property 'chatterHub' of undefined"
I must have something out of order. I checked in Chrome inspector the signalr/hubs defines 'chatterHub'. Below is signalr/hubs. (is it generated? if yes, by what and when?)
/*!
* ASP.NET SignalR JavaScript Library v2.0.1
* http://signalr.net/
*
* Copyright Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the Apache 2.0
* https://github.com/SignalR/SignalR/blob/master/LICENSE.md
*
*/
/// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
/// <reference path="jquery.signalR.js" />
(function ($, window, undefined) {
/// <param name="$" type="jQuery" />
"use strict";
if (typeof ($.signalR) !== "function") {
throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");
}
var signalR = $.signalR;
function makeProxyCallback(hub, callback) {
return function () {
// Call the client hub method
callback.apply(hub, $.makeArray(arguments));
};
}
function registerHubProxies(instance, shouldSubscribe) {
var key, hub, memberKey, memberValue, subscriptionMethod;
for (key in instance) {
if (instance.hasOwnProperty(key)) {
hub = instance[key];
if (!(hub.hubName)) {
// Not a client hub
continue;
}
if (shouldSubscribe) {
// We want to subscribe to the hub events
subscriptionMethod = hub.on;
} else {
// We want to unsubscribe from the hub events
subscriptionMethod = hub.off;
}
// Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
for (memberKey in hub.client) {
if (hub.client.hasOwnProperty(memberKey)) {
memberValue = hub.client[memberKey];
if (!$.isFunction(memberValue)) {
// Not a client hub function
continue;
}
subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
}
}
}
}
}
$.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.chatterHub = this.createHubProxy('chatterHub');
proxies.chatterHub.client = { };
proxies.chatterHub.server = {
send: function (name, message) {
return proxies.chatterHub.invoke.apply(proxies.chatterHub, $.merge(["Send"], $.makeArray(arguments)));
}
};
proxies.products = this.createHubProxy('products');
proxies.products.client = { };
proxies.products.server = {
add: function (newProduct) {
return proxies.products.invoke.apply(proxies.products, $.merge(["Add"], $.makeArray(arguments)));
},
getAll: function () {
return proxies.products.invoke.apply(proxies.products, $.merge(["GetAll"], $.makeArray(arguments)));
},
remove: function (ProductId) {
return proxies.products.invoke.apply(proxies.products, $.merge(["Remove"], $.makeArray(arguments)));
},
update: function (updatedProduct) {
return proxies.products.invoke.apply(proxies.products, $.merge(["Update"], $.makeArray(arguments)));
}
};
return proxies;
};
signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());
}(window.jQuery, window));
And here is Chatter.cshtml
#{
ViewBag.Title = "Chatter";
}
<h2>Welcome #ViewBag.UserName!</h2>
<div id="container">
<input type="text" id="message" />
<input type="button" id="sendMessage" value="Send " />
<input type="hidden" id="displayName" />
<ul id="discussion"> </ul>
</div>
#section Scripts {
#Scripts.Render("~/bundles/signalr")
<script src="/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script src="/Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
// the client proxy object chat takes all the work communicating to the server
var chat = $.connection.chatterHub; // client proxy object starts lowercase. The server Class starts uppercase
// dynamically defines function addNewMessageToPage that corresponding to the one defined in the ChatterHub on server side
// this is what the server is to call to send messages to each clients
chat.client.addNewMessageToPage = function (name,message) {
$("#discussion").append("<li>" + (new Date).toString("HH:mm:ss") + "<strong>" + htmlEncode(name) + "</strong>" + htmlEncode(message) + "</li>");
};
$("#displayName").val('#ViewBag.UserName');
$("#message").focus();
// a ready function for SignalR
$.connection.hub.start().done(function () {
// click event to send username and message to the server and all clients
$("#sendMessage").click(function () {
chat.server.send($("#displayName").val(), $("#message").val());
$("#message").focus();
});
});
$("#message").keypress(function (event) {
if (event.which === 13) $("#sendMessage").click();
});
});
function htmlEncode(value) {
var encodedValue = $("<div />").text(value).html();
return encodedValue;
}
</script>
}
Can anyone tell what is missing or out of order?
Thanks,

I found it. the page source shown in Chrome inspector like this
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="/Scripts/jquery-ui-1.10.3.js"></script>
<script src="/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script src="/Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
// the client proxy object chat takes all the work communicating to the server
var chat = $.hubConnection.chatterHub; // client proxy object starts lowercase. The server Class starts uppercase
Obviously jquery-2.0.3 was loaded twice. I removed
<script src="/Scripts/jquery-2.0.3.min.js"></script>
and it worked.

Related

Using dropzone.js in vue, calling function with image file name

I'm having a hard time getting anything to work with this the way I need it, but I have a working dropzone instance in my Vue project.
I can upload the image and call functions within the dropzone code, however, I need to call a function directly from the form in the html in order to send the 'card' object.
All I need to do is call a function when a file is added through the dropzone form, with the filename.
My code:
<div class="uk-width-3-10">
<form v-on:change="imageChange(card)" method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
class="dropzone" v-bind:id="'dropzone-'+i">
</form>
</div>
...
imageChange(Card){
console.log('working');
},
addCard(){
Vue.nextTick(function () {
new Dropzone("#dropzone-"+cardIndex, {
maxFilesize: 12,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file) {
console.log(file.upload.filename);
var name = file.upload.filename;
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
this.on("addedfile",
function(file) {
instance.imageZoneNames.push({name: file.upload.filename});
console.log(file);
console.log(instance.imageZoneNames);
});
}
});
});
}
Dropzone has many events, You used removedfile() event! there is another event called addedfile() and executes when a file is added to the dropzone list
imageChange(card) {
console.log(card)
},
addCard() {
Vue.nextTick(() => {
new Dropzone('#dropzone-` + cardIndex, {
addedfile(file) {
this.imageChange(file);
}
}
}
}

How to copy a codepen.io example into a .vue

I found a codepen.io example (https://codepen.io/srees/pen/pgVLbm) I want to play around with in the context of a .vue app I'm working on, and I need some help transferring the <script> section over.
I copied the HTML chunk into a <template> and the CSS into a <style>. I've confirmed the .vue file works within the broader context (content loads when the <script> is commented out. I also placed <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" /> immediately before my <script> to resolve the $ not defined error I was getting. Is there something I need to import into App.vue or into this particular .vue file? When I leave <script> uncommented, I simply get a blank page loaded.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
<script>
var hidWidth;
var scrollBarWidths = 40;
...
you could define a method like this:
methods: {
renderStuff: function () {
var hidWidth;
var scrollBarWidths = 40;
var widthOfList = function(){
var itemsWidth = 0;
$('.list li').each(function(){
var itemWidth = $(this).outerWidth();
itemsWidth+=itemWidth;
});
return itemsWidth;
};
var widthOfHidden = function(){
return (($('.wrapper').outerWidth())-widthOfList()-getLeftPosi())-
scrollBarWidths;
};
var getLeftPosi = function(){
return $('.list').position().left;
};
var reAdjust = function(){
if (($('.wrapper').outerWidth()) < widthOfList()) {
$('.scroller-right').show();
}
else {
$('.scroller-right').hide();
}
if (getLeftPosi()<0) {
$('.scroller-left').show();
}
else {
$('.item').animate({left:"-="+getLeftPosi()+"px"},'slow');
$('.scroller-left').hide();
}
}
reAdjust();
$(window).on('resize',function(e){
reAdjust();
});
$('.scroller-right').click(function() {
$('.scroller-left').fadeIn('slow');
$('.scroller-right').fadeOut('slow');
$('.list').animate({left:"+="+widthOfHidden()+"px"},'slow',function(){
});
});
$('.scroller-left').click(function() {
$('.scroller-right').fadeIn('slow');
$('.scroller-left').fadeOut('slow');
$('.list').animate({left:"-="+getLeftPosi()+"px"},'slow',function(){
});
});
}
}
and run the method on mount like this:
mounted() {
this.renderStuff();
}
Side note, var is not ideal in this day and age. Recommend converting these to let.

Add Group in SignalR on MVC application

How to Add SignalR in mvc i have Already Added in View
<script src='#Url.Content("~/Scripts/jquery.signalR-2.1.2.min.js")'></script>
<script type="text/javascript">
$(function () {
$("#btnPopUpLogin").hide();
var MyHub = $.connection.foxHub;
var BlogId = '#ViewBag.BlogId';
//-------------- Load Messages
LoadClientMessage(MyHub);
//----------------- Start Hub
$.connection.hub.start().done(function () {
LoadEvents(MyHub, BlogId);
});
});
function LoadClientMessage(myHub) {
myHub.client.getMessages = function (userName, message) {
$("#Message").val("");
$("#commentList tbody").prepend('<tr><td>' + userName + '</td><td>' + message + '</td></tr>');
}
}
function LoadEvents(myHub, blogId) {
myHub.server.connect(blogId);
$("#btnComment").click(function () {
#if (User.Identity.IsAuthenticated)
{
<text>
var Message = $("#Message").val();
myHub.server.sendMessage('#WebSecurity.CurrentUserId', '#WebSecurity.CurrentUserName', blogId, Message);
</text>
}
else
{
<text>
$("#btnPopUpLogin").fadeIn(100);
</text>
}
});
}
</script>
and Add One View Table for view as id "commentList". but i also added Hub class to my model.. but it is not working.. my back end code is correctly working.. what i have to do..
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="~/signalr/hubs"></script>
add this...

Using WebRTC getStat() API

Hey I am trying to implement the getstat API in my WebRTC application. Im finding it hard to get any tutorials at all , at a beginners level.
My Application
I created a 2 person chat-room using the peer js framework. so in my application I am using what can be described a "Sneeker-net" for signaling , ie I am manually sharing a peer id with the person I want a chat with via giving them my id in a email lets say then they call that ID . it uses the stun and turn servers to make our connections its a simple peer to peer chat with Html5 and JavaScript which uses the peerjs API.
here is my HTML 5 AND Javascript code
HTML5 code
<html>
<head>
<title> PeerJS video chat with manual signalling example</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type="text/javascript" src="ps-webrtc-peerjs-start.js ></script>
</head>
<body>
<div>
<!-- Video area -->
<div id="video-container">
Your Friend<video id="their-video" autoplay class="their-video"></video>
<video id="my-video" muted="true" autoplay class="my-video"></video> You
</div>
<!-- Steps -->
<div>
<h2> PeerJS Video Chat with Manual Signalling</h2>
<!--Get local audio/video stream-->
<div id="step1">
<p>Please click 'allow' on the top of the screen so we can access your webcam and microphone for calls</p>
<div id="step1-error">
<p>Failed to access the webcam and microphone. Make sure to run this demo on an http server and click allow when asked for permission by the browser.</p>
Try again
</div>
</div>
<!--Get local audio/video stream-->
<!--Make calls to others-->
<div id="step2">
<p>Your id: <span id="my-id">...</span></p>
<p>Share this id with others so they can call you.</p>
<p><span id="subhead">Make a call</span><br>
<input type="text" placeholder="Call user id..." id="callto-id">
Call
</p>
</div>
<!--Call in progress-->
<!--Call in progress-->
<div id="step3">
<p>Currently in call with <span id="their-id">...</span></p>
<p>End call</p>
</div>
</div>
</div>
</body>
</html>
My Javascript file
navigator.getWebcam = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
// PeerJS object ** FOR PRODUCTION, GET YOUR OWN KEY at http://peerjs.com/peerserver **
var peer = new Peer({
key: 'XXXXXXXXXXXXXXXX',
debug: 3,
config: {
'iceServers': [{
url: 'stun:stun.l.google.com:19302'
}, {
url: 'stun:stun1.l.google.com:19302'
}, {
url: 'turn:numb.viagenie.ca',
username: "XXXXXXXXXXXXXXXXXXXXXXXXX",
credential: "XXXXXXXXXXXXXXXXX"
}]
}
});
// On open, set the peer id so when peer is on we display our peer id as text
peer.on('open', function() {
$('#my-id').text(peer.id);
});
peer.on('call', function(call) {
// Answer automatically for demo
call.answer(window.localStream);
step3(call);
});
// Click handlers setup
$(function() {
$('#make-call').click(function() {
//Initiate a call!
var call = peer.call($('#callto-id').val(), window.localStream);
step3(call);
});
$('end-call').click(function() {
window.existingCall.close();
step2();
});
// Retry if getUserMedia fails
$('#step1-retry').click(function() {
$('#step1-error').hide();
step();
});
// Get things started
step1();
});
function step1() {
//Get audio/video stream
navigator.getWebcam({
audio: true,
video: true
}, function(stream) {
// Display the video stream in the video object
$('#my-video').prop('src', URL.createObjectURL(stream));
// Displays error
window.localStream = stream;
step2();
}, function() {
$('#step1-error').show();
});
}
function step2() { //Adjust the UI
$('#step1', '#step3').hide();
$('#step2').show();
}
function step3(call) {
// Hang up on an existing call if present
if (window.existingCall) {
window.existingCall.close();
}
// Wait for stream on the call, then setup peer video
call.on('stream', function(stream) {
$('#their-video').prop('src', URL.createObjectURL(stream));
});
$('#step1', '#step2').hide();
$('#step3').show();
}
Many thanks to anybody who takes time out to help me I am very grateful, as Im only a beginner at WebRTC .
Cheers
Here is my code, which works in both Chrome and Firefox. It traces stats in the browser console. Because Chrome stats are very verbose, I filter them following an arbitrary criteria (statNames.indexOf("transportId") > -1):
function logStats() {
var rtcPeerConn = ...;
try {
// Chrome
rtcPeerConn.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
} catch (e) {
// Firefox
if (remoteVideoStream) {
var tracks = remoteVideoStream.getTracks();
for (var h=0; h<tracks.length; h++) {
rtcPeerConn.getStats(tracks[h], function callback(report) {
console.log(report);
}, function(error) {});
}
}
}
}
You need the rtcPeerConnection, and Firefox requires the stream in addition.
for twilio SDK look at this post:
Is there an API for the chrome://webrtc-internals/ variables in javascript?
var rtcPeerConn =Twilio.Device.activeConnection();
rtcPeerConn.options.mediaStreamFactory.protocol.pc.getStats(function callback(report) {
var rtcStatsReports = report.result();
for (var i=0; i<rtcStatsReports.length; i++) {
var statNames = rtcStatsReports[i].names();
// filter the ICE stats
if (statNames.indexOf("transportId") > -1) {
var logs = "";
for (var j=0; j<statNames.length; j++) {
var statName = statNames[j];
var statValue = rtcStatsReports[i].stat(statName);
logs = logs + statName + ": " + statValue + ", ";
}
console.log(logs);
}
}
});
I advice you to read Real-Time Communication with WebRTC for O'Reilly
It is very useful book for beginners in addition the book will guide you to build your webchat application ste by step using sokcet.io for signaling
the link in the first comment

Show alert after action in mvc3/4

I need to inform user about success/failure of clicked operation. In view I've prepared action link that goes to controller, performs database operation and returns with result. Then I'd like to show alert with message "done" or "failure". Everything should be done without reloading page. I've tried to define #Ajax.ActionLink and text/javascript function but it doesn't work at all... Please help. Thanks in advance.
Robert
Firstly you should include scripts: jquery and jquery.unobtrusive-ajax like:
<head>
...
<script src="#Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
Inside View:
<script type="text/javascript">
function myCallback(data) {
if(!data.Success)
{
alert(data.ErrorMessage);
}
else
{
alert("id: " + data.Id);
}
}
</script>
#Ajax.ActionLink("Actionlink", // <-- Text to display
"GetDeneme", // <-- Action Method Name
new { id = "2"},
new AjaxOptions
{
HttpMethod = "POST", // <-- HTTP method
OnSuccess = "myCallback"
})
In Controller:
public ActionResult GetDeneme(string id)
{
var error = (id == "3");
if (error)
{
return Json(new { Success = false, ErrorMessage = "Error!" });
}
return Json(new { Success = true, Id = id });
}