IF Function - Google Scripts - if-statement

I'm struggling to get my Script to run an IF function. Basically I want to run a script based on specific cell contents.
I would like an IF function to run based on this and have written the following code:
function sendemail () {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = SpreadsheetApp.getActiveSheet();
var targetSheet = ss.getSheetByName("Response");
var vCodes = ss.getSheetByName("Codes")
var vResults = targetSheet.getRange("E2").getValues();
var emailAddresses = targetSheet.getRange("B2").getValues()
var dataRange = vCodes.getRange(1, 1, vResults, 1).getValues();
var subject = "Here are your Wi-Fi Codes!";
var vLength = vCodes.getRange("C2").getValues();
if (vLength == "24 hours"){
MailApp.sendEmail(emailAddresses, subject, dataRange);
targetSheet.deleteRows(2);
vCodes.deleteRows(1,vResults);
}
}
If the value in C2 is "24 hours" I'd like it to send an e-mail. At the moment when I run the script there are no errors but it doesn't send any e-mail as the IF function obviously isn't running correctly.
If I edit the code to say:
if (vLength == "")
then the e-mail sends. It doesn't seem to recognise "24 hours" as valid data to look up.
Can anyone see what I'm doing wrong?

The value you get from the cell is not what you think because you are using getValues() with an 's' and you probably know that this method always returns an array of arrays, even when a single cell is defined as range.
You have 2 options :
use getValue() to get the string content of the cell
use getValues()[0][0] to get the first (and only) element of this array.
I would suggest the first solution as I think it's generally a good idea to use appropriate methods... getValue() for single cell and getValues() for multiple cells...
I didn't check further but I'm pretty sure it will work with this change (applies to vResults , emailAddresses and vLength) .
It would also be careful to ensure that vResults is a number since you use it to define a range... you could use Number(vResults) as a safety measure.

Related

Check if any cell in specified range meets 2 conditions

