Installable trigger onEdit in addon - Error - document not being used - events

The code included in this post is using an installable "On Edit" trigger in an addon. An error message is coming up in the console when I pass the id of the document as argument to .forSpreadsheet(ssss) in Google Apps Script:
This Add-on is attempting to create a trigger on a document that it is not currently being used in.
It seems like the Add-on doesn't recognize the active sheet properly. Where should the functions be placed? onInstall(), onOpen()?
function createSpreadsheetEditTrigger() {
var ssss = SpreadsheetApp.getActive().getId();
ScriptApp.newTrigger('onEditTrigger')
.forSpreadsheet(ssss)
.onEdit()
.create();
}
function onEditTrigger(e){
isSheetName('SheetName') && sendingEmailFunction(e);
}

Don't use the ID.
Currently:
var ssss = SpreadsheetApp.getActive().getId();
Should be:
var ssss = SpreadsheetApp.getActive();
The parameter ss for .forSpreadsheet(ss) must be a spreadsheet object. You are entering a string. getId() returns a string. Always look at the data types returned, and the data type required.
Google Documentation

From https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_programmatically
function createSpreadsheetEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('myFunction')
.forSpreadsheet(ss)
.onOpen()
.create();
}

Related

How to get query sys_id of current.sys_id Service Portal (ServiceNow)

