ServiceNotAvailableError: Failed to register SAAgent - samsung-mobile

I'm developing an integrated Gear 2 App and I have some issues with the connection between the phone and Gear 2. The problem is when I call the function:
webapis.sa.requestSAAgent(onsuccess, onerror);
In the console I have this log: ONERROR: err [ServiceNotAvailableError] msg [Failed to register SAAgent.]
The problem is that the functions instantly go to the onerror function, jumping the onsucces function. I post my code for clarification:
function onerror (err) {
console.log("ONERROR: err [" + err.name + "] msg [" + err.message + "]");
}
var agentCallBack = {
onconnect: function (socket) {
console.log ("agentCallBack onconnect" + socket);
SASocket = socket;
alert("SAP Connection Establishe with RemotePeer");
createHTML("startConnection");
SASocket.setSocketStatusListener(function(reason) {
console.log ("Service connection lost, Reason: [" + reason + "]");
disconnect();
})
},
onerror : onerror
};
var peerAgentFindCallback = {
onpeeragentfound : function(peerAgent) {
try {
if (peerAgent.appName == ProviderAppName) {
SAAgent.setServiceConnectionListener(agentCallback);
SAAgent.requestServiceConnection(peerAgent);
} else {
alert("Not expected app!! : " + peerAgent.appName);
}
} catch(err) {
console.log("exception [" + err.name + "] msg[" + err.message + "]");
}
},
onerror : onerror
}
function onsuccess(agents) {
try {
if (agents.length > 0) {
SAAgent = agents[0];
SAAgent.setPeerAgentFindListener(peerAgentFindCallback);
SAAgent.findPeerAgents();
} else {
alert("Not found SAAgent!!");
}
} catch(err) {
console.log("exception [" + err.name + "] msg[" + err.message + "]");
}
}
Anyone can explain how can I fix this? I've already put this privilege into the config.xml file:
<tizen:privilege name="http://developer.samsung.com/privilege/accessoryprotocol"/>

It sound like you are missing serviceprofile.xml file. You need that in both phone and gear applications.
Here is samsung developer guide: http://pl.scribd.com/doc/231769842/Samsung-Gear-Application-Getting-Started-1-0
Look into section 5.2.

Related

LDAP authentication using ldapjs in nodejs

