How to filter Tasks to show only the active ones? - javascript

Hello i try to query the tasks from sharepoint 2013 with javascript.
This is what i got so far:
var context = new SP.ClientContext.get_current();
var userSessionManager = new SP.WorkManagement.OM.UserOrderedSessionManager(context);
var userSession = userSessionManager.createSession();
var userSettingsManager = new SP.WorkManagement.OM.UserSettingsManager(context);
var locations = userSettingsManager.getAllLocations();
var locationFilter = userSettingsManager.locationFilter
var query = new SP.WorkManagement.OM.TaskQuery(context);
var myTasks = userSession.readTasks(query);
var task;
var tasks = [];
var overDue = [];
var dueSoon = [];
var anTimeDue = [];
var dateForEvaluation = new Date();
getMyTasks();
function getMyTasks() {
context.load(locations);
context.load(myTasks);
context.executeQueryAsync(onGetMyTasksSuccess, onGetMyTasksFail);
}
function onGetMyTasksSuccess() {
console.log("Successfully retrieved tasks...");
var taskEnumerator = myTasks.getEnumerator();
while (taskEnumerator.moveNext()) {
task = taskEnumerator.current;
//console.log("Task: " + task.get_id() + " - Taskname: " + task.get_name() + " - Beschreibung: " + task.get_description() + " - dueDatum: " + task.get_dueDate() + " - Startdatum: " + task.get_startDate() + " - Persönlich: " + task.get_isPersonal() + " - Fertiggestellt: " + task.get_isCompleted());
tasks.push({
taskName: task.get_name(),
description: task.get_description(),
dueDate: task.get_dueDate(),
startDate: task.get_startDate(),
personally: task.get_isPersonal(),
complete: task.get_isCompleted(),
location: task.get_locationId()
});
}
console.log(tasks);
console.log(locations)
}
// This function is executed if the above call fails
function onGetMyTasksFail(sender, args) {
console.log('Failed to get tasks. Error:' + args.get_message());
}
This code works but gives me always all Tasks back. I only need the not completed Tasks. Well i tried too look a the referenc pages but there are no code examples or anything.
So my question is how to filte the tasks to get only the not completed Tasks?
Any Advise or held would be great and thanks for your time.

As i discoverd the only working option for me is to us an if Statement where i query the is_completet method result.
Here is the now Working Code:
function onGetMyTasksSuccess() {
console.log("Successfully retrieved tasks...");
var taskEnumerator = myTasks.getEnumerator();
while (taskEnumerator.moveNext()) {
task = taskEnumerator.current;
if (task.get_isCompleted() === false) {
tasks.push({
taskName: task.get_name(),
description: task.get_description(),
dueDate: task.get_dueDate(),
startDate: task.get_startDate(),
personally: task.get_isPersonal(),
complete: task.get_isCompleted(),
location: task.get_locationId()
});
}
}
console.log(tasks);
countForForm(tasks);
}
The importend thing here is if (task.get_isCompleted() === false) its by no means perfect but i works good enough. Sadly the JavaScript API is not good documented for sharepoint sp.workmanagment.js.

Related

ServiceNow - Change a file name in Midserver

