Unable to write to file with phonegap - iphone

Using the methods found on the phonegap api I'm trying to write to a file. This works in Android, but on an iOS device the writer is returning an error. Whenever I call writeFile() it returns an error, and the param passed into writeFail is -1. I cannot see why -1 is being passed into the error function, or why it's even failing to begin with. Has anyone else used the fileWriter on an iOS device, or can you see what I might be doing wrong?
function writeFile() {
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onwrite = writeSuccess;
writer.onerror = writeFail;
writer.write("some sample text");
// The file is now 'some sample text'
}
function writeSuccess() {
console.log("Write has succeeded");
}
function writeFail(evt) {
console.log(evt);
console.log(evt.target.error.code);
}

I had the same problem but I crawled through the mailing list and finally found the solution:
var writer = new FileWriter("write.txt");
This is it. Simply don't prepend the "Documents"-path. The documentation is wrong on that (still).
And don't forget to not use "readAsDataURL" as it would silently not work (on iOS). Hope I could help you.

If you want to write to a file this is the function(phonegap 2.5)
function fileWrite(filePath, text) {
var onFSWin = function(fileSystem) {
fileSystem.root.getFile(filePath, {create: true, exclusive: false}, onGetFileWin, onFSFail);
}
var onGetFileWin = function(fileEntry) {
fileEntry.createWriter(gotFileWriter, onFSFail);
}
var gotFileWriter = function(writer) {
writer.write(text);
}
var onFSFail = function(error) {
console.log(error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin, onFSFail);
}

Related

Google form that turns on and off each day automatically

I love Google Forms I can play with them for hours. I have spent days trying to solve this one, searching for an answer. It is very much over my head. I have seen similar questions but none that seemed to have helped me get to an answer. We have a café where I work and I created a pre-order form on Google Forms. That was the easy part. The Café can only accept pre-orders up to 10:30am. I want the form to open at 7am and close at 10:30am everyday to stop people pre ordering when the café isn't able to deal with their order. I used the very helpful tutorial from http://labnol.org/?p=20707 to start me off I have added and messed it up and managed to get back to the below which is currently how it looks. It doesn't work and I can't get my head around it. At one point I managed to turn it off but I couldn't turn it back on!! I'm finding it very frustrating and any help in solving this would be amazing. To me it seems very simple as it just needs to turn on and off at a certain time every day. I don't know! Please help me someone?
FORM_OPEN_DATE = "7:00";
FORM_CLOSE_DATE = "10:30";
RESPONSE_COUNT = "";
/* Initialize the form, setup time based triggers */
function Initialize() {
deleteTriggers_();
if ((FORM_OPEN_DATE !== "7:00") &&
((new Date()).getTime("7:00") < parseDate_(FORM_OPEN_DATE).getTime ("7:00"))) {
closeForm("10:30");
ScriptApp.newTrigger("openForm")
.timeBased("7:00")
.at(parseDate_(FORM_OPEN_DATE))
.create(); }
if (FORM_CLOSE_DATE !== "10:30") {
ScriptApp.newTrigger("closeForm")
.timeBased("10:30")
.at(parseDate_(FORM_CLOSE_DATE))
.create(); }
if (RESPONSE_COUNT !== "") {
ScriptApp.newTrigger("checkLimit")
.forForm(FormApp.getActiveForm())
.onFormSubmit()
.create(); } }
/* Delete all existing Script Triggers */
function deleteTriggers_() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
/* Allow Google Form to Accept Responses */
function openForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(true);
informUser_("Your Google Form is now accepting responses");
}
/* Close the Google Form, Stop Accepting Reponses */
function closeForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
deleteTriggers_();
informUser_("Your Google Form is no longer accepting responses");
}
/* If Total # of Form Responses >= Limit, Close Form */
function checkLimit() {
if (FormApp.getActiveForm().getResponses().length >= RESPONSE_COUNT ) {
closeForm();
}
}
/* Parse the Date for creating Time-Based Triggers */
function parseDate_(d) {
return new Date(d.substr(0,4), d.substr(5,2)-1,
d.substr(8,2), d.substr(11,2), d.substr(14,2));
}
I don't think you can use .timebased('7:00'); And it is good to check that you don't have a trigger before you try creating a new one so I like to do this. You can only specify that you want a trigger at a certain hour like say 7. The trigger will be randomly selected somewhere between 7 and 8. So you really can't pick 10:30 either. It has to be either 10 or 11. If you want more precision you may have to trigger your daily triggers early and then count some 5 minute triggers to get you closer to the mark. You'll have to wait to see where the daily triggers are placed in the hour first. Once they're set they don't change.
I've actually played around with the daily timers in a log by creating new ones until I get one that close enough to my desired time and then I turn the others off and keep that one. You have to be patient. As long as you id the trigger by the function name in the log you can change the function and keep the timer going.
Oh and I generally created the log file with drive notepad and then open it up whenever I want to view the log.
function formsOnOff()
{
if(!isTrigger('openForm'))
{
ScriptApp.newTrigger('openForm').timeBased().atHour(7).create()
}
if(!isTrigger('closeForm'))
{
ScriptApp.newTrigger('closeForm').timeBased().atHour(11)
}
}
function isTrigger(funcName)
{
var r=false;
if(funcName)
{
var allTriggers=ScriptApp.getProjectTriggers();
var allHandlers=[];
for(var i=0;i<allTriggers.length;i++)
{
allHandlers.push(allTriggers[i].getHandlerFunction());
}
if(allHandlers.indexOf(funcName)>-1)
{
r=true;
}
}
return r;
}
I sometimes run a log entry on my timers so that I can figure out exactly when they're happening.
function logEntry(entry,file)
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
myUtilities.saveFile(s, file, true);//this is part of a library that I created. But any save file function will do as long as your appending.
}
}
This is my utilities save file function. You have to provide defaultfilename and datafolderid.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

