Preventing "onSuccess" firing when there is no connection to an adapter? - hybrid-mobile-app

Using MobileFirst v6.3, whenever I communicate with an adapter using WL.Client.invokeProcedure, the onSuccess function ALWAYS fires, regardless of actual success or not. This includes when the mobile device is completely offline.
onConnectionFailure still functions as expected, firing after the adapter times out, but having onSuccess fire is essentially useless.
Sample code:
var invocationData = {
adapter : 'MaximoLogin',
procedure : 'setValue',
parameters : [itemid,value]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : valueSuccess(itemid),
onConnectionFailure: connectivityFailure,
onFailure : connectFailure
});
How do I prevent this from happening?

You should update your code as follows:
var invocationData = {
adapter : 'MaximoLogin',
procedure : 'setValue',
parameters : [itemid,value]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : valueSuccess,
onConnectionFailure: connectivityFailure,
onFailure : connectFailure,
invocationContext : {
itemid: itemid
}
});
// your success function
function valueSuccess(response) {
// get the item id from the invocationContext object
var successItemId = response.invocationContext.itemid;
// handle your success ...
}
The reason why your valueSuccess function is always called is because you are always calling it i.e.: valueSuccess(itemid). onSuccess takes a callback function and you are invoking the function that's why it always runs.
If you want to pass some variable to your callback functions you use invocationContext which is an object that will be passed to your callback functions both onSuccess and onFailure.

Related

AWS SNS Multiple notifications received

I have an API Gateway method calling a Lambda Node.js function. The Lambda function calls SNS and posts an APNS notification to my iPhone. When I invoke the API gateway or the Lambda function in the AWS console, I get one notification as expected. I also get one notification when running the Lambda code on the command line (Grunt and Node.js). I also get one notification when running the javascript from eclipse.
However, when I POST to the API gateway, I get 2-5 notifications. Every thing looks the same. I checked the Cloudwatch logs and it seems only one request is sent each time. Anybody have any idea how to debug this?
I've had similar. For me, it was that I wasn't calling the success callback properly.
I figured it out. I had my function outside the exports.handler function:
var AWS = require('aws-sdk');
var sns = new AWS.SNS();
var myAlerter = function(){
var numSent = 0;
var callback;
var arn = "arn:aws:sns:us-west-2:45435475457:endpoint/APNS/MyAlerter/5a11c61f-1122-3344-5566-656845463";
var sendNotification = function(messageText){
var apns = {
aps : {
alert : messageText,
sound : 'default'
}
};
var message = {
"APNS" : JSON.stringify(apns)
};
message = JSON.stringify(message);
var params = {
Message: message,
MessageStructure: 'json',
TargetArn: arn
};
numSent++;
sns.publish(params, function(err, data){
if (err){
callback(err, err.stack);
}else {
var result = {
error: false,
numSent : numSent,
data: data
};
callback(false,result);
}
});
};
return {
alert : function(message, cb){
callback = cb;
sendNotification(message);
}
}
}();
exports.handler = function(event, context){
var alertedCallback = function(error, data){
if (error){
context.done(error);
} else {
context.succeed(data);
}
};
myAlerter.alert(event.message, alertedCallback);
};
Everytime I called the API Gateway and invoked my Lambda function, the numSent variable would increment. I guess putting my function inside the exports.handler ensured that my function wasn't global or something.

console.log not showing in Parse Logs page

