CRM Javascript: Getting Email Address of the Participant List - javascript

In CRM 2013 I'm writing a javascript to remove certain email participants that contains a specific email address (in my code below it's test#test.com).
I was told that the best way to do this is to remove the whole email participants and re-build it, because there is no good way of just removing a specific participant from the email (please correct me if there's a better way).
So first I get all of the party in the "to" field in the email. Then I push the 'satisfactory' participants into a new array. The participants that contain test#test.com email will not be pushed into this new array i.e. get dropped from the list.
However I'm having problem trying to get the email address value from the "toParty" list.
This doesn't seem to work and returning undefined instead. Here I'm going by the email's schema name which is 'EMailAddress1'. Trying 'emailaddress1' doesn't work either.
toParty[indxAttendees].EMailAddress1 --> doesn't work
Any ideas is greatly appreciated.
var toParty = Xrm.Page.getAttribute("to").getValue();
for (var indxAttendees = 0; indxAttendees < toParty.length; indxAttendees++) {
var partyListData = new Array();
if (toParty[indxAttendees].EMailAddress1 != "test#test.com")
{
//alert("Email address " + indxAttendees + " :" + toParty[indxAttendees].EMailAddress1); --> this will be undefined value
partyListData[indxAttendees] = new Object();
//get ID
partyListData[indxAttendees].id = toParty[indxAttendees].id;
alert("ID " + indxAttendees + " :" + toParty[indxAttendees].id);
//get Name
partyListData[indxAttendees].name = toParty[indxAttendees].name;
alert("Name " + indxAttendees + " :" + toParty[indxAttendees].name);
partyListData[indxAttendees].entityType = toParty[indxAttendees].entityType;
alert("Entity Type " + indxAttendees + " :" + toParty[indxAttendees].entityType);
}

Using oDataQuery works in this case. Just have to write different function for queue since the email address field is different in queue vs. contact/account.
if ((entityType == "contact") || (entityType == "account")) {
select = "$select=EMailAddress1&$filter=" + entityType.charAt(0).toUpperCase() + entityType.slice(1) + "Id eq guid'" + entityId + "'";
var entitySet = entityType.charAt(0).toUpperCase() + entityType.slice(1) + "Set";
XrmServiceToolkit.Rest.RetrieveMultiple(entitySet, select,
function (results) {
if (results.length > 0) {
result = results[0].EMailAddress1;
}
}, function (error) { alert(error); }, function onComplete() { }, false);
return result;
}

Related

I'm trying to post a Slack message for each new row of a spreadsheet using Google Scripts - but I'm only getting one post. What am I doing wrong?

I'm trying to build a simple app to post a message to Slack for every new row in a Google Spreadsheet. I can get the info from the sheet and post it to the logger, and I can post to Slack, but I can only seem to get this to work with the first row in the loop (whereas the logger will receive all values for all rows). I'm probably just messing up the way the loops work (new to this) but having stared at it for a few hours now I can't see it. My intention is to set this to trigger on edit (it's populated from a Google Form), so I've added a column to mark when a Slack message has been sent, just to avoid a mad loop of endless messages for whatever reason.
I've tried logging the output and can get all values there. Putting the post to Slack part of the code in the same place only results in one post, though.
//Set up a variable to show when we've sent a message to Slack
var slackSentText = "Yes";
//This is hte Slack hook
var url = "https://hooks.slack.com/services/tokens!";
function getNewInfo() {
var sheetname = "Info"
var myspreadsheet = SpreadsheetApp.openById('secretID!');
var sheet = myspreadsheet.getSheetByName(sheetname);
// set rows until work out how to do more elegantly...
var startRow = 8; // First row of data to process
var numRows = 5; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 11);
var data = dataRange.getValues();
// iterate and make variables for Slack
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var idNumber = row[0];
var projectType=row[6];
var supplierName=row[2];
var projectName=row[3];
var projectDescription=row[4];
var projectStatus=row[1];
var projectDate=row[5];
var slackSent = row[10];
// check if column is marked with Slack sent note and if so ignore. If not send Slack
if (slackSent !== slackSentText) {
// Slack bit
var slackMessage = {
"channel": "ID-number-bot",
"username": "ID-bot",
"text": "\n :white_check_mark:" +
"\n *New Project:* " + idNumber +
"\n *Project Name:* " + projectName +
"\n *Supplier:* " + supplierName +
"\n *Project Status:* " + "["+projectStatus+"]" +
"\n *Project Description:* " + "_"+projectDescription+"_" +
"\n *Project Type:* " + projectType +
"\n *Estimated Delivery Date:* " + projectDate +
"\n"+ slackSent +
"\n Job folder string: \n" + "RCM "+jobNumber+" "+projectName +
"\n \n"
};
var options = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(slackMessage)
};
return UrlFetchApp.fetch(url,options);
sheet.getRange(startRow + i, 11).setValue(slackSentText);
Logger.log("jobNumber:"+jobNumber)
Logger.log("projectType:"+projectType)
Logger.log("supplierName:"+supplierName)
Logger.log("projectName:"+projectName)
Logger.log("projectDescription:"+projectDescription)
Logger.log("projectStatus:"+projectStatus)
Logger.log("projectDate:"+projectDate)
}
}
// SpreadsheetApp.flush();
}
Thanks very much everyone. Hopefully I've given enough info.
As #Tanaike proposed, your problem should be fixed by changing:
return UrlFetchApp.fetch(url,options);
To this:
UrlFetchApp.fetch(url,options)
The return keyword gets you out of the loop. The code finds return in the first iteration, so it doesn't go on with the following rows, and that's why you are only getting the first row sent.

