UrlFetchApp.fetch() skip on empty cell - javascript

I've written a script that gets an image url from a cell in Google Sheets and adds that image to a template in Google Docs. However, when the cell is empty, the script crashes:
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
Really new to programming and would appreciate anyones help as to how to prevent the above code from crashing in the event a cell is empty

Usually there are two options:
Check the value before:
if (row[14] != '') {
var beforePhoto1 = UrlFetchApp.fetch(row[14]).getBlob();
} else {
console.log('row[14] was empty');
var beforePhoto1 = 'default_value';
}
// rest code
Try to use the value and skip any error with try/catch:
try {
var beforePhoto1 UrlFetchApp.fetch(row[14]).getBlob();
} catch(e) {
console.log('row[14] was empty');
var var beforePhoto1 = 'default_value';
}
// rest code

Related

How do I use data out of chrome.storage.get function?

I'm trying to grab data from chrome extension storage, but I can use them only in this function.
var help = new Array();
chrome.storage.local.get(null, function(storage){
//get data from extension storage
help = storage;
console.log(storage);
});
console.log(help); // empty
Result in console:
content.js:1 content script running
content.js:11 []
content.js:8 {/in/%E5%BF%97%E9%B9%8F-%E6%99%8F-013799151/: "link", /in/adam-
isaacs-690506ab/: "link", /in/alex-campbell-brown-832a09a0/: "link",
/in/alex-davies-41513a90/: "link", /in/alex-dunne-688a71a8/: "link", …}
Async function has won. I wrote my code again and now function is called hundreds time, i can not do this in dirrefent way
code:
console.log("content script running");
var cards = document.getElementsByClassName("org-alumni-profile-card");
var searchText = "Connect";
function check(exi, cards) {
chrome.storage.local.get(null, function(storage) {
for (var key in storage) {
if (storage[key] == "link" && key == exi) {
cards.style.opacity = "0.3";
}
}
});
}
for (var i = 0; i < cards.length; i++) {
var ctd = cards[i].getElementsByClassName(
"org-alumni-profile-card__link-text"
);
var msg = cards[i].getElementsByClassName(
"org-alumni-profile-card__messaging-button-shrunk"
);
if (ctd.length < 1 || msg.length > 0) {
cards[i].style.display = "none";
} else {
var exi = cards[i]
.getElementsByClassName("org-alumni-profile-card__full-name-link")[0]
.getAttribute("href");
check(exi, cards[i]);
}
}
SOLUTION of my problem
I wanted to delete this topic, but I can not, so instead of doing that, I'll put here what I've done finally.
The code above is wrong becouse, it was taking a list of links from website and for each from them script was grabbing a data from a storage... Which was stupid of course. I didn't see a solution which was so easy:
Put all your file's code in this function - it grabs data from storage just once.
I'm so sorry for messing up this wonderfull forum with topic like this.
Hope u'll forgive.
help will return undefined because it is referencing a asynchronous function and not the return value of that function. The content from storage looks to be printed on content.js:8, i.e. line 8.

Check whether file exists in Google Drive by using trigger file IDs

I capture file ids from triggers and check whether file exists in drive by. The below script throws exception and terminates the scripts abruptly if any of the trigger associated file is missing or if it is trash as mentioned in the Apps script openById documentation (which is natural). How do I overcome this?
function getForms() {
try {
var formsList = [];
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
var fid = triggers[i].getTriggerSourceId();
if (fid) {
var title = FormApp.openById(fid).getTitle() == "" ? "Untitled" : FormApp.openById(fid).getTitle();
formsList.push([title, fid]);
}
}
return formsList;
} catch (e) {
;//catch errors
}
}
You may use the try catch statement wisely to avoid the Exception:
try {
if (fid) {
var title = FormApp.openById(fid).getTitle() == "" ? "Untitled" : FormApp.openById(fid).getTitle();
formsList.push([title, fid]);
}
} catch (e) {
Logger.log(e.message);
}
Use try catch inside for loop instead of outside in a useless place

Dynamics CRM 2016 Javascript forEach not supported

