few line is not clear to me. so please someone explain how those line will work.
<div id="currentHitCount"></div>
<script type="text/javascript">
$(function () {
var connection = $.hubConnection();
var hub = connection.createProxy("hitCounter");
hub.on("showHitCount", function (hitCount) {
if (hitCount > 1) {
$('#currentHitCount')
.html("This site has had " + hitCount + " hits.");
}
else {
$('#currentHitCount')
.html("This site has had " + hitCount + " hit.");
}
});
connection.start().done(function () {
hub.invoke("addHit");
});
});
</script>
1) why createproxy() is used? when it is required?
2) what is the meaning of hub.invoke("addHit"); ?
what will happen when we call hub.invoke ?
3) when this function will be called hub.on("showHitCount", function (hitCount) ?
please explain the code in details. thanks
1) It creates a hub proxy, you can also do
$.connection.hitCounter.client.showHitCount = function(hitCount) {
};
2) addHit is a server side method on the hitCounter Hub
3) My guess is that code in the addHit method will trigger the client side method showHitCount
Related
I'm having an issue with the Googlemaps API, specifically the places library. This is all using WordPress.
I've built a sign up form here: http://dabble.market/cms/sign-up/
I replicated exactly what I built in my localhost. I have the bottom field labelled: "Address which will be shown on the our map. Start typing & choose from the list." hooked up to the Googlemaps API using the places library. It then ran Google's address lookup / autocomplete on it perfectly fine. Once the Address autocomplete ran, it served the full address and lat / lng coords back to the user using the JS written below.
Now that I've migrated it over to a live version of the site, the address lookup functionality no longer works.
Any help would be really appreciated thanks.
var address, latitude, longitude, addressString;
function initialize() {
google.maps.event.addDomListener(window, 'load', function () {
var options = {
componentRestrictions: {country: "nz"}
};
var input = document.getElementById('txtPlaces');
var places = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
if (!place.geometry) {
jQuery('#error').css("display", "inherit");
return;
}
else{
jQuery('#error').css("display", "none");
}
address = place.formatted_address;
latitude = place.geometry.location.lat();
longitude = place.geometry.location.lng();
addressString = "Address: " + address + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude;
jQuery('#geocoords-hidden').val(addressString);
jQuery('#addressContainer').css("display", "inherit");
jQuery('#addressInfo').text("Address: " + address);
jQuery('#addressInfo1').text("Latitude: " + latitude);
jQuery('#addressInfo2').text("Longitude: " + longitude);
});
});
}
OK - I've figured it out.
I removed the function initialize() { ... }
and replaced it with:
jQuery(document).ready(function($){ ... });
We are having an issue with signalR. We have an auction site that runs on signalr for real time bidding. We fixed some issues with the browser and everything seemed to be working well. Then we installed new relic on our server and noticed that every minute we are getting http error code 400 on signalr connect, reconnect and abort. Here's a screenshot:
SignalR connect and reconnect are the most time consuming operations of the site according to new relic.
Here is SignalR backend code (We use sql server as signalr backplane):
public class SignalRHub : Hub
{
public void BroadCastMessage(String msg)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
hubContext.Clients.All.receiveMessage(msg);
}
}
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
string appString=string.Empty;
//Gets the connection string.
if (System.Configuration.ConfigurationSettings.AppSettings["SignaRScaleoutConn"] != null)
{
appString = System.Configuration.ConfigurationSettings.AppSettings["SignaRScaleoutConn"].ToString();
}
GlobalHost.DependencyResolver.UseSqlServer(appString);
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromMinutes(15); //I added this timeout, but it is not required.
app.MapSignalR();
}
}
The javascript client looks like this, it's lengthy, but most of it is jQuery to affect the DOM, I include it all in case something may be wrong inside it.
$(function () {
var chatProxy = $.connection.signalRHub;
$.connection.hub.start();
chatProxy.client.receiveMessage = function (msg) {
var all = $(".soon").map(function () {
var hiddenModelId = $("#hiddenListingId");
if (msg == hiddenModelId.val()) {
$.ajax({
async: "true",
url: "/Listing/AuctionRemainingTime",
type: "POST",
dataType: 'json',
data: '{ "listingID": "' + msg + '"}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null) {
SoonSettings.HasReloadedThisTick = false;
var element = document.getElementById(msg);
var obj = JSON.parse(data)
// For Clock Counter End Date Time Interval
// Adds 2 minutes to the soon clock when bid is close to finishing.
var hdID = "hdn" + obj.ListingId;
var hdValue = $("#" + hdID);
if (obj.EndDate != hdValue.val()) {
SoonSettings.HasUpdated = false; //Allows clock to change color once it gets under two minutes.
$('#' + hdID).val(obj.EndDate);
Soon.destroy(element);
Soon.create(element, { //Recreates clock with the before 2 minute tick event.
'due': 'in ' + obj.Seconds + ' seconds',
'layout':'group label-uppercase',
'visual':'ring cap-round progressgradient-00fff6_075fff ring-width-custom gap-0',
'face':'text',
'eventTick': 'tick'
});
}
var highbid = obj.HighBidderURL;
// For Date Ends Info.
var ListingEndDate = $("#tdAuctionListingEndDate");
if (obj.EndDate != ListingEndDate.val()) {
$('#' + hdID).val(obj.EndDate);
ListingEndDate.text(obj.EndDate + " Eastern");
ListingEndDate.effect("pulsate", { times: 5 }, 5000);
}
else
{
$(".Bidding_Current_Price").stop(true, true); ///Removes the pulsating effect.
$(".Bidding_Current_Price").removeAttr("style"); //Removes unnecessary attribute from HTML.
}
//Bid div notification.
if (obj.AcceptedActionCount.replace(/[^:]+:*/, "") > 0) {
if (obj.Disposition != '' && obj.Disposition != null) {
if (obj.Disposition == "Neutral") {
$("#spanNeutralBid").show();
$("#divOutbidNotification").hide();
$("#spanPositiveBid").hide();
$("#divProxyBidNotification").hide();
}
else if (obj.Disposition == "Positive") {
$("#spanPositiveBid").show();
$("#divOutbidNotification").hide();
$("#spanNeutralBid").hide();
$("#divProxyBidNotification").hide();
}
else if (obj.Disposition == "Negative") {
$("#divOutbidNotification").show();
$("#spanNeutralBid").hide();
$("#spanPositiveBid").hide();
$("#divProxyBidNotification").hide();
}
else {
$("#divOutbidNotification").hide();
$("#spanNeutralBid").hide();
$("#divProxyBidNotification").hide();
$("#spanPositiveBid").hide();
}
}
}
// For Highlight Current Price when it is Updated
var hdCurrentPrice = $("#hdnCurrentPrice");
if (obj.CurrentPrice != hdCurrentPrice.val()) {
$(".Bidding_Current_Price").text(obj.CurrentPrice);
$(".Bidding_Current_Price").effect("pulsate", { times: 5 }, 5000);
$("#hdnCurrentPrice").val(obj.CurrentPrice);
}
else {
$(".Bidding_Current_Price").stop(true, true);
$(".Bidding_Current_Price").removeAttr("style");
}
// For ReservePrice Status
$("#spanReservePriceStatus").html(obj.ReservePriceStatus);
$("#smallReservePriceStatus").html(obj.ReservePriceStatus);
// For Bid Count
var spanBidCounter = $("#spanBidCount");
$(spanBidCounter).text(obj.AcceptedActionCount);
var stringAppend = "<tr id='trhHighBidder'><td><strong>HighBidder</strong></td>";
stringAppend += "<td>";
if (obj.isAdmin == true) {
stringAppend += "<a id='anchorHighBid' href=" + obj.HighBidderURL + ">";
stringAppend += "<span id='spanHighBidder'>" + obj.CurrentListingActionUserName + "</span>"
stringAppend += "</a>";
}
else {
stringAppend += "<span id='spanHighBidderAnonymous'>" + obj.CurrentListingActionUserName + "</span>";
}
stringAppend += "</td></tr>";
if (obj.AcceptedActionCount.replace(/[^:]+:*/, "") > 0) {
if ($("#tblAuctionDetail").find("#rowHighBidder").length > 0) {
if ($("#tblAuctionDetail").find("#trhHighBidder").length > 0) {
$("#trhHighBidder").remove();
}
}
else {
//add tr to table
if (!$("#tblAuctionDetail").find("#trhHighBidder").length > 0) {
$('#tblAuctionDetail > tbody > tr:eq(6)').after(stringAppend);
}
}
}
// For High Bidder
if (obj.isAdmin) {
var anchorElement = $("#anchorHighBid");
$(anchorElement).attr("href", obj.HighBidderURL);
var spanHighBidder = $("#spanHighBidder");
$(spanHighBidder).text(obj.CurrentListingActionUserName);
}
else {
var spanAdminHighBid = $("#spanHighBidderAnonymous");
$(spanAdminHighBid).text(obj.CurrentListingActionUserName)
}
}
},
error: function (xhr, textStatus, errorThrown) {
}
});
}
});
};
});
Is there anything wrong with the client or the server signalr code that may need to be changed to avoid these errors happening so often? The 400 code has the tendency of showing up almost every minute. I am very new to signalR and know very little of how to make effective code with it.
The real time bidding in the site does work, it's just to find a way to avoid these constant errors. Any help explaining anything of how signalR works is appreciated.
Thanks,
I'd give a try changing the transportation method of SignalR: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#transport
and check if problem persists.
If possible to get UserAgent from Bad Request log, try to narrow down which browsers get 400 error. I think, maybe, some browsers are not connecting with correct transport method.
I'm trying to get some data from an API in the variable $scope.proposition with the following code
'use strict';
var app = angular.module('app', []);
app.controller('propositionCtrl',['$scope', 'propositionRepository',
function ($scope, propositionRepository) {
// $scope.proposition = { marge_propose: 3 };
function getProposition() {
propositionRepository.getProposition(function (result) {
$scope.proposition = result;
console.log("we put the json in the scope variable");
}
)
}
getProposition();
$scope.proposition = {marge_propose : 3};
}])
app.factory('propositionRepository', function ($http) {
return {
getProposition: function (callback) {
$http.get('/api/propositionapi/3');
console.log("we call the api");
}
}
})
With the following view
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-controller="propositionCtrl">
<p>{{ proposition.marge_propose}}</p>
</div>
It does not work, but when I uncomment the $scope.proposition = { marge_propose: 3 }; everything works just fine.
That's why I assume that it is my getProposition that encounters some problems.
I don't know what it is because firebug actually tells me that the data are well received from the api with the following result
{"$id":"1","t_concours":{"$id":"2","t_proposition":[{"$ref":"1"}],"id":1,"intitule":"test","valeur":10.0},"t_demandeur":{"$id":"3","t_proposition":[{"$ref":"1"}],"id":"1","nom":"dylan","prenom":"bob","note":"A"},"t_index":{"$id":"4","t_proposition":[{"$ref":"1"}],"id":1,"intitule":"test","valeur":10.0},"t_proposition_concurence":null,"id":3,"id_demandeur":"1","date_proposition":"1991-07-05T00:00:00","type":true,"point_de_vente":"01","code":"a","code_sas":"846684","montant_operation_hors_frais":200,"concours_sollicite":10,"duree_concours":10,"type_concours":1,"id_index":1,"apport_personnel":10,"garantie_reelle":true,"in_fine":false,"majoration":1.0,"prospect":true,"primo_accedant":true,"motif_montant":false,"motif_contrepartie":false,"motif_depot_cmne":false,"id_prop_concurence":null,"motif_autre":true,"motif_commentaire":"true","proposition_derogatoire":true,"visa_responsable":"false","marge_grille":5.0,"marge_theorique":7.0,"marge_propose":32.0}
Can someone explain me please where the problem is?
Thanks a lot!
EDIT:
The console log displays "we call the api" but not "we put the json in the scope variable"
'use strict';
var app = angular.module('app', []);
app.controller('propositionCtrl',['$scope', 'propositionRepository',
function ($scope, propositionRepository) {
// $scope.proposition = { marge_propose: 3 };
function getProposition() {
propositionRepository.getProposition(function (result) {
console.log("we put the json in the scope variable");
$scope.proposition = result;
}
)
}
getProposition();
$scope.proposition = {marge_propose : 3};
}])
app.factory('propositionRepository', function ($http) {
return {
getProposition: function (callback) {
$http.get('/api/propositionapi/3').success(callback);
console.log("we call the api");
}
}
})
This code works...
The thing is that I didn't know that $http.get returns a promise, so I forgot to add the .success(callback) in the line
$http.get('/api/propositionapi/3').success(callback);
Now everthing works.
Thanks for the hint MohammedAbbas
You could try to set the extra data as real JSON, eg:
$scope.proposition = { "marge_propose": "3" };
maybe try to console.log in your propositionRepository to view the result you're getting, place a console.log in the getProposition() as well to check if everything is passing trough fine
EDIT:
here's a working fiddle:
http://jsfiddle.net/c1zxp6uo/
bottomline: you don't call the callback, so when you do
$http.get('/api/propositionapi/3').then(function(){callback()})
it should work
I would like to switch to an iframe using pure phantom.js code
Here is my first attempt
var page = new WebPage();
var url = 'http://www.theurltofectch'
page.open(url, function (status) {
if ('success' !== status) {
console.log("Error");
} else {
page.switchToFrame("thenameoftheiframe");
console.log(page.content);
phantom.exit();
}
});
It produces only the source code of the main page. Any idea ?
Notice that the iframe domain is different from the main page domain.
Please give this a try I believe it may be an async issues meaning the iframe is not present when trying to access it. I received the below snippet from another post.
var page = require('webpage').create(),
testindex = 0,
loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
/*
page.onNavigationRequested = function(url, type, willNavigate, main) {
console.log('Trying to navigate to: ' + url);
console.log('Caused by: ' + type);
console.log('Will actually navigate: ' + willNavigate);
console.log('Sent from the page\'s main frame: ' + main);
};
*/
/*
The steps array represents a finite set of steps in order to perform the unit test
*/
var steps = [
function() {
//Load Login Page
page.open("https://www.yourpage.com");
},
function() {
//access your iframe here
page.evaluate(function() {
});
},
function() {
//any other step you want
page.evaluate(function() {
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
//console.log(document.querySelectorAll('html')[0].outerHTML);
});
//render a test image to see if login passed
page.render('test.png');
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] === "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] !== "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
replace
console.log(page.content);
with
console.log(page.frameContent);
Should return the contents of the frame phantomjs switched to.
If the iframe is from another domain you may need to add the --web-security=no option like this:
phantomjs --web-security=no myscript.js
As an additional information, what xMythicx said could be true. Some iframes are rendered via Javascript after page finishes loading. If the iframe contents are empty, then you will need to wait for all resources to finish loading, before you start grabbing stuff from the page. But this is another issue, if you need an answer on this, I suggest you ask a new question about it, and I will answer there.
Had the same problem for iframes and
phantomjs --web-security=no
helped in my case :]
i have been using colorbox lightbox(slideshow) but the problem is whenever i click on the image i get "settings is undefined". which setting is it talking about. i am confused. i tried to change the settings but i can't find what to change. the settings it showed was
if (settings.slideshow && $related[1]) {
start = function () {
$slideshow
.text(settings.slideshowStop)
.unbind(click)
.bind(event_complete, function () {
if (index < $related.length - 1 || settings.loop) {
timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
}
})
.bind(event_load, function () {
clearTimeout(timeOut);
})
.one(click + ' ' + event_cleanup, stop);
$box.removeClass(className + "off").addClass(className + "on");
timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
};
stop = function () {
clearTimeout(timeOut);
$slideshow
.text(settings.slideshowStart)
.unbind([event_complete, event_load, event_cleanup, click].join(' '))
.one(click, function () {
publicMethod.next();
start();
});
$box.removeClass(className + "on").addClass(className + "off");
};
if (settings.slideshowAuto) {
start();
} else {
stop();
}
} else {
$box.removeClass(className + "off " + className + "on");
}
}
what do i have to change here. thanks for any suggestion or help.
You don't change anything there. You are likely getting that error because you are doing someone on your end that is removing the settings data. Show what you are doing, not snippets of code from the plugin.