adding to a value in a database not replacing it

So i am storing my users 'freinds' in a database and i am currently using this to add there freind to it
socket.on('addFreind', function(username, freind) {
console.log("ADD FREIND " + freind + "TO " + username)
let query = 'update users set freinds="' + freind + '" where username = "' + username + '"';
connection.query(query, function(err) {
console.log(err)
});
});
but that just replaces the original value with the new one how can i add to the original value
i have tried querying the original value and adding it to an array and then adding the new value to that array then putting it in my database but that failed horribly and i was wondering if there was just a simple way to do this

parsing JSON data with java script

I use Google plus API and get this data from it and get an error while parsing this JSON data
and here is the code I use to parse this data and get error as data object is tested and work fine and hold data as it appear in past 2 images
var allIems = data.items;
for (var element in allIems) {
document.getElementById('datafromapi').innerHTML +=
(" , published time :" + element.published +
" , last updated time :" + element.updated +
", complete url : " + element.url
);
var obj = element.object.attachments;
document.getElementById('datafromapi').innerHTML +=
(+"\nattachments of post :\n" +
" type : " +
obj[0].objectType +
" ,displayName of content : " +
obj[0].displayName +
" ,content URL : " +
obj[0].url +
" ,content data :" +
obj[0].image.url +
" ,content type : " +
obj[0].image.type +
" ,content height : " +
obj[0].image.height +
" ,content width : " +
obj[0].image.width +
"\n\n\n");
}
});
i got that error appear
Uncaught TypeError: Cannot read property 'attachments' of undefined
element values in
for (var element in allIems) {
are keys of allItems, which in this case are array indices. You have to address the actual array items like this:
var obj = allItems[element].object.attachments;
Your code element.object.attachments; tries to access property object of a number, which does not exist.
Since we know that allItems is an array, you could have written:
for (var i = 0; i < allIems.length; i++) {
var obj = allItems[i].object.attachments;
Javascript has a built in JSON parser you can use that takes in a string of the data and returns an object.
let jsonDataAsString = "{\"a\":1,\"b\":2}";
let jsonDataAsObject = JSON.parse(jsonDataAsString);
Then you can traverse through the data as an object, referencing properties using dot-notation
console.log(jsonDataAsObject.a); // 1
To be safe, you should be comparing properties to null before trying to use then
if(jsonDataAsObject.somePropery != null) {
// the property exists so you can access it here
}

Javascript assignment for school involving objects and Validation not working correctly

the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.

Javascript (and JSP) won't create table properly with if statement

So i'm using multiple if statements to draw data from a database based on the users search criteria.
What i'm struggling with is
if(request.getParameter("searchProperty")!= ""){
SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'";
if(request.getParameter("bedrooms") != "0"){
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'";
}
}
with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please?
here's where the SQL statement is built and input
MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement);
with the expected outcome being, for example
SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value'
unless value = 0 where it should just be
SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement,
request.getParameter("bedrooms") != "0"
should be something like this ,
(!request.getParameter("bedrooms").isEmpty())
Remember you are comparing the strings
so if is "0"
if(request.getParameter("bedrooms").equals("0")){
return SearchStatement ;
}
else {
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"
}
Hope this helps!!

Categories

Resources