goBack() {
this.generateCode()
this.offerService.removeAllSelectedProducts(this.offer.products)
.pipe(filter((removedProducts) => removedProducts))
.subscribe(() => this.router.navigate(["/home"]))
}
generateCode() {
let offerCode
if (navigator.onLine) {
this.customerId = localStorage.getItem(LocalstorageKeyEnum.SELECTED_CUSTOMER)
? JSON.parse(localStorage.getItem(LocalstorageKeyEnum.SELECTED_CUSTOMER)).id
: "NEW";
if (this.customerId === "NEW") {
this.countNewOffers = 1;
}
else {
this.loading = true;
let offersByIdObservable = this.offerService.getOpportunityCount(this.customerId)
offersByIdObservable.pipe(untilDestroyed(this))
.subscribe(
(data) => {
this.loading = false;
this.countNewOffers = data + 1;
},
(error) => {
if (error.status === 404) {
this.loading = false;
this.countNewOffers = 1;
}
}
);
}
offerCode = "OF-" + this.customerId + "-" + (this.countNewOffers ? this.countNewOffers : "NEW");
this.offer.code = offerCode;
localStorage.setItem(LocalstorageKeyEnum.OFFER, JSON.stringify(this.offer));
} else {
this.loading = false;
}
}
}
I have this two functions, when I click on a button I call the function goBack() that launches the generateCode()
This function (generateCode()) makes the request (the status code is 200). I have tried to debug and it doesn't enter subscribe data or error, so this.countNewOffers results undefined.
I don't understand why it doesn't enter in data or error, but the api call is a 200 with blank response. (but if I call from another place, like swagger, it works and give me back a number)
Related
I have the following function that I wish to turn into a promise:
const blockRequest = (context) => {
let blockRequest = false;
let limitLocation;
const generalLocation = "/limits/general/limits";
let generalTime;
let generalNum;
let limitTime;
let limitNum;
const newTime = new Date().getTime();
if (context.auth != undefined) {
limitLocation = "/users/"+context.auth.uid+"/limits";
} else {
limitLocation = "/limits/"+context.rawRequest.ip+"/limits";
}
admin.database().ref(generalLocation+"/generalNum")
.set(admin.database.ServerValue.increment(1))
.then(()=>{
return admin.database().ref(generalLocation).once("value");
})
.then((snapshot)=>{
if (snapshot.val() == undefined) {
generalNum = 0;
generalTime = newTime;
} else {
generalTime = snapshot.val().generalTime;
generalNum = snapshot.val().generalNum;
}
if ( newTime - generalTime>3000) {
generalNum = 1;
} else if (newTime - generalTime <=300 &&
generalNum < 300) {
} else {
console.log("General Request Blocked");
blockRequest = true;
}
return admin.database().ref(generalLocation)
.set({generalTime: newTime, generalNum: generalNum});
})
.then(()=>{
if (blockRequest) {
return blockRequest;
} else {
return admin.database().ref(limitLocation+"/limitNum")
.set(admin.database.ServerValue.increment(1));
}
})
.then(()=>{
return admin.database().ref(limitLocation).once("value");
})
.then((snapshot)=>{
if (snapshot.val().limitTime == undefined) {
limitNum = snapshot.val().limitNum;
limitTime = newTime;
} else {
limitTime = snapshot.val().limitTime;
limitNum = snapshot.val().limitNum;
}
if ( newTime - limitTime>10000) {
limitNum = 1;
} else if (newTime - limitTime <=10000 &&
limitNum < 20) {
} else {
console.log("Specific Request Blocked");
blockRequest = true;
}
return admin.database().ref(limitLocation)
.set({limitTime: newTime, limitNum: limitNum});
})
.then(()=>{
console.log(blockRequest)
return blockRequest;
})
.catch((error)=>{
console.log(error.message);
return true;
});
};
I also have a function that I would like to call that looks like:
exports.limiterTest = functions.https.onCall(async(data, context)=>{
const result = await blockRequest(context)
console.log("hello")
});
I would like blockRequest to finish running before anything else in limiterTest runs. I think in order for this to function as I intend, I need blockRequest to return a promise. However, I am not sure how to construct this, especially with the chaining .then and .catch statements.
Thanks for your time!
I wrote logic to read the txt file on every 30 mins from Ajax script(Separate ASP) . This ASP is included on multiple ASP pages by using "Include" ..
this html code contains the below logic..
Reading the data from text file on every 30 mins and stored this data and time on local storage.
So on every page load I checked that last data reading time and compare with current time. if time > 30 mins I am reading the data again ..
But in IIS logs, call repeating on every page loads .Console log is fine ..
foot.asp
<script type="text/javascript">
let currentRequest = 0;
$(window).on("load", function () {
if ($(".cookiealert").hasClass('show')) {
$("#data .popup-main").addClass("cookie-accept");
}
else {
$("#data .popup-main").removeClass("cookie-accept");
}
});
$(document).ready(function () {
config()
});
function getData() {
if (currentRequest == 0) {
ajaxRequest = $.get({
url: "/sample.txt",
cache: false
})
.done(function (data) {
if (data;) {
addDataToStorage(data);//Adding data to localstorage
currentRequest = 1;
}
else {
console.log("data empty");
}
})
.fail(function (data, statusTxt, xhr) {
console.log("Error: " + xhr.status + ": " + xhr.statusText);
})
}
}
let runtimerid = null;
let exctime = "1800000";
function config() {
let localstoragesettime, localstoragedata;
const currentdate = new Date();
localstoragedata = localStorage.getItem("data");
if (localstoragedata === null || localstoragedata === "") {
localstoragesettime = localStorage.getItem("LTime");
if (localstoragesettime === null || localstoragesettime === "") {
getData();
if (runtimerid != null || runtimerid != "") {
clearInterval(runtimerid);
}
runtimerid = setTimeout(function () {
currentRequest = 0;
getData();
}, exctime);
}
}
else {
localstoragesettime = localStorage.getItem("LTime");
if (localstoragesettime != null || localstoragesettime != "") {
const localstoragextime = localStorage.getItem("LTime");
const items = JSON.parse(localstoragextime)
epochdate = EpochToDate(items.ltime);
differ = currentdate.getHours() - epochdate.getHours();
if (differ > 1 || differ < 0) {
getData();
if (runtimerid != null || runtimerid != "") {
clearInterval(runtimerid);
}
runtimerid = setTimeout(function () {
currentRequest = 0;
getData();
}, exctime);
}
else {
if (runtimerid != null || runtimerid != "") {
clearInterval(runtimerid);
}
runtimerid = setTimeout(function () {
currentRequest = 0;
getData();
}, exctime);
}
}
}
}
</script>
I included this foot.asp to other asp files.
The bot replies well when a command is sent.
How do I make the WhatsApp web bot to reply with an image pulled from a URL? I want it to be able to reply with an image pulled from a URL, for example, www.school.com/pic.jpg. On the code if a user text #time it replies with time and Date but I want it to reply with an image.
//
// FUNCTIONS
//
// Get random value between a range
function rand(high, low = 0) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
function getElement(id, parent){
if (!elementConfig[id]){
return false;
}
var elem = !parent ? document.body : parent;
var elementArr = elementConfig[id];
for (var x in elementArr){
var pos = elementArr[x];
if (isNaN(pos*1)){ //dont know why, but for some reason after the last position it loops once again and "pos" is loaded with a function WTF. I got tired finding why and did this
continue;
}
if (!elem.childNodes[pos]){
return false;
}
elem = elem.childNodes[pos];
}
return elem;
}
function getLastMsg(){
var messages = document.querySelectorAll('.msg');
var pos = messages.length-1;
while (messages[pos] && (messages[pos].classList.contains('msg-system') || messages[pos].querySelector('.message-out'))){
pos--;
if (pos <= -1){
return false;
}
}
if (messages[pos] && messages[pos].querySelector('.selectable-text')){
return messages[pos].querySelector('.selectable-text').innerText;
} else {
return false;
}
}
function getUnreadChats(){
var unreadchats = [];
var chats = getElement("chats");
if (chats){
chats = chats.childNodes;
for (var i in chats){
if (!(chats[i] instanceof Element)){
continue;
}
var icons = getElement("chat_icons", chats[i]).childNodes;
if (!icons){
continue;
}
for (var j in icons){
if (icons[j] instanceof Element){
if (!(icons[j].childNodes[0].getAttribute('data-icon') == 'muted' || icons[j].childNodes[0].getAttribute('data-icon') == 'pinned')){
unreadchats.push(chats[i]);
break;
}
}
}
}
}
return unreadchats;
}
function didYouSendLastMsg(){
var messages = document.querySelectorAll('.msg');
if (messages.length <= 0){
return false;
}
var pos = messages.length-1;
while (messages[pos] && messages[pos].classList.contains('msg-system')){
pos--;
if (pos <= -1){
return -1;
}
}
if (messages[pos].querySelector('.message-out')){
return true;
}
return false;
}
// Call the main function again
const goAgain = (fn, sec) => {
// const chat = document.querySelector('div.chat:not(.unread)')
// selectChat(chat)
setTimeout(fn, sec * 1000)
}
// Dispath an event (of click, por instance)
const eventFire = (el, etype) => {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent(etype, true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
el.dispatchEvent(evt);
}
// Select a chat to show the main box
const selectChat = (chat, cb) => {
const title = getElement("chat_title",chat).title;
eventFire(chat.firstChild.firstChild, 'mousedown');
if (!cb) return;
const loopFewTimes = () => {
setTimeout(() => {
const titleMain = getElement("selected_title").title;
if (titleMain !== undefined && titleMain != title){
console.log('not yet');
return loopFewTimes();
}
return cb();
}, 300);
}
loopFewTimes();
}
// Send a message
const sendMessage = (chat, message, cb) => {
//avoid duplicate sending
var title;
if (chat){
title = getElement("chat_title",chat).title;
} else {
title = getElement("selected_title").title;
}
ignoreLastMsg[title] = message;
messageBox = document.querySelectorAll("[contenteditable='true']")[0];
//add text into input field
messageBox.innerHTML = message.replace(/ /gm,'');
//Force refresh
event = document.createEvent("UIEvents");
event.initUIEvent("input", true, true, window, 1);
messageBox.dispatchEvent(event);
//Click at Send Button
eventFire(document.querySelector('span[data-icon="send"]'), 'click');
cb();
}
//
// MAIN LOGIC
//
const start = (_chats, cnt = 0) => {
// get next unread chat
const chats = _chats || getUnreadChats();
const chat = chats[cnt];
var processLastMsgOnChat = false;
var lastMsg;
if (!lastMessageOnChat){
if (false === (lastMessageOnChat = getLastMsg())){
lastMessageOnChat = true; //to prevent the first "if" to go true everytime
} else {
lastMsg = lastMessageOnChat;
}
} else if (lastMessageOnChat != getLastMsg() && getLastMsg() !== false && !didYouSendLastMsg()){
lastMessageOnChat = lastMsg = getLastMsg();
processLastMsgOnChat = true;
}
if (!processLastMsgOnChat && (chats.length == 0 || !chat)) {
console.log(new Date(), 'nothing to do now... (1)', chats.length, chat);
return goAgain(start, 3);
}
// get infos
var title;
if (!processLastMsgOnChat){
title = getElement("chat_title",chat).title + '';
lastMsg = (getElement("chat_lastmsg", chat) || { innerText: '' }).innerText; //.last-msg returns null when some user is typing a message to me
} else {
title = getElement("selected_title").title;
}
// avoid sending duplicate messaegs
if (ignoreLastMsg[title] && (ignoreLastMsg[title]) == lastMsg) {
console.log(new Date(), 'nothing to do now... (2)', title, lastMsg);
return goAgain(() => { start(chats, cnt + 1) }, 0.1);
}
// what to answer back?
let sendText
if (lastMsg.toUpperCase().indexOf('#HELP') > -1){
sendText = `
Cool ${title}! Some commands that you can send me:
1. *#TIME*
2. *#JOKE*`
}
if (lastMsg.toUpperCase().indexOf('#About') > -1){
sendText = `
Cool ${title}! Some commands that you can send me:
*${new Date()}*`
}
if (lastMsg.toUpperCase().indexOf('#TIME') > -1){
sendText = `
Don't you have a clock, dude?
*${new Date()}*`
}
if (lastMsg.toUpperCase().indexOf('#JOKE') > -1){
sendText = jokeList[rand(jokeList.length - 1)];
}
// that's sad, there's not to send back...
if (!sendText) {
ignoreLastMsg[title] = lastMsg;
console.log(new Date(), 'new message ignored -> ', title, lastMsg);
return goAgain(() => { start(chats, cnt + 1) }, 0.1);
}
console.log(new Date(), 'new message to process, uhull -> ', title, lastMsg);
// select chat and send message
if (!processLastMsgOnChat){
selectChat(chat, () => {
sendMessage(chat, sendText.trim(), () => {
goAgain(() => { start(chats, cnt + 1) }, 0.1);
});
})
} else {
sendMessage(null, sendText.trim(), () => {
goAgain(() => { start(chats, cnt + 1) }, 0.1);
});
}
}
start();
I am new to Ajax and Jquery.I have a form where there is a DepositAccountNumberId text box and its value is stored in a Hidden Field for Validation.
OnBlur event of DepositAccountNumberId TextBox should give a bootbox alert ("This Account Number has been Suspended"). I have posted the code below:
Javascript Function to CheckAccountSuspension()
var exist = true;
function checkAccountSuspension() {
var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();
// alert(accountNumberId);
if (accountNumberId == "") {
//
} else {
try {
var url = '/WebMethods/AccountDetails.asmx/IsAccountSuspended';
var d = { accountNumberId: accountNumberId };
//var jqXhr = $.post(url, d);
//jqXhr.done(function(data) {
$.post(url, d, function (data) {
if (data) {
var ret = data.d;
if (ret) {
$('#DepositAccountNumberIdHiddenField').val(accountNumberId);
exist = true;
} else {
$('#DepositAccountNumberIdHiddenField').val('');
bootbox.alert("This Account Has been Suspended");
exist = false;
}
}
}).fail(function() {
$('#DepositAccountNumberIdHiddenField').val('');
});
} catch (e) {
bootbox.alert('Error: ' + e);
}
}
Web Method
[WebMethod(EnableSession = true)]
public bool IsAccountSuspended(string accountNumberId)
{
int officeId = OfficeId;
return BusinessLayer.Transactions.Transactions.IsAccountSuspended(officeId, accountNumberId.ToLong());
}
IsAccountSuspended in Business Layer
public static bool IsAccountSuspended(int officeId, long accountNumberId)
{
if (accountNumberId <= 0)
{
return false;
}
return DatabaseLayer.Transactions.Transactions.IsAccountSuspended(officeId,accountNumberId);
}
IsAccountSuspended in Database Layer
public static bool IsAccountSuspended(int officeId, long accountNumberId)
{
if (accountNumberId <= 0)
{
return false;
}
var sql = "SELECT * FROM deposit.is_suspended(#AccountNumberId::bigint);";
using (var command = new NpgsqlCommand(sql))
{
command.Parameters.AddWithValue("#AccountNumberId", accountNumberId);
using (var table = DBOperations.GetDataTable(command))
{
if (table.Rows.Count >= 1)
{
return true;
}
return false;
}
}
}
The Validation does not work.The ajax is not called to check if the account is suspended.Help Please.
Try to use $.post method:
var exist = true;
function checkAccountSuspension() {
var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();
// alert(accountNumberId);
if (accountNumberId == "") {
//
} else {
try {
var url = '/WebMethods/AccountDetails.asmx/IsAccountSuspended';
var d = {accountNumberId: accountNumberId};
var jqXhr = $.post(url, d);
jqXhr.done(function (data) {
if (data) {
var ret = data.d;
if (ret) {
$('#DepositAccountNumberIdHiddenField').val(accountNumberId);
exist = true;
} else {
$('#DepositAccountNumberIdHiddenField').val('');
bootbox.alert("This Account Has been Suspended");
exist = false;
}
}
}).fail(function () {
$('#DepositAccountNumberIdHiddenField').val('');
});
} catch (e) {
bootbox.alert('Error: ' + e);
}
}
}
$('#DepositAccountNumberTextBox').on('blur', function () {
checkAccountSuspension();
});
There is no such method like ajaxPost in JQuery. Use $.Post at its place.
try {
var url = '/WebMethods/AccountDetails.asmx/IsAccountSuspended';
var d = { accountNumberId: accountNumberId };
$.post(url,d,function(data){
if (data) {
var ret = data.d;
if (ret) {
$('#DepositAccountNumberIdHiddenField').val(accountNumberId);
exist = true;
}
else {
$('#DepositAccountNumberIdHiddenField').val('');
bootbox.alert("This Account Has been Suspended");
exist = false;
}
}
}).error(function() {
$('#DepositAccountNumberIdHiddenField').val('');
})
}
catch (e) {
bootbox.alert('Error: ' + e);
}
This is How it worked.
Like some of the experts above said about the use of postAjax and $.post.
As everywhere in the project it was used as postAjax by previous developers here.
I was actually passing a null value again in the hidden field.
This code worked.
var exist = true;
function checkAccountSuspension() {
var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();
if (accountNumberId == "") {
//
} else {
try {
var url = '/WebMethods/AccountDetails.asmx/IsAccountSuspended';
var d = { accountNumberId: accountNumberId };
//$.post(url, d, function (data) {
var jqXhr = ajaxPost(url, d, true);
jqXhr.done(function (data) {
var ret = data.d;
if (!ret) {
$('#DepositAccountNumberIdHiddenField').val(accountNumberId);
exist = true;
}
else {
//$('#DepositAccountNumberIdHiddenField').val('');
// bootbox.alert("<b class='text-red'>Suspended Account</b> <br/>This Account has been Suspended.");
swal({
title: "Suspended Account!",
text: "This Account is Suspended",
type: "error",
confirmButtonText: "OK",
imageSize: "20x20"
});
exist = false;
resetAllInputs();
}
}).fail(function (ex) {
bootbox.alert("Requested process fail to execute");
//$('#DepositAccountNumberIdHiddenField').val('');
});
}
catch (e) {
bootbox.alert('Error: ' + e);
}
}
}
function checkMessages(user, password, callback) {
var page = require('webpage').create();
page.open('http://mywebpage.com', function (status) {
if (status === 'fail') {
console.log(user + ': ?');
} else {
page.evaluate(function (user, password) {
document.querySelector('input[name=username]').value = user;
document.querySelector('input[name=password]').value = password;
document.querySelector('button[name=yt0]').click();
}, user, password);
waitFor(function() {
return page.evaluate(function() {
var el = document.getElementById('fancybox-wrap');
if (typeof(el) != 'undefined' && el != null) {
return true;
}
return false;
});
}, function() {
var messageCount = page.evaluate(function() {
var el = document.querySelector('span[class=unread-number]');
if (typeof(el) != 'undefined' && el != null) {
return el.innerText;
}
return 0;
});
console.log(messageCount);
});
}
page.close();
callback.apply();
});
}
For some reason, I just can't get this to work. PhantomJS is complaining: "Error: cannot access member 'evaluate' of deleted QObject". Is it because I am having multiple page.evaluates?
PhantomJS is asynchronous. In this case waitFor() is asynchronous, so you need to close the page after you've done with it. You need to move
page.close();
callback.apply();
into the last function that will be executed which is the callback of waitFor(). You might want to change waitFor a little bit, so that there is another callback when the timeout is reached which is the error branch which also requires the page closing and callback:
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000,
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
condition = testFx();
} else {
var error = null;
if(!condition) {
error = "'waitFor()' timeout";
console.log(error);
} else {
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
clearInterval(interval);
}
onReady(error);
}
}, 250);
};