In the below cloud code i would like to get a feedback of the saveAll function but after calling the code from my client in the parse Logs page i can only see:
I2014-10-08T15:28:32.930Z] v249: Ran cloud function acceptMeetingBis for user dyGu143Xho with:
Input: {"meetingId":"bUSTGNhOer"}
Result: Meeting accepted
Here is my cloud code:
Parse.Cloud.define("acceptMeetingBis", function(request, response) {
var userAcceptingTheMeeting = request.user;
var meetingId = request.params.meetingId;
var changedObjects = [];
var queryForMeeting = new Parse.Query("MeetingObject");
queryForMeeting.equalTo("objectId", meetingId);
queryForMeeting.first({
success: function(meeting) {
var userCreatorOfMeeting = meeting.get("user");
userAcceptingTheMeeting.increment("acceptedMeetings", +1);
changedObjects.push(userAcceptingTheMeeting);
meeting.add("participantsObjectId", userAcceptingTheMeeting.id);
if (meeting.get("participantsObjectId").length === meeting.get("meetingNumberOfPersons")) {
meeting.set("isAvailable", false);
}
changedObjects.push(meeting);
Parse.Object.saveAll(changedObjects, {
success: function(objects) {
console.log("Successfully saved objects"); //this line doesn't show up
response.success("objects saved");
},
error: function(error) {
// An error occurred while saving one of the objects.
response.error(error);
}
});
//future query and push notifications will go here
response.success("Meeting accepted");
},
error: function() {
response.error("Failed to accept the meeting");
}
});
});
I will also need to add some push and another nested query after the saveAll() but before doing/trying that i would like to know if this is the right method to use or if i have to build the code in a different way. I'm new to javascript and honestly i'm struggling to understand some concepts, like promises. Any help would be much appreciated.
Your call to
Parse.Object.saveAll
is asynchronous, and you call
response.success("Meeting accepted")
immediately after making the asynchronous call, which ends the cloud code running of the method. If you simply replace the
response.success("objects saved")
with
response.success("Meeting accepted")
you should get what you want.
I didn't see the rest of your question about promises. You should check out Parse's documentation on chaining promises, which is what you want here.
Essentially, here's what you'll want to do:
Parse.Cloud.define("acceptMeetingBis", function(request, response) {
var userAcceptingTheMeeting = request.user;
var meetingId = request.params.meetingId;
var changedObjects = [];
var meetingToAccept;
var queryForMeeting = new Parse.Query("MeetingObject");
queryForMeeting.get(meetingId).then(function(meeting) {
meetingToAccept = meeting;
var userCreatorOfMeeting = meeting.get("user");
userAcceptingTheMeeting.increment("acceptedMeetings", +1);
return userAcceptingTheMeeting.save();
}).then(function(userWhoAcceptedMeetingNowSaved) {
meetingToAccept.add("participantsObjectId", userWhoAcceptedMeetingNowSaved.id);
if (meetingToAccept.get("participantsObjectId").length === meetingToAccept.get("meetingNumberOfPersons")) {
meetingToAccept.set("isAvailable", false);
}
return meetingToAccept.save();
}).then(function(savedMeeting) {
response.success("Meeting accepted");
}, function(error) {
response.error("Failed to accept the meeting");
});
});
For each asynchronous action you want to do, perform it at the end of one of the .then functions and return the result (it returns a promise). Keep adding .then functions until you're done all the work you want to do, at which point call response.success.

AngularJS serverside variable to ng-init and methods sequence