I am trying to email on edit, but it is not working due to the fail code listed in the body of this

This should be an easy one to fix and it'll probably be a duh moment, so here it is. I have this google script written to send an email if a certain cell is a certain value. It works just fine when "run". I want it to run onEdit, but I get this notification when it fails:
TypeError: Cannot call method "getActiveSheet" of undefined. (line 3, file "Original Copy to make it send if b29 is less than 100")
Original Code:
function email(e)
{
var sheet = e.SpreadsheetApp.getActiveSheet();
if (sheet.getName() == "Sheet1") {
var activeCell = sheet.getRange("E1");
if (activeCell.getA1Notation() == "E1") {
if (activeCell.getValue() <100)
{
MailApp.sendEmail("#gmail.com", "subject", "message")
}
}}}
Looking forward to that easy answer that I can't seem to find! Thanks in Advance!
EPR
Just remove the e.
var sheet = SpreadsheetApp.getActiveSheet();
This seems to work the best.
I have a trigger set up using the google script trigger "button" to push this everytime the sheet edits.
function emailonEdit(e)
{
var sheet = SpreadsheetApp.getActiveSheet();
if (sheet.getName() == "Sheet1") {
var activeCell = sheet.getRange("E1");
if (activeCell.getA1Notation() == "E1") {
if (activeCell.getValue() <100)
{
MailApp.sendEmail("#gmail.com", "freezer", "temp check for new script")
}
}}}

Protractor: how to click all delete buttons in a page object

I have a table with 3 rows of data and 3 delete buttons. I want to delete all rows of data and so am trying to write a method in my page object to do so... this should be a snap but I can't get it to work. I'm trying it like this:
this.rows = element.all(by.repeater('row in rows'));
this.deleteAllFriends = function() {
this.rows.each(function(row) {
row.$('i.icon-trash').click();
})
};
But this throws an error:
Error: Index out of bound. Trying to access index:2, but locator: by.repeater("row in rows") only has 1 elements
So obviously, the index protractor expects next is no longer there, because it's been deleted. How can I work around this?
This also does not work and throws the same error:
this.deleteButtons = $$('i.icon-trash');
this.deleteAllFriends = function() {
this.deleteButtons.each(function(button) {
button.click();
});
};
This also doesn't work...
this.deleteAllFriends = function() {
while(this.deleteButton.isDisplayed()) {
this.deleteButton.click();
}
};
With today's version >= 1.3.0 of Protractor you are now be able to do this at once
$$('i.icon-trash').click();
feat(protractor): allow advanced features for ElementArrayFinder
I finally figured it out...
this.deleteButtons = $$('i.icon-trash'); // locator
this.deleteAllFriends = function() {
var buttons = this.deleteButtons;
buttons.count().then(function(count) {
while(count > 0) {
buttons.first().click();
count--;
}
})
};

How to globally add a custom locator to Protractor?

I wrote a custom locator for Protractor that finds anchor elements by their ui-sref value. In my specs I just used by.addLocator to add the custom locator, but I figured this might be a cool thing to publish and have other people use it.
The goal is to add this custom locator to the global Protractor object so it can be used in any of your specs.
My initial approach was to add this functionality in the onPrepare block of the Protractor config. Something like the pseudocode below:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
That require statement would just execute this function:
function (ptorInstance) {
ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};
The problem is that by is not defined on the protractor object available in the onPrepare block. This means that I cannot use the .addLocator method.
Try the following:
function () {
by.addLocator('uiSref', function (toState, opt_parentElement) {
...
By should be in the global scope.
The protractor object passed to the onPrepare block has a By property. That By property has an inherited enumerable property named addLocator. My understanding of JavaScript is pretty shallow so it really threw me off that when I console.log'ed the protractor.By it returned {}, but if I did for (var propName in protractor.By) it would show me all the "hidden" properties. I'm still struggling to understand that bit.
Working code:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
The require would execute the function below:
function (ptor) {
ptor.By.addLocator('linkUiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.