Common Java-script
//Constants
var START_END_DATE_VALIDATION_ERROR_MESSAGE = "End Date Should be Greater Than The Start Date";
var START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID = "enddateshouldbegreaterthanthestartdateid";
var Endpoints = {
veriable: null,
getFunction: function () { alert(''); },
}
//****************************************************************//
//********************* Variables & Msgs *************************//
//****************************************************************//
var commonErrorHandler = function (e) {
alert(e.message);
};
var myPopupWindow = ''; var intervalID = null;
//****************************************************************//
//********************* XRM Functions *************************//
//****************************************************************//
function SaveEntityWithoutSave() {
Xrm.Page.data.entity.save();
}
function MakePageReadOnly() {
var controls = Xrm.Page.ui.controls.get();
for (var i in controls) {
var control = controls[i];
if (!control.getDisabled()) {
control.setDisabled(true);
}
}
}
function refereshWithSaveIgnoreMandatory(successCallbak, callbackValue) {
var arrMandsAttrs = [];
Xrm.Page.data.entity.attributes.forEach(function (attr) {
if (attr.getRequiredLevel() == "required") {
arrMandsAttrs.push(attr.getName());
makeNonManadatory(attr.getName());
}
});
Xrm.Page.data.refresh(true).then(function () {
if (arrMandsAttrs.length > 0) {
for (var i = 0; i < arrMandsAttrs.length; i++)
{ makeManadatory(arrMandsAttrs[i]); }
arrMandsAttrs = [];
}
if (successCallbak != null) { if (callbackValue != null) { successCallbak(callbackValue); } else { successCallbak(); } }
});
}
function fullReLoadPageWithHeader() {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Page.data.setFormDirty(false);
Xrm.Utility.openEntityForm(getEntityName(), getRecordId());
}
function fullReLoadEntityPage(entityName, entityId) {
var formType = Xrm.Page.ui.getFormType();
if (formType != 1 && formType != 0 && formType != "1" && formType != "0") {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Page.data.setFormDirty(false);
var windowOptions = {
openInNewWindow: false
};
Xrm.Utility.openEntityForm(entityName, entityId, null, windowOptions);
}
}
function refereshWithoutSave() {
Xrm.Page.data.refresh(false);
}
function refereshIgnoreSave() {
Xrm.Page.data.setFormDirty(false);
Xrm.Page.data.refresh(false);
}
function refereshWithoutSave(successCallback) {
Xrm.Page.data.refresh(false).then(successCallback, commonErrorHandler);
}
function refereshIgnoreSaveWithCallback(successCallback) {
Xrm.Page.data.setFormDirty(false);
Xrm.Page.data.refresh(false).then(successCallback, commonErrorHandler);
}
function refreshWithSave() {
Xrm.Page.data.refresh(true);
}
function refreshWithSave(successCallback, errorCallback) {
Xrm.Page.data.refresh(true).then(successCallback, errorCallback);;
}
function disable(attributeName) {
Xrm.Page.getControl(attributeName).setDisabled(true);
}
function enable(attributeName) {
Xrm.Page.getControl(attributeName).setDisabled(false);
}
function getAttributeValue(attributeName) {
return Xrm.Page.getAttribute(attributeName).getValue();
}
function setAttributeValue(attributeName, value) {
try {
Xrm.Page.getAttribute(attributeName).setValue(value);
Xrm.Page.getAttribute(attributeName).setSubmitMode("always");
} catch (e) {
alert("Error occured while setting value for " + attributeName + ". Possible reason it is not found.");
throw e;
}
}
function setAttributeFocus(attributeName) {
try {
Xrm.Page.getControl(attributeName).setFocus();
} catch (e) {
alert("Error occured while setting value for " + attributeName + ". Possible reason it is not found.");
throw e;
}
}
function setAlwaysSubmitMode(attributeName) {
Xrm.Page.getAttribute(attributeName).setSubmitMode("always");
}
function setDirtySubmitMode(attributeName) {
Xrm.Page.getAttribute(attributeName).setSubmitMode("dirty");
}
function makeNonManadatory(attributeName) {
Xrm.Page.getAttribute(attributeName).setRequiredLevel("none");
}
function makeManadatory(attributeName) {
Xrm.Page.getAttribute(attributeName).setRequiredLevel("required");
}
function hide(attributeName) {
Xrm.Page.getControl(attributeName).setVisible(false);
Xrm.Page.getAttribute(attributeName).setSubmitMode("never");
}
function show(attributeName) {
Xrm.Page.getControl(attributeName).setVisible(true);
Xrm.Page.getAttribute(attributeName).setSubmitMode("dirty");
}
function hideSection(tabName, sectionName) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(false);
}
function showSection(tabName, sectionName) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(true);
}
function hideTab(tabName) {
Xrm.Page.ui.tabs.get(tabName).setVisible(false);
}
function showTab(tabName) {
Xrm.Page.ui.tabs.get(tabName).setVisible(true);
}
function showIframeDelayed(objIframe) {
setTimeout(function () {
objIframe.setVisible(true);
}, 100);
}
function showIframe(objIframe) {
objIframe.setVisible(true);
}
function hideIframe(objIframe) {
objIframe.setVisible(false);
}
function getLookupValueName(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
return lookUpObjectValue[0].name;
}
}
return null;
}
function getLookupValueId(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
return lookUpObjectValue[0].id;
}
}
return null;
}
function setLookupValueName(attributeName, id, logicalName, name, isOverwrite) {
var objAttr = Xrm.Page.getAttribute(attributeName);
if (objAttr != null) {
if (isOverwrite || objAttr.getValue() == null) {
var objLookup = [{ id: id, entityType: logicalName, name: name }];
objAttr.setValue(objLookup);
}
}
}
function getLookupText(lookupSchemaName) {
var lookupRecordName = "";
var lookupObj = Xrm.Page.getAttribute(lookupSchemaName); //Check for Lookup Object
if (lookupObj != null) {
var lookupObjValue = lookupObj.getValue();//Check for Lookup Value
if (lookupObjValue != null) {
//var lookupEntityType = lookupObjValue[0].entityType, //To get EntityName
//lookupRecordGuid = lookupObjValue[0].id, // To get record GUID
lookupRecordName = lookupObjValue[0].name; //To get record Name
}
}
return lookupRecordName;
}
function getOptionSetId(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
return lookUpObjectValue;
}
return null;
}
function fireChangeEvent(attributeName) {
Xrm.Page.getAttribute(attributeName).fireOnChange();
}
//****************************************************************//
//********************* XRM Util Functions *************************//
//****************************************************************//
function openWebResource(name) {
Xrm.Utility.openWebResource(name);
}
//****************************************************************//
//********************* Data Functions *************************//
//****************************************************************//
function getOrganizationName() {
return Xrm.Page.context.getOrgUniqueName();
}
function getUserId() {
var userId = Xrm.Page.context.getUserId();
return userId;
}
function CleanGuid(id) {
return id.replace("{", "").replace("}", "");
}
function getIFrame(name) {
return Xrm.Page.ui.controls.get(name);
}
function BindIFrame(iframeName, iframeURL) {
var formType = Xrm.Page.ui.getFormType();
var customerHierarchyIFrame = getIFrame(iframeName);
if (formType != 1 && formType != 0 && formType != "1" && formType != "0") {
if (customerHierarchyIFrame != null) { customerHierarchyIFrame.setSrc(iframeURL); }
}
else {
if (customerHierarchyIFrame != null) { customerHierarchyIFrame.setSrc("about:blank"); }
}
}
function getLookUpFiledName(attributeName) {
if (Xrm.Page.getAttribute(attributeName) != null && Xrm.Page.getAttribute(attributeName) != undefined)
return Xrm.Page.getAttribute(attributeName).getValue()[0].name;
else
return "";
}
function isNotNullAttribute(attributeName) {
return (Xrm.Page.getAttribute(attributeName) != null || Xrm.Page.getAttribute(attributeName) != undefined);
}
function getAttrValue(attributeName) {
debugger;
if (Xrm.Page.getAttribute(attributeName) != null || Xrm.Page.getAttribute(attributeName) != undefined) {
if (Xrm.Page.getAttribute(attributeName).getValue() != null || Xrm.Page.getAttribute(attributeName).getValue() != undefined)
return getAttributeValue(attributeName);
else
return "";
}
else
return "";
}
function getLookupName(attributeName) {
var lookUp = new Array;
if (isNotNullAttribute(attributeName)) {
lookUp = getAttributeValue(attributeName);
if (lookUp != null || lookUp != undefined)
return lookUp[0].name;
else
return "";
}
else
return "";
}
function getRecordId() {
return Xrm.Page.data.entity.getId();
}
function getEntityName() {
return Xrm.Page.data.entity.getEntityName();
}
function GetDateString(objDate) {
return objDate.getFullYear() + "-" + (objDate.getMonth() + 1) + "-" + objDate.getDate();
}
function hasJsonResult(result) {
var IS_JSON = false;
try {
var json = $.parseJSON(result);
IS_JSON = true;
}
catch (err) {
IS_JSON = false;
}
return IS_JSON;
}
function getClientUrl() {
return Xrm.Page.context.getClientUrl();
}
function isNewFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 1);
}
function isEditFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 2);
}
function isDisabledFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 4);
}
function redirectToEntityInWindow(entityName, Id) {
debugger;
var url = getClientUrl() + "/main.aspx?";
url += "pagetype=entityrecord";
url += "&etn=" + entityName;
url += "&id=" + Id;
window.location.href = url;
}
function getEntityStatus() {
var statecode = getAttributeValue("statecode");
return Number(statecode);
}
function getEntityStatusReson() {
var statuscode = getAttributeValue("statuscode");
return Number(statuscode);
}
//****************************************************************//
//********************* Ajax Function *************************//
//****************************************************************//
function retriveJSON(relativeUrl, successFunction) {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: relativeUrl,
cache: false,
dataType: 'json',
success: successFunction,
async: false,
error: commonErrorHandler
});
}
function retriveJSON(relativeUrl, successFunction, errorFunction) {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: relativeUrl,
cache: false,
dataType: 'json',
success: successFunction,
async: false,
error: errorFunction
});
}
//****************************************************************//
//********************* RestService Function *************************//
//****************************************************************//
function CallCustomWebService(SOAPAction, inputXML, ProxyURL, ReplyTo) {
var xml = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>";
if (ReplyTo != "") {
xml = xml + "<Header>" +
"<ReplyTo xmlns='http://www.w3.org/2005/08/addressing'>" +
"<Address>" + ReplyTo + "</Address> " +
"</ReplyTo> " +
"</Header>";
}
xml = xml + "<Body>" +
inputXML +
"</Body>" +
"</Envelope>";
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.6.0");
xmlHttp.open("POST", ProxyURL, false);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttp.setRequestHeader("Content-Length", xml.length);
xmlHttp.setRequestHeader("SOAPAction", SOAPAction);
xmlHttp.send(xml);
var response = xmlHttp.responseXML;
return response;
}
function CallCustomWebServiceAsynch(SOAPAction, inputXML, ProxyURL) {
var xml = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<Body>" +
inputXML +
"</Body>" +
"</Envelope>";
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp.open("POST", ProxyURL, true);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttp.setRequestHeader("Content-Length", xml.length);
xmlHttp.setRequestHeader("SOAPAction", SOAPAction);
xmlHttp.onreadystatechange = function () {
ParseResult(xmlHttp);
};
xmlHttp.send(xml);
}
function ParseResult(XmlRequest) {
if (XmlRequest.readyState == 4) {
if (XmlRequest.status == 200) {
debugger;
return XmlRequest.responseXML;
}
else {
alert("Request Fail");
}
}
}
function getDataByFilter(entity, filterUrl, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + filterUrl;
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getData(entity, PrimaryIdName, uniqueID, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?&";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + PrimaryIdName + " eq guid'" + uniqueID + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getDataById(entity, PrimaryIdName, uniqueID, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + PrimaryIdName + " eq guid'" + uniqueID + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getDataByName(entity, Name, Value, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + Name + " eq '" + Value + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function GetOptionSetLabel(entityName, fieldName, OptionValue) {
var xml = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soapenv:Body>" +
"<Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
"<request i:type='a:RetrieveAttributeRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
"<a:Parameters xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>EntityLogicalName</b:key>" +
"<b:value i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + entityName + "</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>MetadataId</b:key>" +
"<b:value i:type='ser:guid' xmlns:ser='http://schemas.microsoft.com/2003/10/Serialization/'>00000000-0000-0000-0000-000000000000</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>RetrieveAsIfPublished</b:key>" +
"<b:value i:type='c:boolean' xmlns:c='http://www.w3.org/2001/XMLSchema'>true</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>LogicalName</b:key>" +
"<b:value i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + fieldName + "</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil='true' />" +
"<a:RequestName>RetrieveAttribute</a:RequestName>" +
"</request>" +
"</Execute>" +
"</soapenv:Body>" +
"</soapenv:Envelope>"
req = new ActiveXObject("Msxml2.XMLHTTP");
req.open("POST", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", false);
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("Content-Length", xml.length);
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(xml);
var result = req.responseXML;
var OptionSet = result.getElementsByTagName("c:OptionSet");
var Options = OptionSet[0].getElementsByTagName("c:Options");
var OptionMetadata = OptionSet[0].getElementsByTagName("c:OptionMetadata");
var Text = '';
var Value = '';
for (var i = 0; i < OptionMetadata.length; i++) {
Value = OptionMetadata[i].getElementsByTagName("c:Value")[0].text;
if (Value == OptionValue) {
var Text = OptionMetadata[i].getElementsByTagName("a:Label")[0].text;
return Text;
}
}
return Text;
}
//****************************************************************//
//********************* Model Popup Function *************************//
//****************************************************************//
function openPopupWindowWithOnCloseCallback(url, name, width, height, onCloseCallback) {
//Remove special characters from name
name = name.replace(/\/|\-|\./gi, "");
var left = (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);
//Remove whitespaces from name
var whitespace = new RegExp("\\s", "g");
name = name.replace(whitespace, "");
//If it is already open
debugger;
if (myPopupWindow != null && !myPopupWindow.closed && myPopupWindow.location) {
myPopupWindow.location.href = encodeUrl(url);
}
else
{
myPopupWindow = window.open(encodeUrl(url), name, "location=no, scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
if (!myPopupWindow.opener) myPopupWindow.opener = self;
if (onCloseCallback != null) {
intervalID = window.setInterval(function () { checkWindow(onCloseCallback); }, 500);
}
}
//if (window.focus) { myPopupWindow.focus() }
}
function checkWindow(closeCallback) {
if (myPopupWindow && intervalID && myPopupWindow.closed) {
OpenDiaglog_CreateOpportunityOnFalseFisibility();
window.clearInterval(intervalID);
myPopupWindow = null; intervalID = null;
closeCallback();
}
}
function openPopupWindow(url, name, width, height) {
//Remove special characters from name
name = name.replace(/\/|\-|\./gi, "");
var left = (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);
//Remove whitespaces from name
var whitespace = new RegExp("\\s", "g");
name = name.replace(whitespace, "");
if (myPopupWindow != null && !myPopupWindow.closed && myPopupWindow.location) {
myPopupWindow.location.href = encodeUrl(url);
}
else {
myPopupWindow = window.open(encodeUrl(url), name, "location=no, scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
if (!myPopupWindow.opener) myPopupWindow.opener = self;
}
if (window.focus) { myPopupWindow.focus() }
}
function encodeUrl(url) {
if (url.indexOf("?") > 0) {
encodedParams = "?";
parts = url.split("?");
params = parts[1].split("&");
for (i = 0; i < params.length; i++) {
if (i > 0) {
encodedParams += "&";
}
if (params[i].indexOf("=") > 0) //Avoid null values
{
p = params[i].split("=");
encodedParams += (p[0] + "=" + escape(encodeURI(p[1])));
}
else {
encodedParams += params[i];
}
}
url = parts[0] + encodedParams;
}
url = url.replace('%25', '%');
url = url.replace('%25', '%');
url = url.replace('%25', '%');
url = url.replace('%25', '%');
return url;
}
//****************************************************************//
//********************* XML Function *************************//
//****************************************************************//
function decode64(input) {
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return unescape(output);
}
///Purspose: get data by primary key of entity with linked records
///Param: entitySchemaName= schema name of entity
///Param: recordId= guid of the entity
///Param: attributes= string array of attributes to retrieve from the primary entity
///Param: linkedEntity= object array for linked records with attributes to get from linked entity
/// i.e. linkedEntity = [{ralationSchemaName:"",attributes:[""]}]
///Param: successCallback= callback function when data retrieved, if not passed, function will be synchronous
function RetrieveDataById(entitySchemaName, recordId, attributes, linkedEntity, successCallback) {
var strSelectPart = null, strExpandPart = null;
//prepare selection of attributes to be returned
if (attributes != null && attributes.length > 0) {
strSelectPart = "";
for (var i = 0; i < attributes.length; i++) {
strSelectPart += attributes[i] + ",";
}
}
//prepare selection of attributes to be returned form join entity
if (linkedEntity != null && linkedEntity.length > 0) {
strExpandPart = "";
for (var i = 0; i < linkedEntity.length; i++) {
strExpandPart += linkedEntity[i].ralationSchemaName + ",";
if (linkedEntity[i].attributes != null && linkedEntity[i].attributes.length > 0) {
if (strSelectPart == null) {
strSelectPart = "";
}
for (var j = 0; j < linkedEntity[i].attributes.length; j++) {
strSelectPart += linkedEntity[i].ralationSchemaName + "/" + linkedEntity[i].attributes[j] + ",";
}
}
}
}
if (strSelectPart != null && strSelectPart != "")
{ strSelectPart = strSelectPart.substring(0, strSelectPart.length - 1); }
if (strExpandPart != null && strExpandPart != "")
{ strExpandPart = strExpandPart.substring(0, strExpandPart.length - 1); }
if (entitySchemaName.indexOf("Set") < 0) {
entitySchemaName += entitySchemaName + "Set";
}
var isSsync = successCallback != null;
var dataObject = null;
XrmServiceToolkit.Rest.Retrieve(recordId, entitySchemaName, strSelectPart, strExpandPart, function (dataResult) {
if (isSsync) {
successCallback(dataResult);
}
else {
dataObject = dataResult;
}
}, function (errMsg) {
throw new errMsg;
}, isSsync);
return dataObject;
}
///Purspose: get data by primary key of entity with linked records
///Param: entitySchemaName= schema name of entity
///Param: attributes= string array of attributes to retrieve from the primary entity
///Param: successCallback= callback function when data retrieved, if not passed, function will be synchronous
function RetrieveMultiple(entitySchemaName, attributes, filterString, successCallback) {
var strSelectPart = null;
//prepare selection of attributes to be returned
if (attributes != null && attributes.length > 0) {
strSelectPart = "$select=";
for (var i = 0; i < attributes.length; i++) {
strSelectPart += attributes[i] + ",";
}
}
if (strSelectPart != null && strSelectPart != "")
{ strSelectPart = strSelectPart.substring(0, strSelectPart.length - 1); }
if (filterString != null && filterString != "")
{ strSelectPart = strSelectPart + "&$filter=" + filterString; }
if (entitySchemaName.indexOf("Set") < 0) {
entitySchemaName += entitySchemaName + "Set";
}
var isSsync = successCallback != null;
var dataArray = [];
XrmServiceToolkit.Rest.RetrieveMultiple(entitySchemaName, strSelectPart, function (dataResult) {
if (isSsync) {
successCallback(dataResult);
}
else {
dataArray = dataResult;
}
}, function (errMsg) {
throw new errMsg;
},
function () { }
, isSsync);
return dataArray;
}
///Purpose: to prepare linked entity object to be passed to retrieve data using oData query
function PrepareLinkedObject(ralationSchemaName, attributes) {
if (ralationSchemaName != null || ralationSchemaName != "") {
var objRelation = {};
objRelation.ralationSchemaName = ralationSchemaName;
objRelation.attributes = attributes;
return objRelation;
}
else { throw new Error("Relationship Schema name is not provided."); }
}
//**********************************************************//
//********************* Filter customerid based on segment ***********//
//********************* ***********//
function addFilterToShowContacts() {
var account_filter = "<filter type='and'>" +
"<condition attribute='accountid' operator='null' />" +
"</filter>";
Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "account");
}
// For showing only accounts.
function addFilterToShowAccounts() {
var account_filter = "<filter type='and'>" +
"<condition attribute='contactid' operator='null' />" +
"</filter>";
Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "contact");
}
function generateFetchXml(entityName, lstAttributes, lstConditionAttributes, lstConditionOperators, lstConditionValue, isCore) {
var strFetchXml = (isCore != null && isCore) ? "" : "<fetch>";
strFetchXml += "<entity name='" + entityName + "'>";
if (lstAttributes == null || lstAttributes.Count == 0) {
strFetchXml += "<all-attributes/>";
}
else {
for (var i = 0; i < lstAttributes.length; i++)
{ strFetchXml += "<attribute name='" + lstAttributes[i] + "'/>"; }
}
if (lstConditionAttributes != null && lstConditionOperators != null && lstConditionValue != null && lstConditionAttributes.length > 0 &&
lstConditionAttributes.length == lstConditionOperators.length && lstConditionValue.length == lstConditionAttributes.length) {
strFetchXml += "<filter>";
for (var i = 0; i < lstConditionAttributes.length; i++) {
if (lstConditionOperators[i] == "in" || lstConditionOperators[i] == "not-in") {
if (lstConditionValue[i] == null || !(Array.isArray(lstConditionValue[i]))) {
throw new Exception("Invalid details provided for conditions.");
}
else {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "'>";
for (var j = 0; j < lstConditionValue[i].length; j++) {
strFetchXml += "<value>" + lstConditionValue[i][j] + "</value>";
}
strFetchXml += "</condition>";
}
}
else if (lstConditionOperators[i] == "null" || lstConditionOperators[i] == "not-null") {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "'>";
}
else if (lstConditionValue[i] != null) {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "' value='" + lstConditionValue[i] + "'/>";
}
}
strFetchXml += "</filter>";
}
strFetchXml += "</entity>";
strFetchXml += (isCore != null && isCore) ? "" : "</fetch>";
return strFetchXml;
}
function preventSave(context) {
context.getEventArgs().preventDefault();
}
//This function validate the start date and end date the way end date cant be smaller than start date.
function StartEndDateValidation(fieldStartDate, fieldEndDate, onChangeFieldName) {
var startDate = Xrm.Page.getAttribute(fieldStartDate);
var endDate = Xrm.Page.getAttribute(fieldEndDate);
if (startDate != null && endDate != null && startDate.getValue() != null && endDate.getValue() != null) {
if (startDate.getValue() >= endDate.getValue())
Xrm.Page.getControl(onChangeFieldName).setNotification(START_END_DATE_VALIDATION_ERROR_MESSAGE, onChangeFieldName + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
else {
Xrm.Page.getControl(fieldStartDate).clearNotification(fieldStartDate + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
Xrm.Page.getControl(fieldEndDate).clearNotification(fieldEndDate + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
}
}
}
//Hide Html Element from page
function HideHtmlElement(htmlFieldName) {
if (document.getElementById(htmlFieldName) != null) {
document.getElementById(htmlFieldName).disabled = true;
document.getElementById(htmlFieldName).style.display = "none";
document.getElementById(htmlFieldName).style.visibility = "hidden";
}
}
//Display Notification next to field
function DisplayNotificationNextToField(fieldName, errorMessage) {
Xrm.Page.getControl(fieldName).clearNotification(fieldName + fieldName);
Xrm.Page.getControl(fieldName).setNotification(errorMessage, fieldName + fieldName);
}
//This function validate the date greater than current date
function ValidateDateGreaterThanCurrentDate(fieldName, errorMessage) {
Xrm.Page.getControl(fieldName).clearNotification(fieldName + fieldName);
var startDate = Xrm.Page.getAttribute(fieldName);
if (startDate != null && startDate.getValue() != null) {
if (startDate.getValue() < new Date()) {
Xrm.Page.getControl(fieldName).setNotification(errorMessage, fieldName + fieldName);
}
}
}
function doesControlHaveAttribute(control) {
var controlType = control.getControlType();
return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
// Set form read only
function SetFormReadOnly(onOff) {
//Xrm.Page.ui.controls.forEach(function (control, index) {
// if (doesControlHaveAttribute(control)) {
// control.setDisabled(onOff);
// }
//});
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
var control = Xrm.Page.getControl(attribute.getName());
if (control.getControlType() == controlType)
control.setDisabled(true);
});
}
function removeOptionSetValue(attributeName, value, index) {
var attrName = attributeName;
if (index != undefined && index != null) {
attrName = attrName + index;
index += 1;
}
else {
index = 1;
}
var attrControl = Xrm.Page.getControl(attrName);
if (attrControl != null) {
try {
attrControl.removeOption(value);
removeOptionSetValue(attributeName, value, index);
} catch (e) {
}
}
}
/*
User Management
*/
// In your new function, call the “UserHasTeam("<the team name exactly")” function
// sample usage, this is not part of the function:
function TestUserHasTeam() {
if (UserHasTeam('TestTeam1')) {
alert("I'm a member if the team!");
} else {
alert("I'm NOT a member of the team!");
}
}
// function starts here.
function UserHasTeam(teamName) {
///<summary>
/// Checks to see if the current user is a member of a team with the passed in name.
///</summary>
///<param name="teamName" type="String">
/// A String representing the name of the team to check if the user is a member of.
///</param>
if (teamName != null && teamName != "") {
// build endpoint URL
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
// query to get the teams that match the name
oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
var service = GetRequestObject();
if (service != null) {
// execute the request
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send(null);
// parse the results
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length > 0) {
var teamCounter;
// iterate through all of the matching teams, checking to see if the current user has a membership
for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
var team = requestResults.results[teamCounter];
var teamId = team.TeamId;
// get current user teams
var currentUserTeams = getUserTeams(teamId);
// Check whether current user teams matches the target team
if (currentUserTeams != null) {
for (var i = 0; i < currentUserTeams.length; i++) {
var userTeam = currentUserTeams[i];
// check to see if the team guid matches the user team membership id
if (GuidsAreEqual(userTeam.TeamId, teamId)) {
return true;
}
}
} else {
return false;
}
}
} else {
alert("Team with name '" + teamName + "' not found");
return false;
}
return false;
}
} else {
alert("No team name passed");
return false;
}
}
//Constants
var START_END_DATE_VALIDATION_ERROR_MESSAGE = "End Date Should be Greater Than The Start Date";
var START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID = "enddateshouldbegreaterthanthestartdateid";
var Endpoints = {
veriable: null,
getFunction: function () { alert(''); },
}
//****************************************************************//
//********************* Variables & Msgs *************************//
//****************************************************************//
var commonErrorHandler = function (e) {
alert(e.message);
};
var myPopupWindow = ''; var intervalID = null;
//****************************************************************//
//********************* XRM Functions *************************//
//****************************************************************//
function SaveEntityWithoutSave() {
Xrm.Page.data.entity.save();
}
function MakePageReadOnly() {
var controls = Xrm.Page.ui.controls.get();
for (var i in controls) {
var control = controls[i];
if (!control.getDisabled()) {
control.setDisabled(true);
}
}
}
function refereshWithSaveIgnoreMandatory(successCallbak, callbackValue) {
var arrMandsAttrs = [];
Xrm.Page.data.entity.attributes.forEach(function (attr) {
if (attr.getRequiredLevel() == "required") {
arrMandsAttrs.push(attr.getName());
makeNonManadatory(attr.getName());
}
});
Xrm.Page.data.refresh(true).then(function () {
if (arrMandsAttrs.length > 0) {
for (var i = 0; i < arrMandsAttrs.length; i++)
{ makeManadatory(arrMandsAttrs[i]); }
arrMandsAttrs = [];
}
if (successCallbak != null) { if (callbackValue != null) { successCallbak(callbackValue); } else { successCallbak(); } }
});
}
function fullReLoadPageWithHeader() {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Page.data.setFormDirty(false);
Xrm.Utility.openEntityForm(getEntityName(), getRecordId());
}
function fullReLoadEntityPage(entityName, entityId) {
var formType = Xrm.Page.ui.getFormType();
if (formType != 1 && formType != 0 && formType != "1" && formType != "0") {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Page.data.setFormDirty(false);
var windowOptions = {
openInNewWindow: false
};
Xrm.Utility.openEntityForm(entityName, entityId, null, windowOptions);
}
}
function refereshWithoutSave() {
Xrm.Page.data.refresh(false);
}
function refereshIgnoreSave() {
Xrm.Page.data.setFormDirty(false);
Xrm.Page.data.refresh(false);
}
function refereshWithoutSave(successCallback) {
Xrm.Page.data.refresh(false).then(successCallback, commonErrorHandler);
}
function refereshIgnoreSaveWithCallback(successCallback) {
Xrm.Page.data.setFormDirty(false);
Xrm.Page.data.refresh(false).then(successCallback, commonErrorHandler);
}
function refreshWithSave() {
Xrm.Page.data.refresh(true);
}
function refreshWithSave(successCallback, errorCallback) {
Xrm.Page.data.refresh(true).then(successCallback, errorCallback);;
}
function disable(attributeName) {
Xrm.Page.getControl(attributeName).setDisabled(true);
}
function enable(attributeName) {
Xrm.Page.getControl(attributeName).setDisabled(false);
}
function getAttributeValue(attributeName) {
return Xrm.Page.getAttribute(attributeName).getValue();
}
function setAttributeValue(attributeName, value) {
try {
Xrm.Page.getAttribute(attributeName).setValue(value);
Xrm.Page.getAttribute(attributeName).setSubmitMode("always");
} catch (e) {
alert("Error occured while setting value for " + attributeName + ". Possible reason it is not found.");
throw e;
}
}
function setAttributeFocus(attributeName) {
try {
Xrm.Page.getControl(attributeName).setFocus();
} catch (e) {
alert("Error occured while setting value for " + attributeName + ". Possible reason it is not found.");
throw e;
}
}
function setAlwaysSubmitMode(attributeName) {
Xrm.Page.getAttribute(attributeName).setSubmitMode("always");
}
function setDirtySubmitMode(attributeName) {
Xrm.Page.getAttribute(attributeName).setSubmitMode("dirty");
}
function makeNonManadatory(attributeName) {
Xrm.Page.getAttribute(attributeName).setRequiredLevel("none");
}
function makeManadatory(attributeName) {
Xrm.Page.getAttribute(attributeName).setRequiredLevel("required");
}
function hide(attributeName) {
Xrm.Page.getControl(attributeName).setVisible(false);
Xrm.Page.getAttribute(attributeName).setSubmitMode("never");
}
function show(attributeName) {
Xrm.Page.getControl(attributeName).setVisible(true);
Xrm.Page.getAttribute(attributeName).setSubmitMode("dirty");
}
function hideSection(tabName, sectionName) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(false);
}
function showSection(tabName, sectionName) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(true);
}
function hideTab(tabName) {
Xrm.Page.ui.tabs.get(tabName).setVisible(false);
}
function showTab(tabName) {
Xrm.Page.ui.tabs.get(tabName).setVisible(true);
}
function showIframeDelayed(objIframe) {
setTimeout(function () {
objIframe.setVisible(true);
}, 100);
}
function showIframe(objIframe) {
objIframe.setVisible(true);
}
function hideIframe(objIframe) {
objIframe.setVisible(false);
}
function getLookupValueName(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
return lookUpObjectValue[0].name;
}
}
return null;
}
function getLookupValueId(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
return lookUpObjectValue[0].id;
}
}
return null;
}
function setLookupValueName(attributeName, id, logicalName, name, isOverwrite) {
var objAttr = Xrm.Page.getAttribute(attributeName);
if (objAttr != null) {
if (isOverwrite || objAttr.getValue() == null) {
var objLookup = [{ id: id, entityType: logicalName, name: name }];
objAttr.setValue(objLookup);
}
}
}
function getLookupText(lookupSchemaName) {
var lookupRecordName = "";
var lookupObj = Xrm.Page.getAttribute(lookupSchemaName); //Check for Lookup Object
if (lookupObj != null) {
var lookupObjValue = lookupObj.getValue();//Check for Lookup Value
if (lookupObjValue != null) {
//var lookupEntityType = lookupObjValue[0].entityType, //To get EntityName
//lookupRecordGuid = lookupObjValue[0].id, // To get record GUID
lookupRecordName = lookupObjValue[0].name; //To get record Name
}
}
return lookupRecordName;
}
function getOptionSetId(attributeName) {
var lookupObject = Xrm.Page.getAttribute(attributeName);
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
return lookUpObjectValue;
}
return null;
}
function fireChangeEvent(attributeName) {
Xrm.Page.getAttribute(attributeName).fireOnChange();
}
//****************************************************************//
//********************* XRM Util Functions *************************//
//****************************************************************//
function openWebResource(name) {
Xrm.Utility.openWebResource(name);
}
//****************************************************************//
//********************* Data Functions *************************//
//****************************************************************//
function getOrganizationName() {
return Xrm.Page.context.getOrgUniqueName();
}
function getUserId() {
var userId = Xrm.Page.context.getUserId();
return userId;
}
function CleanGuid(id) {
return id.replace("{", "").replace("}", "");
}
function getIFrame(name) {
return Xrm.Page.ui.controls.get(name);
}
function BindIFrame(iframeName, iframeURL) {
var formType = Xrm.Page.ui.getFormType();
var customerHierarchyIFrame = getIFrame(iframeName);
if (formType != 1 && formType != 0 && formType != "1" && formType != "0") {
if (customerHierarchyIFrame != null) { customerHierarchyIFrame.setSrc(iframeURL); }
}
else {
if (customerHierarchyIFrame != null) { customerHierarchyIFrame.setSrc("about:blank"); }
}
}
function getLookUpFiledName(attributeName) {
if (Xrm.Page.getAttribute(attributeName) != null && Xrm.Page.getAttribute(attributeName) != undefined)
return Xrm.Page.getAttribute(attributeName).getValue()[0].name;
else
return "";
}
function isNotNullAttribute(attributeName) {
return (Xrm.Page.getAttribute(attributeName) != null || Xrm.Page.getAttribute(attributeName) != undefined);
}
function getAttrValue(attributeName) {
debugger;
if (Xrm.Page.getAttribute(attributeName) != null || Xrm.Page.getAttribute(attributeName) != undefined) {
if (Xrm.Page.getAttribute(attributeName).getValue() != null || Xrm.Page.getAttribute(attributeName).getValue() != undefined)
return getAttributeValue(attributeName);
else
return "";
}
else
return "";
}
function getLookupName(attributeName) {
var lookUp = new Array;
if (isNotNullAttribute(attributeName)) {
lookUp = getAttributeValue(attributeName);
if (lookUp != null || lookUp != undefined)
return lookUp[0].name;
else
return "";
}
else
return "";
}
function getRecordId() {
return Xrm.Page.data.entity.getId();
}
function getEntityName() {
return Xrm.Page.data.entity.getEntityName();
}
function GetDateString(objDate) {
return objDate.getFullYear() + "-" + (objDate.getMonth() + 1) + "-" + objDate.getDate();
}
function hasJsonResult(result) {
var IS_JSON = false;
try {
var json = $.parseJSON(result);
IS_JSON = true;
}
catch (err) {
IS_JSON = false;
}
return IS_JSON;
}
function getClientUrl() {
return Xrm.Page.context.getClientUrl();
}
function isNewFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 1);
}
function isEditFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 2);
}
function isDisabledFormMode() {
var formType = Xrm.Page.ui.getFormType();
return (formType == 4);
}
function redirectToEntityInWindow(entityName, Id) {
debugger;
var url = getClientUrl() + "/main.aspx?";
url += "pagetype=entityrecord";
url += "&etn=" + entityName;
url += "&id=" + Id;
window.location.href = url;
}
function getEntityStatus() {
var statecode = getAttributeValue("statecode");
return Number(statecode);
}
function getEntityStatusReson() {
var statuscode = getAttributeValue("statuscode");
return Number(statuscode);
}
//****************************************************************//
//********************* Ajax Function *************************//
//****************************************************************//
function retriveJSON(relativeUrl, successFunction) {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: relativeUrl,
cache: false,
dataType: 'json',
success: successFunction,
async: false,
error: commonErrorHandler
});
}
function retriveJSON(relativeUrl, successFunction, errorFunction) {
$.ajax({
type: 'GET',
contentType: 'application/json',
url: relativeUrl,
cache: false,
dataType: 'json',
success: successFunction,
async: false,
error: errorFunction
});
}
//****************************************************************//
//********************* RestService Function *************************//
//****************************************************************//
function CallCustomWebService(SOAPAction, inputXML, ProxyURL, ReplyTo) {
var xml = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>";
if (ReplyTo != "") {
xml = xml + "<Header>" +
"<ReplyTo xmlns='http://www.w3.org/2005/08/addressing'>" +
"<Address>" + ReplyTo + "</Address> " +
"</ReplyTo> " +
"</Header>";
}
xml = xml + "<Body>" +
inputXML +
"</Body>" +
"</Envelope>";
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.6.0");
xmlHttp.open("POST", ProxyURL, false);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttp.setRequestHeader("Content-Length", xml.length);
xmlHttp.setRequestHeader("SOAPAction", SOAPAction);
xmlHttp.send(xml);
var response = xmlHttp.responseXML;
return response;
}
function CallCustomWebServiceAsynch(SOAPAction, inputXML, ProxyURL) {
var xml = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<Body>" +
inputXML +
"</Body>" +
"</Envelope>";
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp.open("POST", ProxyURL, true);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttp.setRequestHeader("Content-Length", xml.length);
xmlHttp.setRequestHeader("SOAPAction", SOAPAction);
xmlHttp.onreadystatechange = function () {
ParseResult(xmlHttp);
};
xmlHttp.send(xml);
}
function ParseResult(XmlRequest) {
if (XmlRequest.readyState == 4) {
if (XmlRequest.status == 200) {
debugger;
return XmlRequest.responseXML;
}
else {
alert("Request Fail");
}
}
}
function getDataByFilter(entity, filterUrl, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + filterUrl;
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getData(entity, PrimaryIdName, uniqueID, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?&";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + PrimaryIdName + " eq guid'" + uniqueID + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getDataById(entity, PrimaryIdName, uniqueID, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + PrimaryIdName + " eq guid'" + uniqueID + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function getDataByName(entity, Name, Value, attributes) {
var resultData = null;
var Url = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = Url + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += entity + "Set?";
oDataEndpointUrl += "$select=" + attributes + "&$filter=" + Name + " eq '" + Value + "'";
$.ajax({
type: "GET",
url: oDataEndpointUrl,
//data: jsonAccount,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function result(data) {
resultData = data.d.results;
},
async: false,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
if (resultData != null && resultData.length > 0)
return resultData;
else
return null;
}
function GetOptionSetLabel(entityName, fieldName, OptionValue) {
var xml = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soapenv:Body>" +
"<Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
"<request i:type='a:RetrieveAttributeRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
"<a:Parameters xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>EntityLogicalName</b:key>" +
"<b:value i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + entityName + "</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>MetadataId</b:key>" +
"<b:value i:type='ser:guid' xmlns:ser='http://schemas.microsoft.com/2003/10/Serialization/'>00000000-0000-0000-0000-000000000000</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>RetrieveAsIfPublished</b:key>" +
"<b:value i:type='c:boolean' xmlns:c='http://www.w3.org/2001/XMLSchema'>true</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>LogicalName</b:key>" +
"<b:value i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + fieldName + "</b:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil='true' />" +
"<a:RequestName>RetrieveAttribute</a:RequestName>" +
"</request>" +
"</Execute>" +
"</soapenv:Body>" +
"</soapenv:Envelope>"
req = new ActiveXObject("Msxml2.XMLHTTP");
req.open("POST", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", false);
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("Content-Length", xml.length);
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(xml);
var result = req.responseXML;
var OptionSet = result.getElementsByTagName("c:OptionSet");
var Options = OptionSet[0].getElementsByTagName("c:Options");
var OptionMetadata = OptionSet[0].getElementsByTagName("c:OptionMetadata");
var Text = '';
var Value = '';
for (var i = 0; i < OptionMetadata.length; i++) {
Value = OptionMetadata[i].getElementsByTagName("c:Value")[0].text;
if (Value == OptionValue) {
var Text = OptionMetadata[i].getElementsByTagName("a:Label")[0].text;
return Text;
}
}
return Text;
}
//****************************************************************//
//********************* Model Popup Function *************************//
//****************************************************************//
function openPopupWindowWithOnCloseCallback(url, name, width, height, onCloseCallback) {
//Remove special characters from name
name = name.replace(/\/|\-|\./gi, "");
var left = (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);
//Remove whitespaces from name
var whitespace = new RegExp("\\s", "g");
name = name.replace(whitespace, "");
//If it is already open
debugger;
if (myPopupWindow != null && !myPopupWindow.closed && myPopupWindow.location) {
myPopupWindow.location.href = encodeUrl(url);
}
else
{
myPopupWindow = window.open(encodeUrl(url), name, "location=no, scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
if (!myPopupWindow.opener) myPopupWindow.opener = self;
if (onCloseCallback != null) {
intervalID = window.setInterval(function () { checkWindow(onCloseCallback); }, 500);
}
}
//if (window.focus) { myPopupWindow.focus() }
}
function checkWindow(closeCallback) {
if (myPopupWindow && intervalID && myPopupWindow.closed) {
OpenDiaglog_CreateOpportunityOnFalseFisibility();
window.clearInterval(intervalID);
myPopupWindow = null; intervalID = null;
closeCallback();
}
}
function openPopupWindow(url, name, width, height) {
//Remove special characters from name
name = name.replace(/\/|\-|\./gi, "");
var left = (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);
//Remove whitespaces from name
var whitespace = new RegExp("\\s", "g");
name = name.replace(whitespace, "");
if (myPopupWindow != null && !myPopupWindow.closed && myPopupWindow.location) {
myPopupWindow.location.href = encodeUrl(url);
}
else {
myPopupWindow = window.open(encodeUrl(url), name, "location=no, scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
if (!myPopupWindow.opener) myPopupWindow.opener = self;
}
if (window.focus) { myPopupWindow.focus() }
}
function encodeUrl(url) {
if (url.indexOf("?") > 0) {
encodedParams = "?";
parts = url.split("?");
params = parts[1].split("&");
for (i = 0; i < params.length; i++) {
if (i > 0) {
encodedParams += "&";
}
if (params[i].indexOf("=") > 0) //Avoid null values
{
p = params[i].split("=");
encodedParams += (p[0] + "=" + escape(encodeURI(p[1])));
}
else {
encodedParams += params[i];
}
}
url = parts[0] + encodedParams;
}
url = url.replace('%25', '%');
url = url.replace('%25', '%');
url = url.replace('%25', '%');
url = url.replace('%25', '%');
return url;
}
//****************************************************************//
//********************* XML Function *************************//
//****************************************************************//
function decode64(input) {
var keyStr = "ABCDEFGHIJKLMNOP" +
"QRSTUVWXYZabcdef" +
"ghijklmnopqrstuv" +
"wxyz0123456789+/" +
"=";
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return unescape(output);
}
///Purspose: get data by primary key of entity with linked records
///Param: entitySchemaName= schema name of entity
///Param: recordId= guid of the entity
///Param: attributes= string array of attributes to retrieve from the primary entity
///Param: linkedEntity= object array for linked records with attributes to get from linked entity
/// i.e. linkedEntity = [{ralationSchemaName:"",attributes:[""]}]
///Param: successCallback= callback function when data retrieved, if not passed, function will be synchronous
function RetrieveDataById(entitySchemaName, recordId, attributes, linkedEntity, successCallback) {
var strSelectPart = null, strExpandPart = null;
//prepare selection of attributes to be returned
if (attributes != null && attributes.length > 0) {
strSelectPart = "";
for (var i = 0; i < attributes.length; i++) {
strSelectPart += attributes[i] + ",";
}
}
//prepare selection of attributes to be returned form join entity
if (linkedEntity != null && linkedEntity.length > 0) {
strExpandPart = "";
for (var i = 0; i < linkedEntity.length; i++) {
strExpandPart += linkedEntity[i].ralationSchemaName + ",";
if (linkedEntity[i].attributes != null && linkedEntity[i].attributes.length > 0) {
if (strSelectPart == null) {
strSelectPart = "";
}
for (var j = 0; j < linkedEntity[i].attributes.length; j++) {
strSelectPart += linkedEntity[i].ralationSchemaName + "/" + linkedEntity[i].attributes[j] + ",";
}
}
}
}
if (strSelectPart != null && strSelectPart != "")
{ strSelectPart = strSelectPart.substring(0, strSelectPart.length - 1); }
if (strExpandPart != null && strExpandPart != "")
{ strExpandPart = strExpandPart.substring(0, strExpandPart.length - 1); }
if (entitySchemaName.indexOf("Set") < 0) {
entitySchemaName += entitySchemaName + "Set";
}
var isSsync = successCallback != null;
var dataObject = null;
XrmServiceToolkit.Rest.Retrieve(recordId, entitySchemaName, strSelectPart, strExpandPart, function (dataResult) {
if (isSsync) {
successCallback(dataResult);
}
else {
dataObject = dataResult;
}
}, function (errMsg) {
throw new errMsg;
}, isSsync);
return dataObject;
}
///Purspose: get data by primary key of entity with linked records
///Param: entitySchemaName= schema name of entity
///Param: attributes= string array of attributes to retrieve from the primary entity
///Param: successCallback= callback function when data retrieved, if not passed, function will be synchronous
function RetrieveMultiple(entitySchemaName, attributes, filterString, successCallback) {
var strSelectPart = null;
//prepare selection of attributes to be returned
if (attributes != null && attributes.length > 0) {
strSelectPart = "$select=";
for (var i = 0; i < attributes.length; i++) {
strSelectPart += attributes[i] + ",";
}
}
if (strSelectPart != null && strSelectPart != "")
{ strSelectPart = strSelectPart.substring(0, strSelectPart.length - 1); }
if (filterString != null && filterString != "")
{ strSelectPart = strSelectPart + "&$filter=" + filterString; }
if (entitySchemaName.indexOf("Set") < 0) {
entitySchemaName += entitySchemaName + "Set";
}
var isSsync = successCallback != null;
var dataArray = [];
XrmServiceToolkit.Rest.RetrieveMultiple(entitySchemaName, strSelectPart, function (dataResult) {
if (isSsync) {
successCallback(dataResult);
}
else {
dataArray = dataResult;
}
}, function (errMsg) {
throw new errMsg;
},
function () { }
, isSsync);
return dataArray;
}
///Purpose: to prepare linked entity object to be passed to retrieve data using oData query
function PrepareLinkedObject(ralationSchemaName, attributes) {
if (ralationSchemaName != null || ralationSchemaName != "") {
var objRelation = {};
objRelation.ralationSchemaName = ralationSchemaName;
objRelation.attributes = attributes;
return objRelation;
}
else { throw new Error("Relationship Schema name is not provided."); }
}
//**********************************************************//
//********************* Filter customerid based on segment ***********//
//********************* ***********//
function addFilterToShowContacts() {
var account_filter = "<filter type='and'>" +
"<condition attribute='accountid' operator='null' />" +
"</filter>";
Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "account");
}
// For showing only accounts.
function addFilterToShowAccounts() {
var account_filter = "<filter type='and'>" +
"<condition attribute='contactid' operator='null' />" +
"</filter>";
Xrm.Page.getControl("customerid").addCustomFilter(account_filter, "contact");
}
function generateFetchXml(entityName, lstAttributes, lstConditionAttributes, lstConditionOperators, lstConditionValue, isCore) {
var strFetchXml = (isCore != null && isCore) ? "" : "<fetch>";
strFetchXml += "<entity name='" + entityName + "'>";
if (lstAttributes == null || lstAttributes.Count == 0) {
strFetchXml += "<all-attributes/>";
}
else {
for (var i = 0; i < lstAttributes.length; i++)
{ strFetchXml += "<attribute name='" + lstAttributes[i] + "'/>"; }
}
if (lstConditionAttributes != null && lstConditionOperators != null && lstConditionValue != null && lstConditionAttributes.length > 0 &&
lstConditionAttributes.length == lstConditionOperators.length && lstConditionValue.length == lstConditionAttributes.length) {
strFetchXml += "<filter>";
for (var i = 0; i < lstConditionAttributes.length; i++) {
if (lstConditionOperators[i] == "in" || lstConditionOperators[i] == "not-in") {
if (lstConditionValue[i] == null || !(Array.isArray(lstConditionValue[i]))) {
throw new Exception("Invalid details provided for conditions.");
}
else {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "'>";
for (var j = 0; j < lstConditionValue[i].length; j++) {
strFetchXml += "<value>" + lstConditionValue[i][j] + "</value>";
}
strFetchXml += "</condition>";
}
}
else if (lstConditionOperators[i] == "null" || lstConditionOperators[i] == "not-null") {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "'>";
}
else if (lstConditionValue[i] != null) {
strFetchXml += "<condition attribute='" + lstConditionAttributes[i] + "' operator='" + lstConditionOperators[i] + "' value='" + lstConditionValue[i] + "'/>";
}
}
strFetchXml += "</filter>";
}
strFetchXml += "</entity>";
strFetchXml += (isCore != null && isCore) ? "" : "</fetch>";
return strFetchXml;
}
function preventSave(context) {
context.getEventArgs().preventDefault();
}
//This function validate the start date and end date the way end date cant be smaller than start date.
function StartEndDateValidation(fieldStartDate, fieldEndDate, onChangeFieldName) {
var startDate = Xrm.Page.getAttribute(fieldStartDate);
var endDate = Xrm.Page.getAttribute(fieldEndDate);
if (startDate != null && endDate != null && startDate.getValue() != null && endDate.getValue() != null) {
if (startDate.getValue() >= endDate.getValue())
Xrm.Page.getControl(onChangeFieldName).setNotification(START_END_DATE_VALIDATION_ERROR_MESSAGE, onChangeFieldName + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
else {
Xrm.Page.getControl(fieldStartDate).clearNotification(fieldStartDate + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
Xrm.Page.getControl(fieldEndDate).clearNotification(fieldEndDate + START_END_DATE_VALIDATION_ERROR_MESSAGE_UNIQUEID);
}
}
}
//Hide Html Element from page
function HideHtmlElement(htmlFieldName) {
if (document.getElementById(htmlFieldName) != null) {
document.getElementById(htmlFieldName).disabled = true;
document.getElementById(htmlFieldName).style.display = "none";
document.getElementById(htmlFieldName).style.visibility = "hidden";
}
}
//Display Notification next to field
function DisplayNotificationNextToField(fieldName, errorMessage) {
Xrm.Page.getControl(fieldName).clearNotification(fieldName + fieldName);
Xrm.Page.getControl(fieldName).setNotification(errorMessage, fieldName + fieldName);
}
//This function validate the date greater than current date
function ValidateDateGreaterThanCurrentDate(fieldName, errorMessage) {
Xrm.Page.getControl(fieldName).clearNotification(fieldName + fieldName);
var startDate = Xrm.Page.getAttribute(fieldName);
if (startDate != null && startDate.getValue() != null) {
if (startDate.getValue() < new Date()) {
Xrm.Page.getControl(fieldName).setNotification(errorMessage, fieldName + fieldName);
}
}
}
function doesControlHaveAttribute(control) {
var controlType = control.getControlType();
return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
// Set form read only
function SetFormReadOnly(onOff) {
//Xrm.Page.ui.controls.forEach(function (control, index) {
// if (doesControlHaveAttribute(control)) {
// control.setDisabled(onOff);
// }
//});
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
var control = Xrm.Page.getControl(attribute.getName());
if (control.getControlType() == controlType)
control.setDisabled(true);
});
}
function removeOptionSetValue(attributeName, value, index) {
var attrName = attributeName;
if (index != undefined && index != null) {
attrName = attrName + index;
index += 1;
}
else {
index = 1;
}
var attrControl = Xrm.Page.getControl(attrName);
if (attrControl != null) {
try {
attrControl.removeOption(value);
removeOptionSetValue(attributeName, value, index);
} catch (e) {
}
}
}
/*
User Management
*/
// In your new function, call the “UserHasTeam("<the team name exactly")” function
// sample usage, this is not part of the function:
function TestUserHasTeam() {
if (UserHasTeam('TestTeam1')) {
alert("I'm a member if the team!");
} else {
alert("I'm NOT a member of the team!");
}
}
// function starts here.
function UserHasTeam(teamName) {
///<summary>
/// Checks to see if the current user is a member of a team with the passed in name.
///</summary>
///<param name="teamName" type="String">
/// A String representing the name of the team to check if the user is a member of.
///</param>
if (teamName != null && teamName != "") {
// build endpoint URL
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
// query to get the teams that match the name
oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
var service = GetRequestObject();
if (service != null) {
// execute the request
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send(null);
// parse the results
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length > 0) {
var teamCounter;
// iterate through all of the matching teams, checking to see if the current user has a membership
for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
var team = requestResults.results[teamCounter];
var teamId = team.TeamId;
// get current user teams
var currentUserTeams = getUserTeams(teamId);
// Check whether current user teams matches the target team
if (currentUserTeams != null) {
for (var i = 0; i < currentUserTeams.length; i++) {
var userTeam = currentUserTeams[i];
// check to see if the team guid matches the user team membership id
if (GuidsAreEqual(userTeam.TeamId, teamId)) {
return true;
}
}
} else {
return false;
}
}
} else {
alert("Team with name '" + teamName + "' not found");
return false;
}
return false;
}
} else {
alert("No team name passed");
return false;
}
}
No comments:
Post a Comment