I have a question regarding a small issue that I'm having. I've created a widget that will live on the Service Portal to allow an admin to Accept or Reject requests.
The data for the widget is pulling from the Approvals (approval_approver) table. Under my GlideRecord, I have a query that checks for the state as requested. (Ex. addQuery('state', 'requested'))
To narrow down the search, I tried entering addQuery('sys_id', current.sys_id). When I use this query, my script breaks and I get an error on the Service Portal end.
Here's a sample of the GlideRecord script I've written to Accept.
[//Accept Request
if(input && input.action=="acceptApproval") {
var inRec1 = new GlideRecord('sysapproval_approver');
inRec1.addQuery('state', 'requested');
//inRec1.get('sys_id', current.sys_id);
inRec1.query();
if(inRec1.next()) {
inRec1.setValue('state', 'Approved');
inRec1.setValue('approver', gs.getUserID());
gs.addInfoMessage("Accept Approval Processed");
inRec1.update();
}
}][1]
I've research the web, tried using $sp.getParameter() as a work-around and no change.
I would really appreciate any help or insight on what I can do different to get script to work and filter the right records.
If I understand your question correctly, you are asking how to get the sysId of the sysapproval_approver record from the client-side in a widget.
Unless you have defined current elsewhere in your server script, current is undefined. Secondly, $sp.getParameter() is used to retrieve URL parameters. So unless you've included the sysId as a URL parameter, that will not get you what you are looking for.
One pattern that I've used is to pass an object to the client after the initial query that gets the list of requests.
When you're ready to send input to the server from the client, you can add relevant information to the input object. See the simplified example below. For the sake of brevity, the code below does not include error handling.
// Client-side function
approveRequest = function(sysId) {
$scope.server.get({
action: "requestApproval",
sysId: sysId
})
.then(function(response) {
console.log("Request approved");
});
};
// Server-side
var requestGr = new GlideRecord();
requestGr.addQuery("SOME_QUERY");
requestGr.query(); // Retrieve initial list of requests to display in the template
data.requests = []; // Add array of requests to data object to be passed to the client via the controller
while(requestsGr.next()) {
data.requests.push({
"number": requestsGr.getValue("number");
"state" : requestsGr.getValue("state");
"sysId" : requestsGr.getValue("sys_id");
});
}
if(input && input.action=="acceptApproval") {
var sysapprovalGr = new GlideRecord('sysapproval_approver');
if(sysapprovalGr.get(input.sysId)) {
sysapprovalGr.setValue('state', 'Approved');
sysapprovalGr.setValue('approver', gs.getUserID());
sysapprovalGr.update();
gs.addInfoMessage("Accept Approval Processed");
}
...

Unable to view PDF attached with ServiceNow table records

I am able to successfully attach PDF file with ServiceNow table record using GlideSysAttachment API and attachment.write() function in script, however whenever I download and try to open same, I get the error shown in below screenshot.
Code snippet
(function execute() {
try{
var rec = new GlideRecord('incident');
var attachment = new GlideSysAttachment();
var incidentSysID = incident.number;
rec.get(incidentSysID);
var fileName = 'Test_Incident.pdf';
var contentType = 'application/pdf'; // Also tried with contentType as 'text/pdf'
var content = pdf_content;
var agr = attachment.write(rec, fileName, contentType, content);<br>
gs.info('The PDF attachment sys_id is: ' + agr);
}catch(err){
gs.log('Got Error: ' + err);
gs.info(err);
}
})()
I also tried "AttachmentCreator" with ecc_queue within script but same error occurs. Below is code for it.
(function execute()
{var attCreator = new GlideRecord('ecc_queue');
attCreator.agent = "AttachmentCreator";
attCreator.topic = "AttachmentCreator";
attCreator.name = "Test.pdf" + ":" + "text/pdf";
//Also tried, "Test.pdf:application/pdf"
attCreator.source = "incident"+":"+ incident.number;
// Record Table name and sys_id of the particular record
var content = pdf_content; // pdf_content is any string variable
var stringUtil = new GlideStringUtil();
var base64String = stringUtil.base64Encode(content);
var isValid=GlideStringUtil.isBase64(base64String);
var base64String= gs.base64Encode(content);
gs.info("Is valid base64 format in ecc_queue ? "+ isValid);
attCreator.payload = base64String; //base64 content of the file
attCreator.insert();
})()
I am able to attach and view excel and word files with similar scripts without any issues. I have checked system properties for attachments but everything looks fine. I am able to view the PDF file uploaded from UI to particular table records however not the one I attach via REST API or scripts.
I have also tried sending encoded data as bytes, base64 or simple string but nothing seems to work. I don't get any errors and attachment id is returned each time on creation of attachment.
After modifying my code slightly for above functions w.r.t scoped application instead of global; I got some information from logs when I debug:
05:38:38.411 Security restricted: File type is not allowed or does not match the content for file Test.pdf
05:38:38.410 Security restricted: MIME type mismatch for file: Test.pdf. Expected type:application/pdf, Actual type: text/plain
05:38:38.394 App:XYZ App x_272539_xyz_ap: Is valid base64 format in ecc_queue ? true
First a comment: This line in your code is accidentally working -- make sure you understand that a task number is not the object sys_id
var incidentSysID = incident.number; // should be incident.sys_id
Next, it's unclear where the PDF content is coming from. IF your complete code is listed, I would expect the errors given as you have noted that pdf_content is "any string variable."
ServiceNow does have a the capability to create a PDF from an HTML argument.
Generating a PDF from HTML
Here's a helpful blog post for getting a PDF (Platform generated) of an existing record:
Love PDF? PDF loves you too

e.source and e.range missing/unavailable

I have a basic installable trigger I am trying to use to send an email invite based on when a Sheet is edited (a specific checkbox is selected in my case) however when I try and access the range or source object from my event object I get [object Object] and undefined respectively. However I know the event object is working thanks to being able get the oldValue, value, triggerUid, and user.
function onEditCheck(e) {
var cells = e.range.getA1Notation();
var name = e.source.getActiveSheet().getName()
console.log('cells: ' + cells);
console.log('sheet name: ' + name);
console.log('id: ' + e.triggerUid);
console.log('edit: ' + e.value);
if(e.oldValue === 'false' && e.value === 'TRUE') {
sendEmail(e.user.getEmail(), e.range);
}
}
The only other reference to this issue I could find was this question here however I have had no luck with the permissions "solution" they found.
Any help or insight would be appreciated.
This is because necessary authorization wasn't granted to your script.
Add this somewhere in your code:
//SpreadsheetApp.getActive()
This will trigger the oAuth flow and request the permission to access Spreadsheets, which was missing.
Related:
IssueTracker
User response missing on Form submit
This worked for me:
function createTrigger(){
var tr=ScriptApp.newTrigger('onEditCheck').forSpreadsheet('My SSID').onEdit().create();
}
function onEditCheck(e) {
var cell = e.range.getA1Notation();
var name = e.range.getSheet().getName();
var data=Utilities.formatString('<br />Cell Edited: %s<br />Name of Sheet: %s<br />TriggerId: %s<br />Value: %s<br />Old Value: %s<br />',cell,name,e.triggerUid,e.value,e.oldValue);
var userInterface=HtmlService.createHtmlOutput(data);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Testing')
}
By the way it's really handy to go to the trigger editor after creating the trigger and set notifications to immediate. That way you'll get notifications to failures pretty fast from Google Server.

Add a note using the OOB dialog from a webresource

Im working with Microsoft Dynamics CRM. The client is requesting to be able to add notes from a webresources.
I thought that something like this will do the trick:
Xrm.Utility.openEntityForm("annotation", null, parameters);
or even the classic
/main.aspx?etn=annotation&pagetype=entityrecord#
But I receive a "Query Builder Error: The specified record type does not exist in Microsoft Dynamics CRM"
It seems like notes is not something we can open in that way but I cannot found the right way (if even exists!)
Any help?
Maybe this can help someone in the future: This will open a dialog with the Regarding field filled, the textboxs for title and description and the attachments field.
function createNote() {
var EntityID = Xrm.Page.data.entity.getId(); // to get entity id
var ServicerURL = Xrm.Page.context.getClientUrl(); // to get server url
var etc =Xrm.Page.context.getQueryStringParameters().etc; // to get entity type code, make sure not to hard code it, because it could changed in another deployment
var NotesURL = ServicerURL + "/notes/edit.aspx?pId=" + EntityID + "&pType=" + etc;
var features = "copyhistory=no,top=110,left=280,width=600,height=400";
window.open(NotesURL, "", features);
}

Query logging tool for Firefox

I am looking for a way to log my own queries I submit to Google in Firefox. Is there a way so I can store them in a log file?
Cheers.
Do you need write an add-on and you can use many tools for solve this.
You can chose:
HTTP Observers
Listening to events on tabs
Load Events
WebProgressListeners
https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions/XUL_School/Intercepting_Page_Loads
https://developer.mozilla.org/en/docs/Listening_to_events_on_all_tabs
To log JS msj (error, warnings, logs) to disk, set the environment variable XRE_CONSOLE_LOG to the path to the filename. i.e. export XRE_CONSOLE_LOG=/path/to/logfile or set XRE_CONSOLE_LOG=C:\path\to\logfile.
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/XULRunner/Debugging_XULRunner_applications
Or you can create files
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
// get the "data.txt" file in the profile directory
var file = FileUtils.getFile("ProfD", ["GoogleQuery.txt"]);
// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
var ostream = FileUtils.openSafeFileOutputStream(file);
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
return;
}
// Data has been written to the file.
//data is your string of your Google queries
});
Here is an add-on for Firefox or IE to log queries
http://www.lemurproject.org/querylogtoolbar/

Resources