I am attempting to list all user aliases in our network. However, I am having a bit of trouble. I'm working from a bit of canned code here. I know the alias is an array but accessing it per user then listing just the aliases has me seeing double. Any help or tips is much appreciated!
function AliasDomainUsersList() {
var users_alias = [];
var options_alias = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 100,
projection: "full", // Fetch basic details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options_alias);
response.users.forEach(function(user) {
users_alias.push([user.name.fullName, user.primaryEmail]);
});
// For domains with many users, the results are paged
if (response.nextPageToken) {
options_alias.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users-Aliases") || ss.insertSheet("Users-Aliases", 1);
sheet.getRange(1,1,users_alias.length, users_alias[0].length).setValues(users_alias);
}
I think something like this might work. I haven't tested this because I'm the only person in my business account.
function AliasDomainUsersList() {
var users_alias = [];
var options_alias = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 100,
projection: "full", // Fetch basic details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options_alias);
for(var i=0;i<response.users.length;i++) {//you will probably want to do this your way.
users_alias.push([response.users[i].name,response.users[i].primaryEmail]);
}
// For domains with many users, the results are paged
if (response.nextPageToken) {
options_alias.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users-Aliases") || ss.insertSheet("Users-Aliases", 1);
sheet.getRange(1,1,users_alias.length, users_alias[0].length).setValues(users_alias);
var sheet2=ss.getSheetByName('AnotherSheet')
var rg2=sheet2.getRange(1,1,users_alias.length,1);
var vA2=rg2.getValues();
for(var i=0;i<vA2.length;i++) {
vA2[i][0]=users_alias[i][1];
}
rg2.setValues(vA2);
}
Managed to work out the solution (with some help). Here it is:
function getDomainUsersList() {
var users = [];
var options = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 500,
projection: "full", // Fetch details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options);
response.users.forEach(function(user) {
users.push([user.name.fullName, user.primaryEmail]);
});
// For domains with many users, the results are paged
if (response.nextPageToken) {
options.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users") || ss.insertSheet("Users", 1);
sheet.getRange(1,1,users.length, users[0].length).setValues(users);
}
Related
Currently I'm working on a script that checks values of one column and based on that send email containing information from another column. Everything works perfectly except one thing - it send one email per value and I'd like to send all the values in one email. Can someone please help with the issue ?
const helpsheet = SpreadsheetApp.openById("ID").getSheetByName('Sheet');
const date = helpsheet.getRange(1,10).getValue();
const ss = SpreadsheetApp.openById("ID2");
const sh = ss.getSheetByName('Sheet2');
const data = sh.getRange('A2:c'+sh.getLastRow()).getValues();
var recipients = 'EMAIL#EMAIL';
var subject = 'SUBJECT';
data.forEach(r=>{
let overdueValue = r[2];
if (overdueValue > date)
{
let path = r[0];
MailApp.sendEmail({
to: recipients,
subject: subject,
htmlBody: 'Hi guys ' + path +'!<br><br>Best regards,'
});
}
});
} ```
Of course I can't test this because 1st I don't want a bunch of emails to myself and 2nd I don't have a data set that matches your data, but I'm pretty sure this will do what you want. What I do is build an array of rows that pass the sniff test using the Array push method below. Then when I have all the rows that pass I send one email.
I have edited this post to include functions to create an html table.
function test() {
try {
const helpsheet = SpreadsheetApp.openById("ID").getSheetByName('Sheet');
const date = helpsheet.getRange(1,10).getValue();
const ss = SpreadsheetApp.openById("ID2");
const sh = ss.getSheetByName('Sheet2');
const data = sh.getRange('A2:c'+sh.getLastRow()).getValues();
var pre = "Hello";
var post = "Best regards";
var recipients = 'EMAIL#EMAIL';
var subject = 'SUBJECT';
var passed = [];
data.forEach( r => {
let overdueValue = r[2];
if (overdueValue > date) {
passed.push(r);
}
});
if( passed.length > 0 ) { // maybe nothing passed the test
var html = createHTMLfile(true);
html = html.concat("<p>"+pre+"</p>");
html = html.concat(createTable(passed));
html = html.concat(createHTMLfile());
html = html.concat("<p>"+post+"</p>");
MailApp.sendEmail( {
to: email,
subject: subject,
htmlBody: html });
};
}
}
catch(err) {
console.log(err);
}
}
I have added the additional functions to create the table. You are welcome to play with the <style>s.
function createHTMLfile(pre) {
if( pre ) {
return "<html><head><style>table, td { border: thin solid black; border-collapse:collapse; text-align:center }</style></head><body>";
}
else {
return "</body></html>";
}
}
function createTable(data) {
try {
var width = 600/data[0].length;
var table = "<table>";
function addCell(value) {
table = table.concat("<td style=width:"+width+"px>");
table = table.concat(value.toString());
table = table.concat("</td>");
}
function addRow(row) {
table = table.concat("<tr>");
row.forEach( addCell );
table = table.concat("</tr>");
}
data.forEach( addRow )
table = table.concat("</table>");
return table;
}
catch(err) {
console.log(err);
}
}
I have tried using ClientPeoplePickerSearchUser. Can anybody help me out? I have followed link : http://sharepointfieldnotes.blogspot.com/2014/06/sharepoint-2013-clientpeoplepicker.html
You need set "SharePointGroupID" property in the code to limit search people from a specific SharePoint group in client people picker.
function search(request,response) {
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var restSource = appweburl + "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser";
var principalType = this.element[0].getAttribute('principalType');
$.ajax(
{
'url':restSource,
'method':'POST',
'data':JSON.stringify({
'queryParams':{
'__metadata':{
'type':'SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters'
},
'AllowEmailAddresses':true,
'AllowMultipleEntities':false,
'AllUrlZones':false,
'MaximumEntitySuggestions':50,
'PrincipalSource':15,
'PrincipalType': principalType,
'QueryString':request.term
//'Required':false,
'SharePointGroupID':23,
//'UrlZone':null,
//'UrlZoneSpecified':false,
//'Web':null,
//'WebApplicationID':null
}
}),
'headers':{
'accept':'application/json;odata=verbose',
'content-type':'application/json;odata=verbose',
'X-RequestDigest':requestDigest
},
'success':function (data) {
var d = data;
var results = JSON.parse(data.d.ClientPeoplePickerSearchUser);
if (results.length > 0) {
response($.map(results, function (item) {
return {label:item.DisplayText,value:item.DisplayText}
}));
}
},
'error':function (err) {
alert(JSON.stringify(err));
}
}
);
}
I'm making a multiplayer game. below is the flow of the process when i get an error:
(1) After logging in the username is getting stored in session:
socket.on('login', function(username)
{
socket.handshake.session.username = username;
socket.handshake.session.save();
var afterLogin = '/groups';
socket.emit('afterLogin', afterLogin);
});
(2) User get redirect to another page and complete the game, after completing the game user send score and room id to the server:
var submitScore = { score: hit, room: 'gryffindor'};
socket.emit('submitScore', submitScore);
(3) Server get the score and room-id and iterate through all the client and decide the max score, get the username from the session, and send the winner name and score to all user:
socket.on('submitScore', function(submitScore)
{
var room = submitScore.room;
var score = submitScore.score;
if (room == "gryffindor")
{
gryfScoreArray[socket.handshake.session.username] = score;
checkGryfUser --;
if (checkGryfUser == 0)
{
var max = 0;
var winnerName;
for(var index in gryfScoreArray)
{
if (gryfScoreArray[index] > max)
{
max = gryfScoreArray[index];
winnerName = index;;
}
}
// console.log(socket.id);
var winner = {username: winnerName, maxScore: max}
io.in(room).emit('gryfWinner', winner);
// console.log(winner.username);
// console.log(winner.maxScore);
}
}
So, the problem is socket.handshake.session.username giving undefined in point point (3)
I'm trying to get type fields for each attribute of my entities. Quering Orion and getting entities is not the problem (I do this through NGSI Source widget) but the way getting these parameters.
From NGSI Source (usual suscription to Orion instance):
var doInitialSubscription = function doInitialSubscription() {
this.subscriptionId = null;
this.ngsi_server = MashupPlatform.prefs.get('ngsi_server');
this.ngsi_proxy = MashupPlatform.prefs.get('ngsi_proxy');
this.connection = new NGSI.Connection(this.ngsi_server, {
ngsi_proxy_url: this.ngsi_proxy
});
var types = MashupPlatform.prefs.get('ngsi_entities').split(new RegExp(',\\s*'));
var entityIdList = [];
var entityId;
for (var i = 0; i < types.length; i++) {
entityId = {
id: '.*',
type: types[i],
isPattern: true
};
entityIdList.push(entityId);
}
var attributeList = null;
var duration = 'PT3H';
var throttling = null;
var notifyConditions = [{
'type': 'ONCHANGE',
'condValues': MashupPlatform.prefs.get('ngsi_update_attributes').split(new RegExp(',\\s*'))
}];
var options = {
flat: true,
onNotify: handlerReceiveEntity.bind(this),
onSuccess: function (data) {
this.subscriptionId = data.subscriptionId;
this.refresh_interval = setInterval(refreshNGSISubscription.bind(this), 1000 * 60 * 60 * 2); // each 2 hours
window.addEventListener("beforeunload", function () {
this.connection.cancelSubscription(this.subscriptionId);
}.bind(this));
}.bind(this)
};
this.connection.createSubscription(entityIdList, attributeList, duration, throttling, notifyConditions, options);
};
var handlerReceiveEntity = function handlerReceiveEntity(data) {
for (var entityId in data.elements) {
MashupPlatform.wiring.pushEvent("entityOutput", JSON.stringify(data.elements[entityId]));
}
};
To MyWidget:
MashupPlatform.wiring.registerCallback("entityInput", function (entityString) {
var entity;
entity = JSON.parse(entityString);
id = entity.id;
type = entity.type;
for(var attr in entity){
attribute = entity[attr];
}
I'm trying to code something similar to obtain the value of type fields. How can I do that? (I'm sure it's quite easy...)
You cannot make use of the current NGSI source operator implementation (at least v3.0.2) if you want to get the type metadata of attributes as the NGSI source makes use of the flat option (discarding that info).
We are studying updating this operator to allow creating subscriptions without using the flat option. The main problem here is that other components expect the data provided by this operator being provided in the format returned when using the flat option. I will update this answer after analysing deeper the issue.
I want to build a chart to google fusion table. I know there is an option to do it with fusion table but I need to do that using google spreadsheet.
How do I import a private fusion table to a spreadsheet?
function getdata(authToken) {
query = encodeURIComponent("SELECT * FROM tableid");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
return response.getContentText();
}
The code above gives me the table headers only.
Don't set each cell individually as in the example below unless you need to process each bit of data. Using this is about 10x faster:
var rows = o.length;
var columns = o[0].length;
cell.offset(<startrow>, <startcolumn>, rows, columns).setValues(o);
After a deep research, finally i figured it out after a deep search and reading here.
This is how it looks for the code google docs spreadsheet app script:
function onOpen()
{
var tableID = '00000' // Add the table ID of the fusion table here
var email = UserProperties.getProperty('email');
var password = UserProperties.getProperty('password');
if (email === null || password === null) {
email = Browser.inputBox('Enter email');
password = Browser.inputBox('Enter password');
UserProperties.setProperty('email',email);
UserProperties.setProperty('password', password);
} else {
email = UserProperties.getProperty('email');
password = UserProperties.getProperty('password');
}
var authToken = getGAauthenticationToken(email,password);
query = encodeURIComponent("SELECT * FROM tableID");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
var tableData = response.getContentText();
var o = Utilities.parseCsv(response.getContentText());
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var index = 0;
for (var i in o) {
var row = o[i];
var col = 0;
for (var j in row) {
cell.offset(index, col).setValue(row[j]);
col++;
}
index++;
}
}
function getGAauthenticationToken(email, password) {
password = encodeURIComponent(password);
var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
method: "post",
payload: "accountType=GOOGLE&Email=" + email + "&Passwd=" + password + "&service=fusiontables&Source=testing"
});
var responseStr = response.getContentText();
responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
responseStr = responseStr.replace(/\n/g, "");
return responseStr;
}
After that you can do whatever you want in the spreadsheet.
BTW, I still think there is a simple way to import a private table into a spreadsheet automaticly.