I'm putting together a macro that sends alert e-mails if two conditions are met.
The e-mails are being sent, but indiscriminately and not just when the conditions I want to set are being met.
The conditions: send an e-mail if any cell inside the range (I1:I9999) has white as background colour AND contains the text "QC".
This is what I have tried:
var QCJobRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WIP").getRange("I1:I9999");
var Location = QCJobRange.getValue();
// Check for white cells with value=QC in Location column
if (Location = "QC") and (Background = "#ffffff");
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WIP").getRange("C2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'bla';
var subject = 'bla';
MailApp.sendEmail(emailAddress, subject, message);
I'm working directly in the script editor that you can open from Google sheets.
It seems that some operators are not being picked up, f. e. "and" is not even highlighted and I get the following error message: "and" is not defined.
I've been combing the forums for a simple solution but am kind of stuck on the problem with "and".
Any suggestions?
Google Apps Script is based on Javascript
The syntax for "and" is &&
The syntax for an if statement is if(condition1&&condition2){...do something...};
The method getValue() is applicable to a single value (from a single cell), while getValues() is to be used for value ranges, which represent 2-dimentsional arrays
If you want to compare two values, use the operator ==
Here is a sample to modify your code in roder to send a message if the background of cell "I1" is white and its value "QC":
function myFunction() {
//if you do not have 999 rows full of data, please reduce your range - otherwise your code will be slow
var QCJobRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WIP").getRange("I1:I9999");
var Locations = QCJobRange.getValues();
var firstLocation=Locations[0][0];
// Check for white cells with value=QC in Location column
if (firstLocation == "QC"&& QCJobRange.getBackgrounds()[0][0]== "#ffffff"){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("WIP").getRange("C2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'bla';
var subject = 'bla';
MailApp.sendEmail(emailAddress, subject, message);
}
}
Please consult the Apps Script tutorial for more samples and information:

How to build a Postman url query with Pre-request Scripts

I'm trying to use a pre-request script to build out a request object based on data pulled from a CSV file. The problem is that the request seems to be set in stone prior to the pre-request script being run. That would seem to make this a mid-request script almost rather than a pre-request.
My code is as follows:
if(ipList === undefined) ipList = "1.2.3.4,2.3.4.5,123.234.345.465";
let ips = ipList.split(',');
let queryArray = [];
for( i=0; i<ips.length; i++){
queryArray.push({ "key": "ip", "value": ips[i] });
}
console.log(queryArray);
pm.request.url.query = queryArray;
console.log(pm.request);
When I hardcode a url query variable in the request to equal 4.3.2.1, the pm.response.url object like this:
pm.request.url.query[0] = {key:"ip", value:"4.3.2.1"}
Note that the url.query[0] part of the object matches the parameter in the actual get request.
When I change the value of pm.request.url.query to equal the new query array, however as you can see here, the query array is set correctly, but the parameters are not appended to the request URL.
So unless I'm doing something wrong, it appears that the request is immutable even to the pre-request scripts.
So my question is this:
Is there a way to modify the url params of a request prior to making the request?
BTW: I know that is might seem odd to have multiple params with the same key in a query, but that's the way this API works and hard coding multiple ip addresses in the query works just fine.
You could just assign a new value to pm.request.url.
Here I had some query params already in the URL, which I had to edit:
const urlSplit = request.url.split('?');
const paramsString = urlSplit[1]; // the second part actually represents the query string we need to modify
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
params.bla = params.bla + 'foobar';
newQueryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
pm.request.url = urlSplit[0] + '?' + newQueryString;
In the end, I just constructed a new URL, using the first part of the previous one & the query string with the edited bla parameter.
This seemed to work for me--it didn't change what the UI shows the query string is, but it changed what the actual request was (looking at the console log)
pm.request.url.addQueryParams(["a=1", "b=2"])
pm.request.url.query.remove("b")
I have some parameters called "script_loginAs" etc... named such that people on my team know the parameter is evaluated and not sent.

Parsing email with Google Apps Script, regex issue?

I used to be quite proficient in VBA with excel, but I'm currently trying to do something with Google Scripts and I am well and truly stuck.
Basically, I am trying like to extract data out of a standardised email from Gmail into a Google sheet. There are a couple of other threads on the subject which I have consulted so far, and I can get the body of the email into the sheet but cannot parse it.
I am new to regex, but it tests OK on regex101
I am also brand new to Google Script, and even the debugger seems to have stopped working now (it did before, so would be grateful if anyone can suggest why this is).
Here is my basic function:
function processInboxToSheet() {
var label = GmailApp.getUserLabelByName("NEWNOPS");
var threads = label.getThreads();
// Set destination sheet
var sheet = SpreadsheetApp.getActiveSheet();
// Get all emails labelled NEWNOPS
for (var i = 0; i < threads.length; i++) {
var tmp,
message = threads[i].getMessages()[1], // second message in thread
content = message.getPlainBody(); // remove html markup
if (content) {
// search email for 'of:' and capure next line of text as address
// tests OK at regex101.com
property = content.match(/of:[\n]([^\r\n]*)[\r\n]/);
// if no match, display error
var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';
sheet.appendRow([property]);
} // End if
// remove label to avoid duplication
threads[i].removeLabel(label)
} // End for loop
}
I can append 'content' to the sheet Ok, but cannot extract the address text required by the regex. Content displays as follows:
NOPS for the purchase of:
123 Any Street, Anytown, AN1 1AN
DATE: 05/05/2017
PRICE: £241,000
Seller’s Details
NAME: Mrs Seller
Thanks for reading :)
The return value of .match() is an array. The first captured group, containing the address, will be at index 1.
Based on the following line after your call to .match(), it looks like the tmp variable should have been assigned that array, not the property variable.
var property = (tmp && tmp[1]) ? tmp[1].trim() : 'No property';
That line says, if .match() returned something that isn't null and has a value at index 1, then trim that value and assign to property, otherwise assign it the string 'No property'.
So, try changing this line:
property = content.match(/of:[\n]([^\r\n]*)[\r\n]/);
To this:
tmp = content.match(/of:[\n]([^\r\n]*)[\r\n]/);
Thanks Kevin, I think I must have changed it while debugging.
The problem was with my regexp in the end. After a bit of trial and error the following worked:
tmp = content.match(/of:[\r\n]+([^\r\n]+)/);

If statement for cookie - WebMatrix/Razor

