Archive
Checking whether user part of team using jscript CRM 2011
Hi,
We can verify whether the User is part of particular Team using jscript.
Below is the jscript function
function isUserPartOfTeam(userId, teamId) {
var oDataEndpointUrl = serverUrl + “/XRMServices/2011/OrganizationData.svc/”;
oDataEndpointUrl += “TeamMembershipSet?$select=BusinessUnitId&$filter=TeamId eq guid'” + teamId + “‘ SystemUserId eq guid'” + userId + “‘”;
var service = GetRequestObject();
if (service != null) {
service.open(“GET”, oDataEndpointUrl, false);
service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);
service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);
service.send(null);
var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;
if (requestResults != null && requestResults.results.length > 0) {
return true;
}
}
return false;
}
How do I call this method :-
- Pass User Id & Team Id to the function.
- Function returns true/false
var userId={User GUID};
var teamId={Team GUID};
var flag= isUserPartOfTeam(userId, teamId);
🙂
Retrieve multiple records synchronously using OData & JQuery in CRM 2011
Hi,
Below is the Jscript function to retrieve multiple records synchronously using OData & JQuery.
function retrieveMultipleSync(odataSetName, select, filter) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;
if (select) {
odataUri += “$select=” + select ;
}
if (filter) {
odataUri += “&” + “$filter=” + filter;
}
var service = GetRequestObject();
if (service != null) {
service.open(“GET”, odataUri, false);
service.setRequestHeader(“X-Requested-Width”, “XMLHttpRequest”);
service.setRequestHeader(“Accept”, “application/json,text/javascript, */*”);
service.send(null);
var requestResults = eval(‘(‘ + service.responseText + ‘)’).d;
return requestResults;
}
}
function GetRequestObject() {
var req = false;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
return req;
}
- Copy & Paste above method to a new .jscript file
- Replace double quotes(“) symbols with your keyboard double quotes
- Add the new .jscript file as web resource to CRM application
- Add “Jquery” & json” helper classes as web resources
How do I call this method :-
- In my sample below, I will show you how to read “Contacts” of an “Account”
function retrieveContactsByAccountId(accountId) {
// Pass ‘Contact’ set name since we are reading Contacts
var oDataSetName = “ContactSet”;
// Column names of ‘Contact’ (Pass * to read all columns)
var columns = “FirstName,LastName”;
// Prepare filter
var filter = “AccountId/Id eq guid'” + accountId + “‘”;
var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
if (requestResults != null) {
if (requestResults.results != null && requestResults.results.length > 0) {
for (var indxContacts = 0; indxContacts < requestResults.results.length; indxContacts++) {
var contact = requestResults.results[indxContacts];
if (contact.FirstName) {
alert(“Contact’s First Name – ” + contact.FirstName);
}
}
}
}
else {
alert(“Error while retrieving; Error – ” + service.responseText);
}
}
Get OData URI conventions from here
🙂
Limitation of OData End Point – Setting Activity Parties
Hi,
In one of my requirement, I had to create an “Appointment” record programmatically using Jscript by populating field ‘required attendees’ (i.e., ActivityParty) to it.
I followed below steps to complete the requirement
- Created the “Appointment” record first
- Added 2 contacts as “Required Attendees” to Appointment, for which I used below code and called it 2 times since I need to create 2 activity parties
var activityParty = new Object();
activityParty.PartyId = {
Id: participentId,
LogicalName: participentLogicalName
};
activityParty.ActivityId = {
Id: activityId,
LogicalName: “appointment”
};
activityParty.ParticipationTypeMask = { Value: 5 }; //5 = Required Attendees
var activityParty = createRecord (activityParty, “ActivityPartySet”);
Issue I faced :-
- The problem I faced was,
- only one “Contact” added as “Required Attendees” (i.e., Only 1 Activity Party is creating) instead of 2
- When I debug the script and DB, I observed that 1st activity party is getting created initially but once after the 2nd activity party created, the first one is getting deleted
Reason & Workaround :-
- Later I came to know that, this is the limitation of OData end point.
- As a workaround, I registered a Plugin on post create of “Appointment” and added “Activity Parties”
🙂
Delete record synchronously using OData and JScript in CRM 2011
Hi,
Below is the script to delete record synchronously
function deleteRecordSync(recordId, odataSetName) {
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var deleteRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
deleteRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid'” + recordId + “‘)”, false);
deleteRecordReq.setRequestHeader(“Accept”, “application/json”);
deleteRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
deleteRecordReq.setRequestHeader(“X-HTTP-Method”, “DELETE“);
deleteRecordReq.send(null);
}
How do I call this method :-
- To delete an “Account”
- Pass account GUID and OData Set name (i.e.,AccountSet)
Var accountId=”{Account GUID}”;
deleteRecordSync (accountId , “AccountSet”);
🙂
Update record synchronously using OData and JScript in CRM 2011
Hi,
Below is the Jscript function to update record synchronously using OData and Jscript
function updateRecordSync(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var updateRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid'” + id + “‘)”, false);
updateRecordReq.setRequestHeader(“Accept”, “application/json”);
updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE“);
updateRecordReq.send(jsonEntity);
}
How do I call this method :-
- Create a new .jscript file (i.e., “account.js”)
- Copy & Paste above code
- Add “account.js” as a webresource in CRM
- Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
- Get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
- To update an “Account”
- Pass “Account” object and GUID and OData Set name (i.e.,AccountSet)
Var accountId=”{Account GUID}”;
var account = new Object();
account.Name = “Rajeev Pentyala”;
updateRecordSync (accountId ,account, “AccountSet”);
🙂
Create record synchronously using OData and JScript in CRM 2011
Hi,
Below is the Jscript function to create record synchronously using OData and Jscript
function createRecordSync(entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var createRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
createRecordReq.open(‘POST’, ODataPath + “/” + odataSetName, false);
createRecordReq.setRequestHeader(“Accept”, “application/json”);
createRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
createRecordReq.send(jsonEntity);
var newRecord = JSON.parse(createRecordReq.responseText).d;
return newRecord;
}
How do I call this method :-
- Create a new .jscript file (i.e., “account.js”)
- Copy & Paste above code
- Add “account.js” as a webresource in CRM
- Add “Json2.js” & “jquery1.4.1.min.js” helper script files as webresources
- Get the helper files from CRM 2011 SDk under path “\sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts”
- To create an “Account”
- Pass “Account” object, OData Set name (i.e.,AccountSet)
var account = new Object();
account.Name = “Rajeev Pentyala”;
var createdAccount = createRecordSync(account, “AccountSet”);
if (createdAccount) {
alert(“New Account Created !!!; Id – “+createdAccount.AccountId);
}
🙂
Retrieve multiple records using OData & JQuery in CRM 2011
Hi,
Below are the Jscript functions to retrieve multiple records using OData & JQuery.
function retrieveMultiple(odataSetName, select, filter, successCallback) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;
if (select) {
odataUri += “$select=” + select + “&”;
}
if (filter) {
odataUri += “$filter=” + filter;
}
//Asynchronous AJAX function to Retrieve CRM records using OData
$.ajax({
type: “GET”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
if (data && data.d && data.d.results) {
successCallback(data.d.results, textStatus, XmlHttpRequest);
}
else if (data && data.d) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
else {
successCallback(data, textStatus, XmlHttpRequest);
}
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert(“Error while retrieval ; Error – ” + XmlHttpRequest.responseText);
}
}
});
}
function readRecordsOnSuccess(data, textStatus, XmlHttpRequest) {
// Loop through the retrieved records
for (var indx = 0; indx < data.length; indx++) {
alert(“Name – ” + data[indx].name);
}
}
- Copy & Paste above methods to a new .jscript file
- Replace double quotes(“) symbols with your keyboard double quotes
- Add the new .jscript file as web resource to CRM application
- Add “Jquery” & json” helper classes as web resources
How do I call this method :-
- In my sample below, I will show you how to read “Contacts” for an “Account”
function retrieveContactsByAccountId() {
// Pass ‘Contact’ set name since we are reading Contacts
var oDataSetName = “ContactSet”;
// Column names of ‘Contact’ (Pass * to read all columns)
var columns = “FirstName,LastName”;
// Read Account Guid
var accountId = Xrm.Page.data.entity.getId()
// Prepare filter
var filter = “AccountId/Id eq guid'” + accountId + “‘”;
retrieveMultiple(oDataSetName, columns, filter, readRecordsOnSuccess);
}
Note :- Import “ODataQueryDesigner” solution to prepare the Filters easily.
Hope it helps 🙂
Reading option set using JScript in CRM 2011
Hi,
Below is the Jscript functions to read “Option set” and get the option text by option value.
In this approach I have 3 methods and details are below
- getOptionSet() – Returns optionset object
- Parameters
- Entity Name (Entity logical name)
- Attribute Name (i.e., Option set field name)
- retrieveAsIfPublished (True/False)
- Parameters
- getTextByValue() – Returns option set text by passing value
- Parameters
- optionSet (i.e., Option set object got from above method)
- attributeValue (Option set field value)
- Parameters
- getSOAPWrapper – Helper method
function getOptionSet (entityLogicalName, attributeLogicalName, retrieveAsIfPublished) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODataPath = serverUrl + “/XRMServices/2011/Organization.svc/web”;
var MetadataId = “00000000-0000-0000-0000-000000000000”;
var request = “<Execute xmlns=\”http://schemas.microsoft.com/xrm/2011/Contracts/Services\” xmlns:i=\”http://www.w3.org/2001/XMLSchema-instance\“>”;
request += “<request i:type=\”a:RetrieveAttributeRequest\” xmlns:a=\”http://schemas.microsoft.com/xrm/2011/Contracts\“>”;
request += “<a:Parameters xmlns:b=\”http://schemas.datacontract.org/2004/07/System.Collections.Generic\“>”;
request += “<a:KeyValuePairOfstringanyType>”;
request += “<b:key>EntityLogicalName</b:key>”;
request += “<b:value i:type=\”c:string\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + entityLogicalName + “</b:value>”;
request += “</a:KeyValuePairOfstringanyType>”;
request += “<a:KeyValuePairOfstringanyType>”;
request += “<b:key>MetadataId</b:key>”;
request += “<b:value i:type=\”ser:guid\” xmlns:ser=\”http://schemas.microsoft.com/2003/10/Serialization/\“>” + MetadataId + “</b:value>”;
request += “</a:KeyValuePairOfstringanyType>”;
request += “<a:KeyValuePairOfstringanyType>”;
request += “<b:key>RetrieveAsIfPublished</b:key>”;
request += “<b:value i:type=\”c:boolean\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + retrieveAsIfPublished + “</b:value>”;
request += “</a:KeyValuePairOfstringanyType>”;
request += “<a:KeyValuePairOfstringanyType>”;
request += “<b:key>LogicalName</b:key>”;
request += “<b:value i:type=\”c:string\” xmlns:c=\”http://www.w3.org/2001/XMLSchema\“>” + attributeLogicalName + “</b:value>”;
request += “</a:KeyValuePairOfstringanyType>”;
request += “</a:Parameters>”;
request += “<a:RequestId i:nil=\”true\” /><a:RequestName>RetrieveAttribute</a:RequestName></request>”;
request += “</Execute>”;
request = _getSOAPWrapper(request);
var req = new XMLHttpRequest();
req.open(“POST”, ODataPath, false);
req.setRequestHeader(“Accept”, “application/xml, text/xml, */*”);
req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);
req.setRequestHeader(“SOAPAction”, “http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute“);
req.send(request);
if (req.responseXML != null) {
var attributeData = req.responseXML.selectSingleNode(“//b:value”);
if (attributeData != null) {
var attributeType = attributeData.selectSingleNode(“c:AttributeType”).text;
switch (attributeType) {
case “Picklist”:
return attributeData;
break;
default:
break;
}
}
}
}
function _getSOAPWrapper(request) {
var SOAP = “<soapenv:Envelope xmlns:soapenv=\”http://schemas.xmlsoap.org/soap/envelope/\“><soapenv:Body>”;
SOAP += request;
SOAP += “</soapenv:Body></soapenv:Envelope>”;
return SOAP;
}
function getTextByValue(optionSet, attributeValue) {
var options = optionSet.selectSingleNode(“c:OptionSet//c:Options”);
for (var i = 0; i < options.childNodes.length; i++) {
var value = options.childNodes[i].selectSingleNode(“c:Value”).text;
if (value == attributeValue) {
var text = options.childNodes[i].selectSingleNode(“c:Label”).selectSingleNode(“a:UserLocalizedLabel”).selectSingleNode(“a:Label”).text;
return text;
}
}
}
How do I call this method –
- Copy the above functions and create a Jscript webresource in CRM
- In below example I am reading “Address Type” option set of entity “Contact”
// Get option set object by passing params
// Entity name, Optionset field name, true/false
var optionSet = getOptionSet(“contact”, “address1_addresstypecode”, true);
if (optionSet) {
// Read option text of value ‘2’
var optionValue = 2;
var optionText = getTextByValue(optionSet, optionValue);
alert(“Text of option value – ” + optionValue + ” is -” + optionText);
// Read option text of value ‘10001’
optionValue = 10001;
optionText = getTextByValue(optionSet, optionValue);
alert(“Text of option value – ” + optionValue + ” is -” + optionText);
}
else {
alert(“Invalid Option set”);
}
Note :- *** If you copy the code please replace double quotes(“) symbols with your keyboard double quotes ***
Hope it helps 🙂