So I am trying to write javascript code for a ribbon button in Dynamics CRM 2016 that will grab a phone number from a list of Leads that can be seen in the Active Leads window.
However, when I try to run it, I get an error telling me
As I step into my code (I'm debugging), I see this error
Here is the code I am working with.
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
// this should iterate through the list
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
//this should get the id and name of the selected lead
getPhoneNumber(selected, SelectedEntityTypeName);
});
}
//I should have the lead ID and Name here, but it is returning null
function getPhoneNumber(id, entityName) {
var query = "telephone1";
Sdk.WebApi.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
// I'm trying to capture the number and display it via alert.
alert(telephone1);
},
function (error) {
alert(error);
})
}
Any help is appreciated.
What you have is an javascript error. In js you can only use forEach on an array. SelectedControlSelectedItemIds is an object not an array.
To loop though an object, you can do the following.
for (var key in SelectedControlSelectedItemIds){
if(SelectedControlSelectedItemIds.hasOwnProperty(key)){
getPhoneNumber(SelectedControlSelectedItemIds[key], SelectedEntityTypeName)
}
}
Okay, so I figured it out. I had help, so I refuse to take full credit.
First, I had to download the SDK.WEBAPI.
I then had to add the webAPI to my Javascript Actions in the Ribbon Tool Bench.
Then, I had to create a function to remove the brackets around the
SelectedControlSelectedItemIds
Firstly, I had to use the API WITH the forEach method in order for it to work.
These are the revisions to my code.
function removeBraces(str) {
str = str.replace(/[{}]/g, "");
return str;
}
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
//alert(SelectedEntityTypeName);
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
getPhoneNumber(removeBraces(selected), SelectedEntityTypeName);
// alert(selected);
});
}
function getPhoneNumber(id, entityName) {
var query = "telephone1";
SDK.WEBAPI.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
formatted = telephone1.replace(/[- )(]/g,'');
dialready = "1" + formatted;
withcolon = dialready.replace(/(.{1})/g,"$1:")
number = telephone1;
if (Xrm.Page.context.getUserName() == "Jerry Ryback") {
url = "http://111.222.333.444/cgi-bin/api-send_key";
} else if(Xrm.Page.context.getUserName() == "Frank Jane") {
url = "http://222.333.444.555/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bob Gilfred"){
url = "http://333.444.555.666/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Cheryl Bradley"){
url = "http://444.555.666.777/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bill Dunny"){
url = "http://555.666.777.888/cgi-bin/api-send_key";
}
if (url != "") {
var params = "passcode=admin&keys=" + withcolon + "SEND";
var http = new XMLHttpRequest();
http.open("GET", url + "?" + params, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
}
},
function (error) {
// alert(error);
})
}
To elaborate, once I successfully get the number, I remove the parenthesis, dashes and white-space. Then, I add a "1" to the beginning. Finally, I insert colons in between each number. Then, I create an HTTP command and send it to the office phone of whoever is using CRM at the time. The user eval and HTTP message is my code. I'm showing you all of this because it was a great learning experience, and this feature really adds to the functionality.
I hope some of you find this useful.
Thanks for the help.

How can I capitalize field text values at OnChange in MS CRM 2015?

I'm fairly new to CRM development and I'm trying to customize my account form to Capitalize any text field at onChange. I'm currently working with this function that I found online:
function UpperCaseField(fieldName)
{
var value = Xrm.Page.getAttribute(fieldName).getValue();
if (value != null)
{
Xrm.page,getAttribute(fieldName).setValue(value.toUpperCase());
}
}
However, when I change a value in my test account it tells me that the method getValue() is not supported. Everything I've found tells me to use getValue(). Im at a loss.
Any help would be appreciated.
Thanks
If you're getting a getValue is not supported error, double check that the value for fieldName is actually a field on the form. It's best to code more defensively, like this:
function UpperCaseField(fieldName)
{
var attr = Xrm.Page.getAttribute(fieldName);
if (!attr) {
console.log(fieldName + " not found");
return;
}
var value = attr.getValue();
if (value != null)
{
attr.setValue(value.toUpperCase());
}
}
Update: When you connect your fields to JS functions via the form editor, CRM passes an event context as the first parameter. Here's what the code would look like in that case:
function UpperCaseField(context)
{
var fieldName == context.getEventSource().getName();
var attr = Xrm.Page.getAttribute(fieldName);
if (!attr) {
console.log(fieldName + " not found");
return;
}
var value = attr.getValue();
if (value != null)
{
attr.setValue(value.toUpperCase());
}
}
Here's more info about the context: https://msdn.microsoft.com/en-us/library/gg328130.aspx
Replace line
Xrm.page,getAttribute(fieldName).setValue(value.toUpperCase());
with line
Xrm.Page.getAttribute(fieldName).setValue(value.toUpperCase());
Also please provide a screenshot that shows how you use/register this handler.

CRM Xrm.Page.ui.formSelector.items.get() Returning Null

I wrote javascript code and added it as a form on load event of entity(contact). In that Code I want to navigate from the opening form to another form.
For previous developments, I'm trying to get the id of the opening form which I need in order to navigate.
Code as shown below.
var id = Xrm.Page.ui.formSelector.getCurrentItem().getId();
if (itemid != null)
Xrm.Page.ui.formSelector.items.get(id).navigate();
Xrm.Page.ui.formSelector.getCurrentItem() function returns a null value. It doesn't get the item so I can't get the value. What's wrong with that code, what am I missing?
Thanks for replies in advance.
You are assigning the value to id variable but checking itemid in your IF condition.
In if condition just replace the if (itemid != null) with if (id != null)
To test your JavaScript. You can run following function:
var formItem = Xrm.Page.ui.formSelector.getCurrentItem();
if (formItem != null)
{
var itemId = formItem.getId();
var itemLabel = formItem.getLabel();
alert(itemId + " | " itemLabel);
}
else
{
alert("Unable to get current form");
}
Finally, to switch between form, following is very useful function which takes the form name as parameter. you can make changes to use form Id if you like.
function redirectToForm(formName) {
var currentForm = Xrm.Page.ui.formSelector.getCurrentItem();
if (currentForm != null) {
if (currentForm.getLabel().toLowerCase() != formName.toLowerCase()) { //make sure it's not already this form
var availableForms = Xrm.Page.ui.formSelector.items.get();
for (var i in availableForms) {
var form = availableForms[i];
if (form.getLabel().toLowerCase() == formName.toLowerCase()) {
form.navigate();
}
}
}
}
}
In My case, i prefer send the form name as parameter of a kind function such as constructor via load form function.
in the javascript code:
var Formname = "Default";
function Initialize(formname)
{
Formname = formname;
}
In customization of Form, in the onload function, you set this variable and this way remove the dependece from for selector component.
I hope that this solution can help many.
I took it up a notch and wrote the following post. You might find it interesting.
http://totbcrm.blogspot.co.il/2014/08/working-with-multiple-forms.html

Categories

Resources