409 http error in Couchbase lite in phonegap on iOS - ios

I'm getting a 409 on PUT, POST and DELETE actions.
I have successfully created a database and have PUT one document successfully ONCE. I have tried local and "normal" documents. I haven't spend any focus on revisions but think it has to do with this. I only want to save and update this one JSON string in my app - thats it.
It's like I have created this one document to stay forever :-)
Will sample code help? I'm really only using Angular's $http.
On a side note: I need a save mechanism in phonegap that is html5 cache-clear resistent.

You need to check if your document exists first before you update it. that's why it worked the first time and not the second.
config.db.get( "myDocumentID", function(error, doc) {
if (error) {
if (error.status == 404) {
//document does not exist insert it
config.db.put( "myDocumentID", myDocument, function(error,ok) {
if(error) { alert( "error" + JSON.stringify( error ) } else {
alert("success");
}
} )
} else {
alert( "error:" + JSON.stringify( error ) )
}
} else {
//update your document
doc.my_new_key = "value";
config.db.put( "myDocumentID", doc, function(error, ok) {
if( error ) { alert( "error:" + JSON.stringify( error ) ) } else {
alert("success");
}
} );
}
} )

Related

How to debug an issue with Zendesk App as console.log is not working

topBarClient.request(settings).then(
function (data) {
console.log("data",data);
showTaskData(data);
if (data.status === 200) {
onSuccess(JSON.parse(data.responseText));
} else {
onFailure(data.status);
}
},
function (response) {
console.log("error", response);
onFailure(response.status);
}
);
onFailure is working but not able to get the error out
Is there a way to test this locally?
console.log works fine, if it's not working then it is not getting called probably due to some exception in the line above console.log.
If you face any problem you can render html component like div to dislplay the text for debugging purpose.

XML API calling not working with cordova-plugin-advanced-http latest version in ionic3

I am using cordova-plugin-advanced-http plugin for API calling and all JSON enabled API working fine but I have one XML embedded API which is working fine in Postman but while I call it from ionic its param not getting at the server end.
Below is my code for XML API:
Type 1:
let headers = {
"Content-type": 'text/xml; charset=utf-8',
"Authorization": token,
};
let xmlBody =
'<ServiceRequest>' +
'<CaseNumber>' + caseNumber +
'</CaseNumber>' +
'</ServiceRequest>'
this.httpPlugin.setDataSerializer('utf8');
this.httpPlugin.post('https://test.com/Service', xmlBody, headers).then((response) => {
console.log("XML Response : ", JSON.stringify(response.data));
xml2js.parseString(response.data, function (err, result) {
console.log("XML parser success:", result);
console.log("XML parser error:", err);
if (result) {
resolve(result);
} else {
reject(err);
}
});
}).catch(error => {
if (error.status == 403) {
console.log("Token expired : " + JSON.stringify(error));
} else {
console.log("Error : " + error.error);
console.log("Error " + JSON.stringify(error));
reject(error);
}
});
Type 2:
let xmlBody = '<ServiceRequest>' +
'<CaseNumber>' + caseNumber +
'</CaseNumber>' +
'</ServiceRequest>';
console.log("XML Body", xmlBody)
// this.httpPlugin.setRequestTimeout(60);
this.httpPlugin.setDataSerializer('utf8');
this.httpPlugin.setHeader('*', 'authorization', token);
this.httpPlugin.setHeader('*', 'Content-Type', "application/x-www-form-urlencoded");
this.httpPlugin.post('https://test.com/Service', xmlBody, {}).then((response) => {
console.log("XML Response : ", JSON.stringify(response.data));
xml2js.parseString(response.data, function (err, result) {
console.log("XML parser success:", result);
console.log("XML parser error:", err);
if (result) {
resolve(result);
} else {
reject(err);
}
});
}).catch(error => {
if (error.status == 403) {
console.log("Token expired : " + JSON.stringify(error));
} else {
console.log("Error : " + error.error);
console.log("Error " + JSON.stringify(error));
reject(error);
}
});
All the time it's throwing errors from the server and with the same request, I am able to get data in postman as well as Native iOS code.
I referred this issue on GitHub but still no success.
Something I am missing though it's not able to get data on the server.
Help me to solve this issue.
After struggling a lot on this issue I found a solution to clean my request cookies.
In the HTTP Advanced plugin, there is one method to clear my cookies.
clearCookies()
Clear all cookies.
Use this method before calling any API.
So what it will do clear all my cookies and my issue related to old cookies will be solved in this way.
constructor(
public storage: Storage,
public httpPlugin: HTTP,
private platform: Platform
) {
// enable SSL pinning
httpPlugin.setSSLCertMode("pinned");
//Clear old cookies
httpPlugin.clearCookies();
}
The above code solves my issue.
Thanks all for your quick guidance and suggestions.
comment on this if this is not the right way to clear my old request data.

TFS Rest API: Extension Data Service unreliable?

My TFS hub extension (on-premise 2015.3) does not load correctly because of unexpected extension data service behaviour and not getting its needed preferences. The extension users store - after installation once during first-start/loading the hub page - extension preferences on the collection-level, as key-value pairs (getValue/setValue from extension data service API), and if the hub page gets reloaded the preferences are stored already. It's like an Application Wizard/First start Dialog in my hub page.
But when I install the extension on another collection of the same TFS and want to store (=setValue) preferences for that collection it comes back with OK (can see it in F12->network capture of Internet Explorer), but cannot find these previously entered/stored key-value pairs when refreshing (=getValue on the key) my hub. It delivers an empty value for the key, and the "first-start" dialog reappears again, what shouldnt happen if there was a value for the key. Already debugged, it always comes back empty (empty value) in that collection. No error from the service, nothing to capture, nothing to debug.
Can I check somewhere else (on the TFS logs, event viewer, or database) for deeper debugging?
I also tried with Powershell and restcalls manually by putting and getting the json on the Rest urls for the extension data service. In one collection it works (manually and per hub extension) but for the other collection the data service does not work.
Is there a known issue in 2015.3 in the extension data service? I really have a problem if I cannot store the preferences of the extension anywhere - storing it to an default source control path would be an alternative, but I do not want to force the projects to check-in preferences for my extension...
EDIT:
Adding relevant code snippet
function showSourceControlDialog(project: string/*TFS_Core_Contracts.TeamProjectReference*/) {
return Q.Promise(function (resolve, reject) {
//setTimeout(function () {
var thatProjectIDclean = project/*.id*/.replace(/-/g, "_");
var enterSourceControlPathDialog = VSS_Controls_Dialogs.show(VSS_Controls_Dialogs.ModalDialog, {
title: "Please now enter source control path for " + thisProjectName /*project.name*/,
content: $("<p/>").addClass("confirmation-text").html("<label><b>Source Control Path</b> to preferences file, e.g. '$/" + thisProjectName /*thisCollectionName + "/" + project.name*/ + "/.../...xml:</label><input id='enterSourceControlPathInput' size='40'/>" /*+ projectName + ".xml"*/),
useBowtieStyle: true,
buttons: {
"Cancel": function () {
enterSourceControlPathDialog.close();
enterSourceControlPathDialog.dispose();
reject("cancelled");
},
"OK": function () {
sourceControlPath = $("input#enterSourceControlPathInput").val();
if (sourceControlPath) {
setConfiguration(thatProjectIDclean, sourceControlPath).then(function (setToThisPath) {
console.log(setToThisPath);
enterSourceControlPathDialog.close();
enterSourceControlPathDialog.dispose();
$(".bss-button").show();
$(".bss-tvc").show();
resolve(sourceControlPath);
}).catch(function (error) {
reject(error);
})
}
}
}
});
//}, 10000);
});
}
function setConfiguration(key: string, value: string) {
return Q.Promise(function (resolve, reject) {
// Get data service
VSS.getService(VSS.ServiceIds.ExtensionData).then(function (dataService: IExtensionDataService) {
// Set value in collection scope
dataService.setValue(pssVersion + "_" + key, value/*, { scopeType: "Project Collection" }*/).then(function (setToThis: string) {
console.log(pssVersion + "_" + key + " is now " + setToThis );
resolve(setToThis);
}, function (error) {
reject(error);
console.log(error);
}, function (error) {
reject(error);
console.log(error);
});
});
}
function getConfiguration(key: string) {
return Q.Promise(function (resolve, reject) {
// Get data service
VSS.getService(VSS.ServiceIds.ExtensionData).then(function (dataService: IExtensionDataService) {
// Get value in collection scope
dataService.getValue(pssVersion + "_" + key/*, { scopeType: "Project Collection" }*/).then(function (gotThis: string) {
sourceControlPath = gotThis;
console.log(pssVersion + "_" + key + " is " + gotThis );
resolve(gotThis);
}, function (error) {
reject(error);
console.log(error);
});
}, function (error) {
reject(error);
console.log(error);
});
});
}
try {
console.log(thisProjectIDclean);
getConfiguration(thisProjectIDclean).then(function (resultPath: string) {
console.log(resultPath);
console.log(sourceControlPath);
if (!resultPath) {
//getProjects().then(function (resultProjects: TFS_Core_Contracts.TeamProjectReference[]) {
// resultProjects.forEach(function (resultProject: TFS_Core_Contracts.TeamProjectReference) {
showSourceControlDialog(thisProjectID/*resultProject*/).then(function () {
getXMLTree();
}, function (error) {
console.log(error);
});
// }, function (error) {
// console.log(error);
// });
//}, function (error) {
// console.log(error);
//});
} else {
getXMLTree();
}
});
} catch (error) {
console.log(error);
}
Unfortunately what you are trying to do is not possible. Referring to the example the "maximum" scope you can store extension data in is the "Project Collection".
From my experience while fiddling with ExtensionDataService it is not possible to query data from a "foreign" collection.

react-native error RCTJSONStringify() encountered the following error: Invalid type in JSON write (NSURL)

I am trying to use react-native-fbsdk in my react-native app. It was working fine untill yesterday. But, today it gives a weird error stating RCTJSONStringify() encountered the following error: Invalid type in JSON write (NSURL).
RN v0.42.0
Here is my code:
_fbAuth(error, result) {
if (error) {
console.log("error");
alert("login has error: " + result.error);
} else if (result.isCancelled) {
console.log("login cancelled");
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then((data) => {
console.log("login success");
console.log(data.accessToken.toString());
let accessToken = data.accessToken;
alert(data.accessToken.toString());
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
});
}
}
render() {
console.log("in new render");
return (
<View style={styles.container}>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={this._fbAuth}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
The error information printed in debugger:
I get the above error while calling the graphAPI in the function responseInfoCallback. Any ideas what is happening ?
Update 1:
This error happens only when remote debugger is turned on!! Else it is not happening. But without remote debugger, I cannot proceed with developing the app. Are there any other methods to see log statements of react-native app other than remote debugger ?
Update 2:
The RCTJSONStringify() error happens only behind proxy. And also https fetch calls does not work under proxy. I tested in an open network, it works fine. I guess, it is to add some proxy information to RN app. I think it is related to APP transport security
If you turn the debugger off, you can see the proper error in the XCode console. Access it from Xcode menu View/Debug Area/Activate console, if it's not enabled automatically.

Parse server return invalid session token for public records and only when calling functions

ok this is something that start to show a few weeks ago, I have a parse server running on an ubuntu machine with version 2.3.3, I have a bunch of cloud functions running, nothing fancy just querying some specific Class, all the data in that class is public and all work most of the time just fine. However from time to time, calling a cloud function start to return invalid sessions error 209, even with a user logged or not, super weird, but what is even strange is that when that happens no one else can run the function, and every user start to got the same error.
The only way I can make it work again is restarting the server, also only happens with cloud functions and from the ios app, I saying this cause we have some other part calling functions from php but it seems those are not starting the problem
2017-02-21T01:26:57.676Z - Failed running cloud function partnersv2 for user undefined with:
Input: {"k":"","searchType":"","category":"comida"}
Error: {"code":141,"message":{"code":209,"message":"invalid session token"}}
2017-02-21T01:26:57.669Z - invalid session token
2017-02-21T01:26:55.738Z - ParseError { code: 209, message: 'invalid session token' }
2017-02-21T01:26:55.737Z - Error generating response. ParseError {
code: 141,
message: ParseError { code: 209, message: 'invalid session token' } }
I have no idea why is this happening, also I don't think is related to the legacy session cause this server and the user are new, we start developing this a few months ago is not a ported app from the old service
One thing we are doing a lot is removing from the dashboard sessions at will, cause we are testing and developing, not sure if this could be a reason, but what about when the user is undefined, it shouldn't even try to use session I think, or maybe a user that was actually logged could be the culprit, setting the server to VERBOSE is not telling anything else as well, just the params and the call which it doesn't look weird to me, am looking for someone that maybe can put me in the right direction of maybe how the session work or something, thank you for any help
EDIT 1:
This is the cloud function that is trowing the error
Parse.Cloud.define('partnersv2', function (req, res) {
var searchType = req.params.searchType,
k = req.params.k,
category = req.params.category,
query;
query = new Parse.Query('Partner');
query.addDescending('is_open');
query.equalTo('enabled', true);
query.equalTo('category', category);
query.select(['name', 'phone', 'delivery_eta', 'keys', 'price_range', 'is_new', 'cover', 'recommended', 'open_time', 'min_order', 'delivery_rank', 'logo', 'comingsoon', 'category', 'is_open']);
if (searchType !== '' && searchType !== undefined && k !== '' && k !== undefined) {
if (searchType === 'Tag') {
query.equalTo('tags', k);
} else {
query.equalTo('name', k);
}
}
query.limit(1000);
query.find({
success: function (results) {
if (results.length > 0) {
res.success(results);
} else {
res.error('404 not found');
}
},
error: function (error) {
res.error(error);
}
});
});
and this is a screenshot of the ACL col
Use Master Key
Parse.Cloud.define('partnersv2', function (req, res) {
//var token = req.user.getSessionToken() // getSession Token return r: (yourkey);
var searchType = req.params.searchType,
k = req.params.k,
category = req.params.category,
query;
query = new Parse.Query('Partner');
query.addDescending('is_open');
query.equalTo('enabled', true);
query.equalTo('category', category);
query.select(['name', 'phone', 'delivery_eta', 'keys', 'price_range', 'is_new', 'cover', 'recommended', 'open_time', 'min_order', 'delivery_rank', 'logo', 'comingsoon', 'category', 'is_open']);
if (searchType !== '' && searchType !== undefined && k !== '' && k !== undefined) {
if (searchType === 'Tag') {
query.equalTo('tags', k);
} else {
query.equalTo('name', k);
}
}
query.limit(1000);
query.find({
useMasterKey: true, // sessionToken: token
success: function (results) {
if (results.length > 0) {
res.success(results);
} else {
res.error('404 not found');
}
},
error: function (error) {
res.error(error);
}
});
});

Resources