I have set a cookie that I want to use to populate a form, so that users don't need to keep filling out the same form (it's submitting an inquiry to owners of holiday villas).
I've got it working fine if the cookie is already set, but it errors out if there is no cookie set.
I'm guessing I'll need to use an "if" statement, but don't quite know how to write the code.
Here is the code that sets the cookie...
Response.Cookies["BookingEnquiry"]["ReqName"] = Request["BookingReqName"];
Response.Cookies["BookingEnquiry"]["ReqEmail"] = Request["BookingReqEmail"];
Response.Cookies["BookingEnquiry"]["ReqPhone"] = Request["BookingReqPhone"];
Response.Cookies["BookingEnquiry"]["NumAdults"] = Request["BookingNumAdults"];
Response.Cookies["BookingEnquiry"]["NumChildren"] = Request["BookingNumChildren"];
Response.Cookies["BookingEnquiry"]["ReqMessage"] = Request["BookingReqMessage"];
Response.Cookies["BookingEnquiry"].Expires = DateTime.Now.AddHours(4);
}
Here are the variables that collect info from the cookie...
var reqname = Request.Cookies["BookingEnquiry"]["ReqName"];
var reqemail = Request.Cookies["BookingEnquiry"]["ReqEmail"];
var reqphone = Request.Cookies["BookingEnquiry"]["ReqPhone"];
var numadults = Request.Cookies["BookingEnquiry"]["NumAdults"];
var numchildren = Request.Cookies["BookingEnquiry"]["NumChildren"];
var reqmessage = Request.Cookies["BookingEnquiry"]["ReqMessage"];
and here is a sample input from the form...
<label>Name</label>
<input type="text" name="BookingReqName" id="BookingReqName" placeholder="full name…" value="#reqname">
In WebMatrix C#.net, I think you are looking for something like this:
if(Request["BookingReqName"] != null)
{
Response.Cookies["BookingEnquiry"]["ReqName"] = Request["BookingReqName"];
}
else
{
Response.Cookies["BookingReqName"] = ""; //<--Whatever default value you want (I've used an empty string here, so you, at least, won't get a null reference error).
}
Or you can use the same code as a one liner (to not clutter up your code, however this will decrease readability, obv.).
if(Request["BookingReqName"] != null){Response.Cookies["BookingEnquiry"]["ReqName"] = Request["BookingReqName"];}else{Response.Cookies["BookingReqName"] = ""; //<--Whatever default value you want (I've used an empty string here, so you, at least, won't get a null reference error).}
You'll just have to do that for all of your lines requesting cookie values.
The point is, though, that anything can go in the "else" block that helps you handle what to do when the cookie values have been cleared/expired (which you must always expect). You could redirect to a page that requests information from the user to reset any "forgotten" configurations, or, if you want to persist the data no matter what, consider storing these values in a database, instead, as those values won't clear/expire.
One last thing, if this doesn't help:
If you find yourself wondering what value to store in the cookie (the default value you wish to specify), because you need to know, right then and there, what it was supposed to have remembered, then I am afraid it is time to reconsider how you have structured the flow of data.
Sorry, but I have done that, once upon a time, only with Session variables, and it wasn't pretty :)
If you need any help with the best way(s) to transfer data between web pages, check this very helpful, concise link from Mike Brind's website: http://www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages
It should just be the following
if(Request.Cookies["BookingEnquiry"] == null)
{
return; // <- if BookingEnquiry is null we end this routine
}
// Normal code flow here...
or something similar

Locking script when accessing spreadsheet doesnot work

My problem is how to ensure that no data will be lost while concurrent access.
I have script published as web-app. I want to add new row to DATA_SHEET. The function that handles submit button looks like this:
function onButtonSubmit(e) {
var app = UiApp.getActiveApplication();
var lock = LockService.getPublicLock();
while (! lock.tryLock(1000))
;
var ssheet = SpreadsheetApp.openById(SHEET_ID);
var sheet = ssheet.getSheetByName(DATA_SHEET);
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var rangeToInsert = sheet.getRange(lastRow+1, 1, 1, lastCol);
var statText = rangeToInsert.getA1Notation();
rangeToInsert.setValues(<some data from webapp form>);
app.getElementById('statusLabel').setText(statText);
lock.releaseLock();
return app;
}
But it seems that this does not work. When I open two forms and click submit button within one second, it shows same range in statsLabel and writes data into same range. So I lose data from one form.
What is wrong with this code? It seems like tryLock() does not block script.
Is there any other way how to prevent concurrent write access to sheet?
It might be worth taking a look at appendRow(), rather than using getLastRow()/setValues() etc.
Allows for atomic appending of a row to a spreadsheet; can be used
safely even when multiple instances of the script are running at the
same time. Previously, one would have to call getLastRow(), then write
to that row. But if two invocations of the script were running at the
same time, they might both read the same value for getLastRow(), and
then overwrite each other's values.
while (! lock.tryLock(1000))
;
seems a bit hinky. Try this instead:
if (lock.tryLock(30000)) {
// I got the lock! Wo000t!!!11 Do whatever I was going to do!
} else {
// I couldn’t get the lock, now for plan B :(
GmailApp.sendEmail(“admin#example.com”, “epic fail”,
“lock acquisition fail!”);
}
http://googleappsdeveloper.blogspot.com/2011/10/concurrency-and-google-apps-script.html
You must insert this code when using getLastRow()/setValues() with lock.
SpreadsheetApp.flush();
// before
lock.releaseLock();