Parse.com Save Object Error - edit

Running into issues when trying to edit an object in Javascript.
Getting a "Error 201: must have user password."
Tried to get the users password and couldn't succeed. Trying to edit the users username in my application
function editProfile() {
Parse.initialize("", "");
var ProfileEdit = Parse.Object.extend("User");
var profile = new ProfileEdit();
var currentUser = Parse.User.current();
profile.save(null, {
success: function(profile) {
profile.set(currentUser, $("editprofile-username"));
profile.save();
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
}

I guess you want to do something like the code I wrote, however I don't understand why are you are using save() two times, maybe I am not really getting the question. . .
function editProfile() {
Parse.initialize("", "");
var currentUser = Parse.User.current();
currentUser.set("username",$("editprofile-username"))
currentUser.save(null, {
success: function(user) {
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
}

Related

Getting Bad method 405 response while trying to upload a file to Google Cloud Storage using SAP ui5

I am trying to upload a file to Google Cloud Storage using a basic uploader in UI5.
When I am uploading the file, I am getting a 405 error in my response.
My controller code goes like this.
Please let me know if I am making any mistake anywhere.
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
return Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function() {
var oFileUploader = this.byId("fileUploader");
var prop = oFileUploader.getValue();
var path = oFileUploader.getUploadUrl();
MessageToast.show(prop);
MessageToast.show(path);
// var form = new FormData();
//form.append("files", fileInput.files[0],"C:\Users\i347520\Desktop\pan.jpg");
/*eslint-disable*/
var settings = {
"url": "https://storage.googleapis.com/upload/storage/v1/b/testocr-1234/o?uploadType=media&name=prop"
/*eslint-enable*/
};
oFileUploader.upload(settings);
}
});
});
View:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
</mvc:View>

Node JS code not running in order

I have no idea why the code do not run as I expected.
When the UserExist is called, it should either console.log one of the statements that I set in my function code.
But the result is like the following the picture. Apreciate that if somebody can help!!
Console
var sql = require('mssql');
var config = require('./configuration/sqlconfig');
var Username = "Testing";
sql.connect(config);
console.log("Connected to DB");
if (!UserExist(Username)) {
InsertNewRecord(Username);
}
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function UserExist(Username) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
return true;
} else {
console.log("The user is existed already.");
return false;
}
}).catch(function (err) {
//When errors come
});
}
function InsertNewRecord(Username) {
console.log('Attempting to Insert records...');
new sql.Request().query("INSERT INTO dbo.Embright_Users (Username) VALUES ('" + Username + "');");
console.log("Added one new record");
}
The callbacks are not chained correctly. The InsertNewRecord() should be passed as callback to UserExist() function to make sure the execute in sequence. eg:
// Calling UserExist with a callback instead of 'if' statement
UserExist(Username, InsertNewRecord)
function UserExist(Username, callback) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
// Calling InsertNewRecord with the username passed
callback(Username);
} else {
console.log("The user is existed already.");
// Do nothing
}
}).catch(function (err) {
//When errors come
});
}

Mailgun - Attach a file in phantomjs

I am trying to make a application using phantomjs which requires mailgun service to send email. Since there is no official mailgun phantomjs library, I am facing some troubles with attaching files in the emails. The email is dispatched successfully but I dont see any attachment to it.
Here is the code:
function ObjToQs(obj) {
var str = "";
for (key in obj) {
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
return str;
}=
var page = require('webpage').create(),
url = 'https://api.mailgun.net/v3/sandboxbxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org/messages',
data = {
from: "Ganesh <mail#gmail.com>",
to: "email#gmail.com",
subject: "subject!",
text: "Body",
attachment: '/path/test.txt'
};
console.log(ObjToQs(data));
page.customHeaders = {'Authorization': 'Basic ' + btoa('api:key-xxxxxxxx')};
page.open(url, 'post', ObjToQs(data), function (status) {
if (status !== 'success') {
console.log('FAIL to load the log');
console.log(status);
} else {
console.log('Log success');
var result = page.evaluate(function () {
return document.body.innerText;
});
console.log("log Result: " + result);
phantom.exit();
}
});
What should I do?
Thanks!
This will work for you -- it's a NodeJS lib for mailgun: https://www.npmjs.com/package/mailgun-js

Uploaded image on parse.com gives 403 error

I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com

JSON store hangs while retrieving data

We have observed that at certain times accessing the JSONStore API's hangs for long time, to make it work we have to call the function again or app has to be taken to background & bring to foreground again.
NOTE : when application faces this issue, behaviour is same until we reinstall the app or reboot the device.
There doesn't appear to be any proper scenarios for this, we have searched many articles but did not find any solution, any solutions are welcome.
We observed this issue on Android devices like S5 and S4.
Here is my code Snippet:
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { user_id : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}
Logs when everything works fine http://pastebin.com/NVP8ycTG
Logs when accessing JSON store hangs, it will work only when app taken to background & bring back to foreground again http://pastebin.com/eYzx57qC
JSON store is initialised as below
var collections = {
// User
user: {
searchFields: {
user_id : 'string',
user_name : 'string',
first_name : 'string',
last_name : 'string',
}
}
}};
// Storage encryption
var options = {};
if (key) {
options.password = key;
options.localKeyGen = true;
}
// Open the collection
var promise = WL.JSONStore.init(collections, options)
.then(function() {
Logger.debug("initializeAppStorage: " + JSON.stringify(collections) + " completed");
initAppStorageSuccessCallback(true);
return true;
})
// Handle failure
.fail(function(errorObject) {
Logger.error("initializeAppStorage: failed, error: " + errorObject.toString());
initAppStorageFailureCallback(errorObject.toString());
return false;
});
return promise;
Thanks.
Try this one :
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { key : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}