I am currently trying to replace the name of a file in the Mid Server after a scheduled export.
The idea here is that the file goes with the name in the format "file_name_datetime" and the customer needs "datetime_file_name" for the file to be correctly read by another system.
My main idea was to rename the file after the export to the correct format, but if there is a way of changing the file name to the required one I could do that also.
I would love to hear from you guys as I have no idea how can I do this.
Thanks in advance.
If anyone is interested in the answer, see below:
Script include:
initialize: function() {
this.filePath = gs.getProperty('directory_path');
this.midServer = gs.getProperty('midserver');
this.authMidServerBase64 = gs.getProperty('authmidserver');
},
nameChange: function(exportSetName) {
var exportGr = new GlideRecord("sys_export_set_run");
exportGr.addEncodedQuery("set.nameSTARTSWITH" + exportSetName);
exportGr.orderByDesc("completed");
exportGr.query();
if (exportGr.next()) {
var attachSysID = exportGr.ecc_agent_attachment.sys_id;
}
var attachGr = new GlideRecord("sys_attachment");
attachGr.addEncodedQuery("table_sys_idSTARTSWITH" + attachSysID);
attachGr.query();
if (attachGr.next()) {
var attachName = attachGr.file_name;
var attachDate = attachName.match((/\d+/));
var newName = attachDate + '_' + exportSetName + '.csv';
}
var jspr = new JavascriptProbe(this.midServer);
jspr.setName('FileNameChange'); // This can be any name
jspr.setJavascript('var ddr = new MidServer_script_include(); res = ddr.execute();');
jspr.addParameter("verbose", "true");
jspr.addParameter("skip_sensor", "true"); // prevent Discovery sensors running for the ECC input
jspr.addParameter("filename", this.filePath + "\\" + attachName);
jspr.addParameter("filePath", this.filePath);
jspr.addParameter("newName", this.filePath + "\\" + newName);
jspr.addParameter("operation", "rename");
return jspr.create();
},
Mid Server Script include:
initialize: function() {
/**
*** Set up the Packages references
**/
this.File = Packages.java.io.File;
this.FileOutputStream = Packages.java.io.FileOutputStream;
this.FileInputStream = Packages.java.io.FileInputStream;
this.Path = Packages.java.nio.file.Path;
this.Paths = Packages.java.nio.file.Paths;
this.Files = Packages.java.nio.file.Files;
this.StandardCopyOption = Packages.java.nio.file.StandardCopyOption;
/**
/* Set up the parameters
**/
this.verbose = probe.getParameter("verbose");
this.filePath = probe.getParameter("filePath");
this.filename = probe.getParameter("filename");
this.operation = probe.getParameter("operation");
this.newName = probe.getParameter("newName");
result = "initialize complete";
},
execute: function() {
if (this.operation == 'rename') {
this.fileRename(this.filename, this.newName);
}
return result;
},
fileRename: function(fileName, newName) {
result+= "\r\n Renaming file.";
this._debug(result);
try {
var res = this._moveFile(fileName, newName);
} catch (e) {
result += "\r\n Erro no renomeamento do ficheiro: " + e;
this._debug(result);
}
},
_moveFile: function(initialPath, targetPath) {
try {
this._debug("Initiating file move function");
var inPath = this.Paths.get(initialPath);
var tgPath = this.Paths.get(targetPath);
var res = this.Files.move(inPath, tgPath, this.StandardCopyOption.REPLACE_EXISTING);
result += "File successfully moved from: " + initialPath + " to: " + targetPath + " \r\n Result: " + res;
this._debug(result);
} catch (e) {
this._debug('Error:' + e);
}
},
_debug: function(m) {
if (this.verbose == "true") {
ms.log("::: Mid Server script include logger ::: " + m);
}
},
https://community.servicenow.com/community?id=community_question&sys_id=a56b38a6db326490fa192183ca961987

Use variable from callback as global variable