I´v got a "detail" view and a controller that initilizes data with an id.
My view:
<div ng-app="AFApp" ng-controller="AgentCtrl" ng-init="init('#Model.Id')">
My controller:
$scope.id;
$scope.agent = {};
$scope.init = function (id) {
$scope.id = id;
getAgent();
getAgentStatus();
getSystemInfo();
getActions();
};
The problem is that the method "getAgentStatus();" gets executed before "getAgent();". The "getAgentStatus" needs the $scope.agent data that "getAgent" provides. The function getAgentStatus has an attached timer, and it gets the value as the timer elepses but not in the init function. Can someone please help me out with the method execution sequence in angular controllers and how the id parameter is provided the best possible way.
See methods below:
function getAgent() {
agentDataFactory.getAgent($scope.id)
.success(function (data) {
$scope.agent = data;
})
.error(function (error) {
console.log('Unable to load data: ' + error.message);
});
};
function getAgentStatus() {
if (typeof ($scope.agent.ServiceUrl) == 'undefined' || $scope.agent.ServiceUrl == null) {
console.log('getAgentStatus: ServiceUrl is undefined ' + JSON.stringify($scope.agent));
}
agentDataFactory.getAgentStatus($scope.agent.ServiceUrl)
.success(function (data) {
$scope.agent.CurrentStatus = data.Status;
$scope.agent.CurrentInterval = data.Interval;
})
.error(function (error) {
console.log('Unable to load data: ' + error);
});
$timeout(getAgentStatus, 3000);
};
You can pass getAgentStatus() as a callback parameter to getAgent() and have it executed in the success callback (at which point agent will be defined):
function getAgent(callback) {
agentDataFactory.getAgent($scope.id)
.success(function (data) {
$scope.agent = data;
callback && callback();
})
.error(function (error) {
console.log('Unable to load data: ' + error.message);
});
};
$scope.init = function (id) {
$scope.id = id;
getAgent(getAgentStatus);
getSystemInfo();
getActions();
};
Short explanation:
Some highlights first:
agentDataFactory.getAgent($scope.id).success(...).error(...);:
Creates a promise (which will be resolved) asynchronously and registers two callbacks, one if the promise is successfully resolved and one for the case of an error.
.success(function (data) { $scope.agent = data; }):
Registers a callbackfor when the promise is successfully resolved. When (and if) that happens, $scope.agent will be set.
function getAgentStatus() { if (typeof ($scope.agent.ServiceUrl...:
Tries to access some properties of $scope.agent and thus requires the object to be defined.
So, what happens with your code:
getAgent() is gets called.
[$scope.agent is undefined]
A promise is created that when resolved will set $scope.agent.
[$scope.agent is undefined]
getAgent() returns and getAgentStatus() is called.
[$scope.agent is undefined]
getAgentStatus() tries to access $scope.agent's properties and fails.
[$scope.agent is undefined]
The promise created in step 2 is resolved and its success callback get executed.
[$scope.agent is finally defined]
My version of the code ensures that getAgentStatus() is not executed before the promise is resolved and thus $scope.agent is defined:
getAgent() is gets called.
[$scope.agent is undefined]
A promise is created that when resolved will set $scope.agent.
[$scope.agent is undefined]
getAgent() returns and other functions get called (e.g. getSystemInfo(), getActions(), etc.).
[$scope.agent is undefined]
The promise created in step 2 is resolved and its success callback get executed.
[$scope.agent is finally defined]
Only now does getAgentStatus() get called and it works as expected since...
[$scope.agent is defined]
Take a look at the $q service for more info on Angular promises.

SignalR- send data to a specific client

I want to send data to a specific client. to do that I am trying with the following;
public Task GetWaitingOrdersCount(string id, string clientId)
{
DateTime today = Util.getCurrentDateTime();
var data = 10
return Clients.Client(Context.ConnectionId).loadOrders(data);
//return data;
}
In the above code, I want to send 'data' to the 'clientId' passed to this method.
BUT I m having an error in this line
return Clients.Client(Context.ConnectionId).loadOrders(data);
And the error is
'System.Threading.Tasks.Task<object>' does not contain a definition for 'loadOrders'
the client side code
con.loadOrders = function (data) {
loadOrders(data);
};
function loadOrders(data) {
$('#totalOrders').html(data);
}
Any help about the error???
EDIT:
This is my full client code..
<script type="text/javascript">
var con;
$(document).ready(function () {
con = $.connection.messagingHub;
$.connection.hub.start(function () {
var myClientId = $.connection.hub.id;
con.getWaitingOrdersCount('<%:ViewBag.rid%>',myClientId).done(function (data) {
console.log(data);
});
});
con.client.loadOrders = function (data) {
loadOrders(data);
};
});
function loadOrders(data) {
$('#totalOrders').html(data);
I just tried out your code (slightly modified) and it works fine for me. What version of SignalR are you using? Judging by your server code I'd say 1.0Alpha1+ but your client code looks more like 0.5.3, that is unless your con object is assigned to $.connection.yourhub.client;
If you update to SignalR 1.0Alpha2 and change your client code to be:
var con = $.connection.myCon;// This is arbitrary and would change based on your naming
con.client.loadOrders = function (data) {
loadOrders(data);
};
function loadOrders(data) {
$('#totalOrders').html(data);
}
That being said I believe your issue has to do with the version of SignalR you are using, server side that is: since you're receiving a task oriented error. Another piece of information that might be beneficial would be to know how GetWaitingOrdersCount is being called. Aka is it being invoked from the client directly via: con.server.getWaitingOrdersCount or is it being called from within the hub.
Hope this info helps!

How to wait for all ajax queries to finish (and use combined result)

var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
}
});
});
alert(display_message);
alert(display_message);
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
in this code, i use two alert-box for display display_message variable value.
when i run successfully this code, in 1st alert-box i get blank value and second alert-box i get value which i needed, then it will go in if condition.
if i doesn't use alert box then it will always take null value in display_message variable and never enters into the if condition. so what i need to change to run this code without alert box?
You are making an asynchronous call via AJAX, but your code is executing synchronously. So it is returning before the AJAX call completes. The first alert box just gives the function time to catch up. You need to handle all this code in your success callback.
var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
});
});
You want all your ajax queries to finish and return results, right?
Then this is a synchronization problem.
I would suggest this approach (code is simplified for clarity).
var inputs_processed = -1;
var inputs_to_process = -1;
function queryData() {
inputs_to_process = $('input:checked').length;
$('input:checked').each(function() {
$.ajax({success: function(data) {
inputs_processed += 1;
// build up that message
}});
});
}
function displayResult() {
if (inputs_processed == inputs_to_process) {
// display result
} else {
// not all queries finished yet. Wait.
setTimeout(displayResult, 500);
}
}
queryData();
displayResult();
Basically, you know how many requests should be made and you don't display result until that number of requests returns.
Why your data is "data"? I cant see any variable called data is declared here. You should pass in the value you want to use as the parameter into the data options.
Edit: This is why u getting the null value. data is not initialize into anything. Only after the success function, your "data" will have the value since you declare the return value with the same name

Resources