I am currently trying to run 2 separate XMLHTTPRequests in dynamics CRM Javascript to retrieve data from 2 different entities and run code depending on what is retrieved..
I've done my best to try and edit some names for security reasons, but the premise is the same.
My main problem is that the first run of the XMLHTTPRequest (the RA Banner) works fine, but then the second run (the Status Banner) the Readystate that is returned is 2 and stopping.
function FormBanners(formContext) {
//Clear the existing banners
formContext.ui.clearFormNotification("Notif1");
formContext.ui.clearFormNotification("Notif2");
//Get the customer/rep
var customer = formContext.getAttribute("customerid").getValue();
var rep = formContext.getAttribute("representative").getValue();
var contact;
//use the rep if there is one else use the customer
if (rep != null) {
contact = rep;
}
else if (customer!= null) {
contact = customer;
}
//Get the account
var account = formContext.getAttribute("accountfield").getValue();
//As there is a requirement for 2 XMLHTTPRequests we have to queue them
var requestURLs = new Array();
//There will always be a customers or rep on the form
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/contacts?$select=new_RA,new_SC,new_VC,new_PR&$filter=contactid eq " + contact[0].id + "", true);
//there may not be an account
if (account) {
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?$select=_new_statusLookup_value&$filter=accountid eq " + account[0].id + "", true);
}
var current = 0;
function getURL(url) {
var req = new XMLHttpRequest();
req.open("GET", requestURLs[current]);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(req.response);
// Creation of the RA Banner
if (current == 0) {
var RA = result.value[0]["new_RA#OData.Community.Display.V1.FormattedValue"];
var SC = result.value[0]["new_SC#OData.Community.Display.V1.FormattedValue"];
var VC = result.value[0]["new_VC#OData.Community.Display.V1.FormattedValue"];
var PR = result.value[0]["new_PR#OData.Community.Display.V1.FormattedValue"];
var Notif = "";
//Only create a notification if any of the above contain "Yes"
if (RA == "Yes" || SC == "Yes" || VC == "Yes" || PR == "Yes") { Notif = "The Customer/Rep has:" }
if (RA == "Yes") { Notif = Notif + " RA,"; }
if (SC == "Yes") { Notif = Notif + " SC,"}
if (VC == "Yes") { Notif = Notif + " VC,"}
if (PR == "Yes") { Notif = Notif + " PR."}
if (Notif != "") {
formContext.ui.setFormNotification(Notif, "INFO", "Notif1");
}
}
//Creation of the Status Banner
else if (current == 1) {
status = results.value[i]["_new_statusLookup_value"];
if (status) {
if (status[0].name != "Open")
var Notif = "The status for the organisation on this case is " + status[0].name + ".";
formContext.ui.setFormNotification(Notif, "INFO", "Notif2");
}
}
++current;
if (current < requestURLs.length) {
getURL(requestURLs[current]);
}
} else {
Xrm.Utility.alertDialog(req.statusText);
}
}
}; req.send();
}
getURL(requestURLs[current]);
}
Can anyone help me out?
So in my example I had made many mistakes. Taking Arun's advice I separated the function out, which made debugging far easier.. it instead was not failing on the XMLHTTP Request because that worked fine, but firefox was crashing when debugging.
So my issues were that I was in the second part:
Used the value of i for results (i was no longer defined)
Getting the "_new_statusLookup_value" would only provide the guid of the lookup I would instead want "_new_statusLookup_value#OData.Community.Display.V1.FormattedValue"
Lets not ignore the fact that because I had copied and pasted many iterations of this code that I was also using "results" instead of "result".
Many little mistakes.. but it happens! Thanks for the help, just goes to show.. typos are our downfall!
The gist of the project is: I have Google Form answers that get populated on a Google doc, let's call this doc the template. The template is copied so I never overwrite the original. That copy is converted to PDF, sent to email, and moved to a specific folder on my Drive. This function happens flawlessly with every Form submission and gets triggered on submit. My next function is supposed to send that copied doc to my Google Cloud Print, but I'm having trouble writing the code for that. I have it to the point where it will print the doc on Form submit, but I have to specifically define the doc's ID. Unfortunately the ID is not static since a new doc is made with every submission. Here's my full code minus any sensitive information:
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var ship_to = values[11];
var address = values[12];
var order_count = values[7];
var program = values[2];
var workspace = values[3];
var offer = values[4];
var sort_1 = values[5];
var sort_2 = values[6];
var image_services = values[9];
var print_services = values[10];
var priority = values[13];
var notes = values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(copyId, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": copyId,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
createNewDoc(values);
printGoogleDocument(copyId, docName);
}
Return the new document from the 'createNewDoc(values);' function by changing by adding this to the end of the createNewDoc() function, right before the closing bracket:
//Starting at the code here
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
//Add this
var newDocName = docName + ' for ' + job_name;
return [file, newDocName];
//To this point
}
Then change the onFormSubmit() function as shown below:
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
var returnedDocValues = createNewDoc(values);
var file = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(file, docName);
}
Let me know if there are errors as I have not tested this code myself.
I'm having a few problems with this, so I'll try to keep it simple. What's happening in the first script is a new Google doc file gets made from a copy of a "master" doc I've defined, which gets its data populated from Form submissions, and that new copy is ultimately moved to a Folder on my Drive. The second script is supposed to send that copied file to the Google Cloud Print. The first script works perfect; I have it triggered on a form submit. The second script works by itself, but only when I explicitly define the master doc ID in the "content" section. Because with each Form submission a new doc gets made, I was having trouble integrating the new doc's ID with the second script. Right now, I tried pulling from the var file, but that's not working. I might have a syntax issue.
My other problem is I need to merge my second script with the first, in a way that gets triggered on the same Form Submit and probably execute after the PDF creation and Email send, but before it gets moved to the folder.
Any help or advice would be greatly appreciated.
And I've removed some of my IDs and sensitive information where you only see double quotes.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
**
Update 8/14 with Sandy Good's suggestion:
**
I've attempted to do what you suggested, but now it's not creating the doc or sending to the cloud print. Any thoughts?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}
Not sure if that is what you are after, but the easiest way to execute functions consecutively is to pass a callback function as an argument to your function.
Here's the list of simple functions assigned to variables.
var addFive = function(number, callback){
number += 5;
if (callback) {
return callback(number);
}
return number;
}
var multiplyByFive = function(number, callback){
number *= 5;
if (callback) {
return callback(number);
}
return number;
}
var subtractFive = function(number, callback){
number -= 5;
if (callback) {
return callback(number);
}
return number;
}
You can then just chain call them like this.
function test() {
var result = addFive(7, function(number) {
return multiplyByFive(number, function(number){
return subtractFive(number);
});
});
Logger.log(result); //logs (7 + 5) * 5 - 5 = 55
}
Of course, if your functions only perform operations like creating files and don't return values, feel free to omit the 'return' statement.
I have more questions in regards to this project, but I think this specific question has been answered, so here's the final code for future reference.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var ship_to = values[11];
var address = values[12];
var order_count = values[7];
var program = values[2];
var workspace = values[3];
var offer = values[4];
var sort_1 = values[5];
var sort_2 = values[6];
var image_services = values[9];
var print_services = values[10];
var priority = values[13];
var notes = values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}
What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();
I wrote a script in JS that will retrieve the traffic source of the user and store that value in a cookie.
For all but three pages this works. If the user's landing page is for example www.example.com/example1, www.example.com/example2 or www.example.com/example3 the cookie gets stored on those pages only. I do not see see it in developer tools on chrome but when I write document.cookie I do see the cookie I created. I also see it in settings.
But if I were to navigate to another page it doesn't get stored.
It works fine on all other pages, the user enters on the landing page and the cookie stays stored during the whole session. Except on the above pages.
The hostname is the same for all pages.
Any ideas?
var source = trafficSource();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
var source = document.referrer;
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function checkCookie() {
var verifyCookie = getCookie("Traffic Source Cookie");
if (verifyCookie != null ){
//alert("there is a cookie");
return "";
}else{
setCookie("Traffic Source Cookie", source, 30);
//alert("new cookie made");
}
}
checkCookie();
var trafficSourceValue = getCookie("Traffic Source Cookie"); // delete if doesnt work
//dataLayer.push( "Cookie Traffic Source is " +getCookie("Traffic Source Cookie"));
function trafficSource(trafficType){
var trafficType;
//set traffic sources to variables
/*var sourceSearchEngine = searchEngine();
var sourceSocialNetwork = socialNetwork();
var sourcePaidSearch = paidSearch(); */
// get what kind of referrer
var trafficReferrer = document.referrer;
var trafficURL = document.URL;
if(trafficURL.indexOf("gclid") > -1) {
trafficType = paidSearch();
//alert("paidSearch google");
} else if (trafficURL.indexOf("bing") >-1 &&(trafficURL.indexOf("ppc")> -1) || (trafficURL.indexOf("cpc") >-1)){
trafficType = paidSearch();
//alert("paidSearch bing");
}
else if((trafficReferrer.indexOf("plus.url.google.com")<= 0) && trafficReferrer.indexOf("google")>-1 || trafficReferrer.indexOf("bing")>-1 || trafficReferrer.indexOf("baidu") >-1 || trafficReferrer.indexOf("yahoo") > -1 && (trafficURL.indexOf("ppc") < 0)){
trafficType = searchEngine();
//alert("searchEngine");
//(trafficReferrer.indexOf("facebook","googleplus", "twitter", "t.co/", "linkedin", "pinterest","reddit","disqus","blogspot.co.uk") >-1
} else if ((trafficReferrer.indexOf("facebook")>-1) || (trafficReferrer.indexOf("plus.url.google.com")>-1) || (trafficReferrer.indexOf("t.co/")>-1) || (trafficReferrer.indexOf("linkedin")>-1) || (trafficReferrer.indexOf("reddit")>-1) || (trafficReferrer.indexOf("disqus")>-1) || (trafficReferrer.indexOf("blogspot.co.uk")>-1) || (trafficReferrer.indexOf("t.umblr")>-1)) {
trafficType = socialNetwork();
//alert("socialNetwork");
} else if (trafficReferrer.indexOf("")>-0){
trafficType = directSource();
//alert("direct");
}else if (trafficURL.indexOf("display") >-1 || trafficURL.indexOf("Display") >-1){
trafficType = display();
//alert("display");
}else if (trafficReferrer === "" || trafficReferrer === null){
trafficType = "Direct";
}else {
//var hostnameReturn = hostname.split("www.");
var returnReferrer = document.referrer.match(/https?:\/\/([^\/]*)(?:\/|$)/i)[1].replace(/www\./, "");
// do I need this snippet
trafficType = returnReferrer + "/Referral" ;
//alert("Hostname Referral");
}
//Return the trafficType which is the function that will get source
return trafficType;
// alert("trafficType");
}
//setCookie("trafficSource",1,30)
//search engine source
function searchEngine (referrer){
var search = document.referrer;
var bing = "bing";
var google ="google";
var yahoo = "yahoo";
var ask = "ask";
var msn = "msn";
var baidu = "baidu";
var referrer;
if (search.indexOf(bing)> -1){
//alert(bing);
referrer = bing + " organic";
} else if (search.indexOf(yahoo)>-1){
// alert(bing);
referrer = yahoo + " organic";
} else if (search.indexOf(ask)>-1){
referrer = ask + " organic";
} else if (search.indexOf(msn)>-1){
// alert(bing);
referrer = msn + " organic";
} else if (search.indexOf(baidu)>-1){
// alert(baidu);
referrer = baidu + " organic";
}
else{
// alert(google);
referrer = google + " organic";
}
return referrer;
// alert("Search Engine: " + referrer);
}
//search social network
function socialNetwork (referrer){
var search = document.referrer;
var facebook ="facebook";
var twitter = "twitter";
var googlePlus = "google plus";
var googlePlus2 = "plus.url.google.com";
var pinterest ="pinterest";
var linkedin = "linkedin";
var tumblr = "t.umblr";
var reddit = "reddit";
//var beforeItsNews ="news";
var disquis = "disqus";
var blogger = "blogspot.co.uk";
//var StumbleUpon = "StumbleUpon";
var referrer;
if(search.indexOf(facebook)> -1){
// alert(facebook);
referrer = "Social/ " + facebook;
}else if (search.indexOf(twitter)> -1 || search.indexOf("t.co/") >-1){
// alert(twitter);
referrer = "Social/ "+ twitter;
}else if (search.indexOf(pinterest)> -1){
//alert(pinterest);
referrer = "Social/ "+ pinterest;
}else if (search.indexOf(linkedin) >- 1){
//alert(linkedin);
referrer = linkedin;
}else if (search.indexOf(googlePlus) >-1 || search.indexOf(googlePlus2) >-1){
// alert(googlePlus);
referrer = "Social/ "+ googlePlus;
}else if (search.indexOf(tumblr) >-1){
// alert(googlePlus);
referrer ="Social/ "+ "tumblr";
}else if (search.indexOf(reddit) >-1){
// alert(googlePlus);
referrer = "Social/ " + reddit;
}else if (search.indexOf(disquis) >-1){
//alert(disquis);
referrer = "Social/ "+ disquis;
}else if (search.indexOf(blogger) >-1){
blogger ="Blogger";
//alert(blogger);
referrer = "Social/ "+ blogger;
}else{
// alert(document.referrer);
referrer = "Referral: " + document.referrer;
// alert("Check Cookie - Referrer");
}
return referrer;
// alert("Social Media Network: " + referrer)
}
// search for paid search
function paidSearch(referrer){
var paidCampaign = document.URL;
var campaignReferrer = document.referrer;
var referrer;
var googleAd = "gclid";
var justGoogle = "google";
var justBing = "ppc";
var bingAd = "Bing";
if (paidCampaign.indexOf(googleAd) >- 1 || campaignReferrer.indexOf(justGoogle) >-1){
googleAd = "Google/CPC ";
// alert(googleAd);
//referrer = paidCampaign; < original code but trying the code on the bottom>
referrer = googleAd;
// alert(referrer);
}
if (paidCampaign.indexOf(bingAd)>- 1 || paidCampaign.indexOf(justBing) >-1){
bingAd = "Bing/CPC ";
//alert(bingAd);
referrer = bingAd ;
}
return referrer;
// alert("The paid ad is: " + googleAd);
}
function directSource(referrer){
var directVistor = document.referrer;
if(directVistor ==="" || directVistor === null ){
referrer = "Direct";
//alert("Direct");
}
return referrer;
}
function display(referrer){
var displayURL = document.URL;
var referrer;
if(displayURL.indexOf("display") >- 1 || displayURL.indexOf("Display")>-1){
var returnDisplay = window.location.search.substring(1);
referrer = "Display: " + returnDisplay;
//alert(referrer);
return referrer;
}
}
// function urlSpilt(url){
// // return utm_source and utm_medium if iti has it.
// var url;
// var getURL = document.URL;
// //var testURL = "http://www.franciscoignacioquintana.com/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName";
// var getURL = getURL.split("utm_source");
// getURL = getURL[1].split("utm_source");
// url = getURL;
// return url;
// }
//http://www.currencies.co.uk/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName
function getQueryParam(par){
//var strURL = document.URL;#
var strURL = document.referrer;
var regParam = new RegExp("(?:\\?|&)" + par + "=([^&$]*)", "i");
var resExp = strURL.match(regParam);
if((typeof resExp == "object") && resExp && (resExp.length > 1)){
return resExp[1];
}
else{
return "";
}
}
//var hostname = window.location.hostname;
//var hostnameReturn = hostname.split("www.");
//var hostname2 = hostname.slice(4);