Am a newbie to node.js, have somewhat figured out the LDAP authentication. Here am trying to retrieve employee ID from the search but none of the search entries are fetched though the passed credentials are bounded successfully , not sure where i'm mislead. If someone could help me out in it would be of a great help!
Below are the result sets of the code snippet:
Reader bind succeeded
Search results length: 0
Search
retval:{"messageID":2,"protocolOp":"LDAPResult","status":0,"matchedDN":"","errorMessage":"","referrals":[],"controls":[]}
No unique user to bind
ldapRoute.route('/ldap').post((req, res, next) => {
var result = "";
var email =req.body.email;
var client = ldap.createClient({
url: 'ldap://******'
});
var opts = {
filter: '(sAMAccountName='+ email + ')',
attributes: ['sAMAccountName']
};
var username = 'ii' + "\\" + email;
client.bind(username, req.body.password, function(err) {
if (err){
result += "Reader bind failed " + err;
res.send(result);
return;
}
else{
result += "Reader bind succeeded\n";
}
client.search('OU=emp,dc=i,dc=ac,dc=com', opts, function(err, searchRes) {
var searchList = []
if (err) {
result += "Search failed " + err;
res.send(result);
return;
}
searchRes.on("searchEntry", (entry) => {
result += "Found entry: " + entry + "\n";
searchList.push(entry);
});
searchRes.on("error", (err) => {
result += "Search failed with " + err;
res.send(result);
});
searchRes.on("end", (retVal) => {
result += "Search results length: " + searchList.length + "\n";
for(var i=0; i<searchList.length; i++)
result += "DN:" + searchList[i].employeeID + "\n";
result += "Search retval:" + retVal + "\n";
if (searchList.length == 1) {
client.bind(searchList[0].employeeID, req.body.password, function(err) {
if (err)
result += "Bind with real credential error: " + err;
else
result += "Bind with real credential is a success";
res.send(result);
}); // client.bind (real credential)
} else {
result += "No unique user to bind";
res.send(result);
}
});
});
});
});
The issue was in the filters and for some strange reasons the 'end' got fired before hitting the 'searchEntry', debugging it helped me to resolve the issue.
//Filter
var opts = {
filter: '(sAMAccountName=' + email+')',
scope: 'sub',
attributes: ['employeeID']
};
//Search
client.search('OU=empl,dc=ii,dc=ac,dc=in', opts, function(err, searchRes)
{
if (err)
{
result += "Search failed " + err;
res.send(result);
return;
}else{
searchRes.on("searchEntry", (entry) =>
{
result += "Found entry: " + entry.object.employeeID;
res.send(result);
}
/ ........../
} });

Socket io connected at same time with same socket.id

I developing chat app using socket io. The problem is when two socket connected at same time will produce same socket.id. So when socket disconnect, it will remove both socket. so the other one cannot listening anymore. How i can prevent socket connected with same id? Thank You.
app.post("/online", bodyP, async (req, res) => {
var userID = req.body.username;
var connectStatus;
try {
if (onlineUsersArray.indexOf(userID) === -1) {
connectStatus = true;
var io_online = io.of("/online");
io_online.on("connection", async function (socket) {
var date = new Date().toLocaleString("en-US", { timeZone: "Asia/Singapore" });
onlineUsersArray.push(userID.toString());
users[socket.id] = userID;
console.log('sessionID ' + socket.id);
console.log(users[socket.id] + " connected at " + date);
console.log("User in array : " + onlineUsersArray);
console.log("Number of users connected : " + onlineUsersArray.length);
socket.on("disconnect", function () {
var date = new Date().toLocaleString("en-US", { timeZone: "Asia/Singapore" });
if (onlineUsersArray.indexOf(users[socket.id]) === -1) {
console.log(">>>>>>>>>>>>>>>> " + users[socket.id] + "Not existed in online array");
} else {
var indexOfConnection = onlineUsersArray.indexOf(users[socket.id]);
onlineUsersArray.splice(indexOfConnection, 1);
console.log("user " + users[socket.id] + " disconnected at " + date);
console.log("Number of users connected : " + onlineUsersArray.length);
console.log("Users Currently Online: " + onlineUsersArray);
}
socket.removeAllListeners();
io_online.removeAllListeners();
});
});
} else {
console.log("user " + userID + " already in session");
connectStatus = false;
}
res.status(200).send({
status: true,
connection: connectStatus
});
}
catch (e) {
res.status(200).send({
status: false,
result: "Failed to set online user"
});
logg.loggerServer("app.js - Online user error ", "0", "Failed in online " + e);
}
});
if 2 or more device run at same time it will produce same socket id

Waiting query result

I can't succeed into waiting an sql query result
This is what my Code looks like
socket.on('new', async function(information) {
console.log("check no offer en cours");
var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
doInsert = false;
con.query(checkOffer, function(err, result) {
if (err) throw err;
console.log(result[0].total);
if (result[0].total == 0) {
console.log("can insert");
doInsert = true;
}
}).then(function() {
console.log(doInsert);
if (doInsert) {
console.log("create offer");
var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
"VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
console.log(sql);
con.query(sql, function(err, result) {
if (err) throw err;
socket.emit('new', result);
});
} else {
console.log("Cet user a déjà une offre en cours");
}
});
Issue is the doInsert Log is executed before the canInsert Log.
I think that con.query() accept the callback and is also "thennable" returning a Promise.
In most cases if the callback is provided, that will be the handler of the result and it wont be passed to the Promise.
So
con.query(query, () => {
// this code is executed when the query ends
}).then(() => {
// this code is executed when the promise attached to .then() is resolved
// in this case con.query() is instant resolved cause a callback parameter is given
})
The solution is to put all in the callback OR all in the promise chain.
I would do like :-
try{
let result = await con.query(checkOffer);
if (result) {
let resultFromAnotherQuery = await con.query(sql);
if (resultFromAnotherQuery){
console.log("done");
}
}
}catch(err) {
console.log(err);
}

Twitter streaming issue using Nodejs "Twit"

I Just try to streaming tweets form twitter using nodejs with "Twit" (npm) my code is look as follows.
stream = tweeter.stream('statuses/filter', { track: phrase, language: 'en' });
var testTweetCount = 0;
stream.on('tweet', function (data) {
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log("stream started Successfully with "+filterText+"- "+datetime);
//socket.emit('gotTweetss');
var tweetText = JSON.stringify(data.text);
if(tweetText){
var Created_at=JSON.stringify(data.created_at);
var User=JSON.stringify(data.user.screen_name);
tweetCollection.count({text:tweetText,user:User,Created_at:Created_at}, function(err, existdata){
/* console.log("existdata : " + existdata);*/
if(existdata > 0){
console.log("duplicate data : " + JSON.stringify(existdata));
} else{
var tText=filterText.split(',');
var chekTrue=false;
for(iix=0;iix<tText.length;iix++)
{
var twData=tweetText.toUpperCase();
var txzt=tText[iix].trim();
if(twData.indexOf(txzt.toUpperCase())>-1)
{
console.log('true');
chekTrue='true';break;
}
}
if(chekTrue=='true'){
tweetCollection.insert([{text:tweetText,user:User,Created_at:Created_at}], {w:1}, function (error) {
if (error){
console.log("Error Occurred " + error.message);
} else{
// Wait for a second before finishing up, to ensure we have written the item to disk
setTimeout(function() {
// Fetch the document
tweetCollection.findOne ({text:tweetText}, function (err, item) {
assert.equal(null, err);
if(item!=null)
assert.equal(tweetText, item.text);
})
}, 1000);
}
});
}
}
});
}
// socket.emit('gotTweet');
});
stream.on('error', function(error, code) {
console.log("My error: " + error + ": " + code);
/*if(code=="420")
{
io.sockets.emit('gotTweet');
}*/
});
stream.on('delete', function(error, code) {
console.log("My delete: : " + code);
});
This is the code of start streaming area for getting stream for this am using
'twit' NPM .Its show in console date and time for sync while streaming start,Its work fine. But some time tweets not getting properly,When i tweet in twitter this streaming not getting that tweets. Is there is any solution ?
this becuase of language: 'en' in twitter stream
tweeter.stream('statuses/filter', { track: phrase, language: 'en' });
i just remove the language: 'en' in above code its work perfectly
tweeter.stream('statuses/filter', { track: phrase });

azure mobile api variable scope

I have the following Azure Mobile Services API get function. I want to set the isValidUser flag based on if there is a record for the providerKey (from the twitter authentication) in the SQLMembership table (AspNetUserLogins).
While testing, I see the following in the log file, confirming that the flag is being set.
"setting isValidUser [object Object] Number of records = 1"
However, if(isValidUser) is not getting evaluated correctly. The result I get from the API is "Not a registered user." which is set from the else portion of the if(isValidUser) check.
Why is it that the value set inside the mssql.query() is not available outside of it?
exports.get = function(request, response) {
var authenticatedUserId = request.user.userId;
var providerName = authenticatedUserId.split(":")[0];
var providerUserId = authenticatedUserId.split(":")[1];
var isValidUser = false;
console.log('providerName = ' + providerName.trim());
console.log('providerUserId = ' + providerUserId.trim());
request.service.mssql.query(
"select userId from dbo.AspNetUserLogins where LoginProvider = '" + providerName + "' and ProviderKey = '" + providerUserId + "'",
{
success: function(results)
{
console.log('inside success AspNetUserLogins. ' + results + " Number of records = " + results.length);
if (results.length == 1) {
console.log('setting isValidUser ' + results + " Number of records = " + results.length);
isValidUser = true;
}
},
error : function(err)
{
console.log('inside error AspNetUserLogins. ' + err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: err });
}
}
);
if (isValidUser) {
request.service.mssql.query('select * from dbo.Church',
{
success: function(results)
{
console.log('inside success Church' + results);
response.json(statusCodes.OK, results);
},
error : function(err)
{
console.log('inside error : ' + err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: err });
}
}
);
} else {
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: "Not a registered user." + isValidUser });
}
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: "Unexpected end." });
};
The call to mssql.query is an asynchronous function (like many other functions in node.js); when it returns the callback (either the success or the error) hasn't been executed yet, so when you check the isValidUser flag, it still has the original value (false).
What you need to do is to move that code to inside the success callback, and that should work:
exports.get = function(request, response) {
var authenticatedUserId = request.user.userId;
var providerName = authenticatedUserId.split(":")[0];
var providerUserId = authenticatedUserId.split(":")[1];
var isValidUser = false;
console.log('providerName = ' + providerName.trim());
console.log('providerUserId = ' + providerUserId.trim());
var sql = "select userId from dbo.AspNetUserLogins where LoginProvider = ? and ProviderKey = ?";
var sqlParams = [providerName, providerUserId];
request.service.mssql.query(sql, sqlParams, {
success: function(results)
{
console.log('inside success AspNetUserLogins. ' + results + " Number of records = " + results.length);
if (results.length == 1) {
console.log('setting isValidUser ' + results + " Number of records = " + results.length);
isValidUser = true;
}
if (isValidUser) {
request.service.mssql.query('select * from dbo.Church', {
success: function(results)
{
console.log('inside success Church' + results);
response.send(statusCodes.OK, results);
},
error : function(err)
{
console.log('inside error : ' + err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: err });
}
});
} else {
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: "Not a registered user." + isValidUser });
}
},
error : function(err)
{
console.log('inside error AspNetUserLogins. ' + err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, { error: err });
}
});
};
One more thing: do use parameters in the SQL (also shown above), instead of composing the query directly. In this case (you're using the user id) it shouldn't be a problem, but as a general rule you should use parameters whenever possible to prevent SQL injection attacks.

Resources