I made a block in which the request to the specified URL occurs.
Inside this block, I can work with the data from response, but outside this block I can not get this data because of asynchrony.
Is it possible to simulate a synchronous request in blockly or in some other way, save the received data to a global variable?
code of the created block:
Blockly.Blocks['request'] =
'<block type="request">'
+ ' <value name="URL">'
+ ' <shadow type="text">'
+ ' <field name="TEXT">text</field>'
+ ' </shadow>'
+ ' </value>'
+ ' <value name="LOG">'
+ ' </value>'
+ ' <value name="WITH_STATEMENT">'
+ ' </value>'
+ ' <mutation with_statement="false"></mutation>'
+ '</block>';
Blockly.Blocks['request'] = {
init: function() {
this.appendDummyInput('TEXT')
.appendField('request');
this.appendValueInput('URL')
.appendField('URL');
this.appendDummyInput('WITH_STATEMENT')
.appendField('with results')
.appendField(new Blockly.FieldCheckbox('FALSE', function (option) {
var delayInput = (option == true);
this.sourceBlock_.updateShape_(delayInput);
}), 'WITH_STATEMENT');
this.appendDummyInput('LOG')
.appendField('log level')
.appendField(new Blockly.FieldDropdown([
['none', ''],
['info', 'log'],
['debug', 'debug'],
['warning', 'warn'],
['error', 'error']
]), 'LOG');
this.setInputsInline(false);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(230);
this.setTooltip('Request URL');
this.setHelpUrl('https://github.com/request/request');
},
mutationToDom: function() {
var container = document.createElement('mutation');
container.setAttribute('with_statement', this.getFieldValue('WITH_STATEMENT') === 'TRUE');
return container;
},
domToMutation: function(xmlElement) {
this.updateShape_(xmlElement.getAttribute('with_statement') == 'true');
},
updateShape_: function(withStatement) {
// Add or remove a statement Input.
var inputExists = this.getInput('STATEMENT');
if (withStatement) {
if (!inputExists) {
this.appendStatementInput('STATEMENT');
}
} else if (inputExists) {
this.removeInput('STATEMENT');
}
}};
Blockly.JavaScript['request'] = function(block) {
var logLevel = block.getFieldValue('LOG');
var URL = Blockly.JavaScript.valueToCode(block, 'URL', Blockly.JavaScript.ORDER_ATOMIC);
var withStatement = block.getFieldValue('WITH_STATEMENT');
var logText;
if (logLevel) {
logText = 'console.' + logLevel + '("request: " + ' + URL + ');\n'
} else {
logText = '';
}
if (withStatement === 'TRUE') {
var statement = Blockly.JavaScript.statementToCode(block, 'STATEMENT');
if (statement) {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
" var response = this.response;\n" +
" var brightness = 'brightness: ' + JSON.parse(this.response).payload.devices[0].brightness;\n" +
" " + statement + "\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
} else {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
}
} else {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
}};
We actually use Promises extensively in our Blockly environment. My suggestion would be to Promisify this and then use a generator function. For example, we use the co library to wrap our generated code, then use yield statements for asynchronous values to make them behave synchronously. For example:
For a block setup similar to this --
The generated code would be something like this (simplified) --
co(function* () {
var getUsername;
// getFieldValue makes an asynchronous call to our database
getUsername = (yield getFieldValue("username", "my user record Id", "users"));
Promise.all(inputPromises)
let inputPromises = [];
inputPromises.push('User name is');
inputPromises.push(getUsername);
yield new Promise(function(resolve, reject) {
Promise.all(inputPromises).then(function(inputResults) {
let [TITLE, MESSAGE] = inputResults;
let activity = "toastMessage";
let LEVEL = "success";
try {
var params = {message: MESSAGE, title: TITLE, level: LEVEL};
interface.notification(params);
return resolve();
} catch(err) {
return reject(err);
}
}).catch(reject);
});
return true;
}
As you may have noticed, though, this isn't always as easy as just sticking a "yield" before the block. Depending on your setup, you may have to get more creative using Promise.all to get values in your block, etc. (We actually wound up editing a bunch of the Blockly core blocks to append 'yield' in front of inputs which had a "promise" type set amongst their output types in order to make this work, but based on your setup, this may be overkill.)
Obviously, you would need to make sure this was either transpiled or run in an environment which supports ES6.
Of course, once you enter an asynchronous setup, there's not really any going back -- co functions themselves return a Promise, so you will need to deal with that appropriately. But in general, we've found this to be a pretty robust solution, and I'm happy to help you figure it out in more detail.
You can have blocks that execute asynchronously without Promises, async functions, or callbacks by using the JS Interpreter (docs, GitHub), conveniently written by the same guy that created Blockly. JS Interpreter is a JavaScript-in-JavaScript implementation. This does mean there needs to be a lot of code to connect the functions/commands of the main JS VM to the interpreter's embedded implementation.
Blockly has a few demonstrations of doing this (src). In particular, you'll want to investigate async-execution.html and the wait block implementation. You can find the wait block running live here.
Conveniently, the interpreter's doc's section on External API happens to use XMLHttpRequest as its example implementation. This should should be a good starting point for your request block's implementation.

Get Geopoints from parse.com javascript

I have succesfuly stored some geopoints in Parse.com and now in another page i want to console log them all so i can place them into some variables and then put one marker in google map.
So i'm trying with this code to get them but for sure i miss some thing and i need your advice.
Parse.initialize("APPID", "JSKEY");
var PhotoObject = Parse.Object.extend('magazia');
var photoObject = new PhotoObject();
var query = new Parse.Query(PhotoObject);
query.select('latlon');
query.find({
success: function(locationList) {
alert("Successfully retrieved " + locationList.length + " locations.");
for (var i = 0; i < locationList.length; i++) {
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(locationList[i]));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.geolocation));
alert(location.latitude);
};
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
So i have a class called "magazia"
and inside that class there is a column which is called "latlon" and its a Geopoint. The content of this column is for example 48.29124, 28.52015 float number.
The alert shows me the correct number of rows that there are in the "magazia" class.
Does anyone knows why i dont get the results from my code above?
thanks in advance.
Ok that was a stupid mistake
var PhotoObject = Parse.Object.extend('magazia');
var photoObject = new PhotoObject();
var query = new Parse.Query(PhotoObject);
query.select('latlon');
query.find({
success: function(locationList) {
console.log("Successfully retrieved " + locationList.length + " locations.");
for (var i = 0; i < locationList.length; i++) {
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(locationList[1]));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.latlon));
var lat = location.latitude;
var lon = location.longitude;
console.log(lat, lon);
};
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
instead of locationsBlock.geolocation
there should be locationsBlock.latlon

(AdWords Script) Saving spreadsheet to specified Google Drive folder

I'm trying to get the newly created spreadsheet into a specified folder through the variable "datedFolder". Can someone assist me with this? The code is as follow.
var folderName = 'Performance_Folder';
var myAccounts = ['xxxx','yyyyy'];
function main() {
var myFolder = DriveApp.getFoldersByName(folderName).next();
var formattedDate = Utilities.formatDate(new Date(), 'GMT', 'yyyy-MM-dd');
var datedFolder = myFolder.createFolder(formattedDate);
var accountSelector = MccApp.accounts();
if (myAccounts.length > 0) {
accountSelector = accountSelector.withIds(myAccounts);
}
accountSelector.withLimit(50).executeInParallel('runOnEachAccount');
}
function runOnEachAccount() {
Logger.log('Starting on: '+AdWordsApp.currentAccount().getCustomerId());
var results = getAccountReport();
Logger.log(results);
return JSON.stringify(results);
}
function getAccountReport() {
var spreadsheet = SpreadsheetApp.create(AdWordsApp.currentAccount().getCustomerId());
var report = AdWordsApp.report(
"SELECT CampaignName, AdGroupName, KeywordText, QualityScore " +
" FROM KEYWORDS_PERFORMANCE_REPORT " +
" WHERE " +
" QualityScore < 5" +
" AND Impressions > 0" +
" DURING LAST_7_DAYS");
report.exportToSheet(spreadsheet.getActiveSheet());
Logger.log("Report available at " + spreadsheet.getUrl());
}
Greatly appreciated. Thanks!

Node.js with Restler to return a value?

This is very early in my Node and JavaScript learning. Ideally, what I am attempting to do is create a small module querying a specific type of rest endpoint and returning a specific feature based on an attribute query. The module is correctly logging out the result, but I am struggling to get the .findById function to return this result. Although aware it has something to do with how the callbacks are working, I am not experienced enough to be able to sort it out yet. Any help, advice and direction towards explaning the solution is greatly appreciated.
// import modules
var restler = require('restler');
// utility for padding zeros so the queries work
function padZeros(number, size) {
var string = number + "";
while (string.length < size) string = "0" + string;
return string;
}
// create feature service object
var FeatureService = function (url, fields) {
// save the parameters
this.restEndpoint = url;
this.fields = fields;
var self = this;
this.findById = function (idField, value, padZeroLength) {
var options = {
query: {
where: idField + '=\'' + padZeros(value, padZeroLength) + '\'',
outFields: this.fields,
f: "pjson"
},
parsers: 'parsers.json'
};
var url = this.restEndpoint + '/query';
restler.get(url, options).on('complete', function(result){
if (result instanceof Error){
console.log('Error:', result.message);
} else {
console.log(result); // this log result works
self.feature = JSON.parse(result);
}
});
return self.feature;
};
};
var restEndpoint = 'http://services.arcgis.com/SgB3dZDkkUxpEHxu/ArcGIS/rest/services/aw_accesses_20140712b/FeatureServer/1';
var fields = 'nameRiver,nameSection,nameSectionCommon,difficulty,diffMax';
var putins = new FeatureService(restEndpoint, fields);
var feature = putins.findById('awid_string', 1143, 8);
console.log(feature); // this log result does not
//console.log('River: ' + feature.attributes.nameRiver);
//console.log('Section: ' + feature.attributes.nameSection + ' (' + feature.attributes.nameSectionCommon + ')');
//console.log('Difficulty: ' + feature.attributes.difficulty);
So, I sorted out how to insert a callback from a previous thread. It appears it is just passed in as a variable and called with expected parameters. However, I now wonder if there is a better way to accept parameters, possibly in the form of options. Any advice in this regard?
// import modules
var restler = require('restler');
// utility for padding zeros so the queries work
function padZeros(number, size) {
var string = number + "";
while (string.length < size) string = "0" + string;
return string;
}
// create feature service object
var FeatureService = function (url, fields) {
// save the parameters
this.restEndpoint = url;
this.fields = fields;
var self = this;
// find and return single feature by a unique value
this.findById = function (idField, value, padZeroLength, callback) {
// query options for
var options = {
query: {
where: idField + '=\'' + padZeros(value, padZeroLength) + '\'',
outFields: this.fields,
f: "pjson"
},
parsers: 'parsers.json'
};
var url = this.restEndpoint + '/query';
restler.get(url, options)
.on('success', function(data, response){
var dataObj = JSON.parse(data).features[0];
console.log(dataObj);
callback(dataObj);
})
.on('fail', function(data, response){
console.log('Error:', data.message);
});
return self.feature;
};
};
var restEndpoint = 'http://services.arcgis.com/SgB3dZDkkUxpEHxu/ArcGIS/rest/services/aw_accesses_20140712b/FeatureServer/1';
var fields = 'nameRiver,nameSection,nameSectionCommon,difficulty,diffMax';
var putins = new FeatureService(restEndpoint, fields);
putins.findById('awid_string', 1143, 8, function(dataObject){
console.log('River: ' + dataObject.attributes.nameRiver);
console.log('Section: ' + dataObject.attributes.nameSection + ' (' + dataObject.attributes.nameSectionCommon + ')');
console.log('Difficulty: ' + dataObject.attributes.difficulty);
});

Categories

Resources