public static void DeleteRecords(IOrganizationService service,EntityCollection results)
{
ExecuteMultipleRequest multipleRequest = BulkDeleteRequest();
foreach (var entityRef in results.Entities)
{
DeleteRequest deleteRequest = new DeleteRequest()
{
Target = new EntityReference(entityRef.LogicalName, entityRef.Id)
};
multipleRequest.Requests.Add(deleteRequest);
if (multipleRequest.Requests.Count == 1000)
{
BulkDeleteResponse(service, multipleRequest);
multipleRequest = BulkDeleteRequest();
}
}
if (multipleRequest.Requests.Count <= 1000)
BulkDeleteResponse(service, multipleRequest);
}
public static ExecuteMultipleRequest BulkDeleteRequest()
{
var multipleRequest = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
return multipleRequest;
// Execute all the requests in the request collection using a single web method call.
}
public static void BulkDeleteResponse(IOrganizationService service, ExecuteMultipleRequest multipleRequest)
{
ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
How to use FetchXml in CRM Web API
Here I am going to show how to use FetxhXML query to get the results from CRM Web API. below example shows how to get logged in user Security roles.
function getRoles(token) {
var req = new XMLHttpRequest();
var fetch = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’true’>” +
“<entity name=’role’>” +
“<attribute name=’name’ />” +
“<attribute name=’businessunitid’ />” +
“<attribute name=’roleid’ />” +
“<order attribute=’name’ descending=’false’ />” +
“<link-entity name=’systemuserroles’ from=’roleid’ to=’roleid’ visible=’false’ intersect=’true’>” +
“<link-entity name=’systemuser’ from=’systemuserid’ to=’systemuserid’ alias=’ad’>” +
“<filter type=’and’>” +
“<condition attribute=’systemuserid’ operator=’eq-userid’ />” +
“</filter>” +
“</link-entity>” +
“</link-entity>” +
“</entity>” +
“</fetch>”;
$.ajax({
type: “GET”,
contentType: “application/json; charset=utf-8”,
datatype: “json”,
url: Xrm.Page.context.getClientUrl() + “/api/data/v8.2/roles?fetchXml=” + fetch,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader(“OData-MaxVersion”, “4.0”);
XMLHttpRequest.setRequestHeader(“OData-Version”, “4.0”);
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
XMLHttpRequest.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
},
async: false,
success: function (data, textStatus, xhr) {
var results = data;
for (var i = 0; i < results.value.length; i++) {
var roleid = results.value[i][“roleid”];
var roleName = results.value[i][“name”];
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + ” ” + errorThrown);
}
});
}
Plug-in Images (Pre vs Post)
Plugins in Dynamics CRM, allow you to register images against the steps of a plugin assembly. Images are a way to pass the image of the record that is currently being worked upon prior or after the action has been performed. In general it could be said, it is the image of the record as is available in the SQL backend.
Two types of Images are supported, Pre-Image and Post Image.
In case of Pre-image, you get the image of the record as is stored in the SQL database before the CRM Platform action has been performed.
Post Image, returns the image of the record after the CRM Platform action has been performed.
It is there important to understand when the images would be available and what state of the record would be returned in these images.
Say you were to register a “Pre-Image” for a plugin registered in Pre-Create Stage. We just mentioned above, that the image is a copy of the record as is stored in the SQL backend. Since this is the create stage and the record has not even been created as yet, there is no record in the SQL backend that can be returned in the Pre-Image and hence any call for the image would fail with the above error message.
The following table explains the Pre-Image Availability
Stage | Create | Update | Delete |
PRE | NO | Yes | Yes |
Post | Yes | Yes | Yes |
The following table explains the Post-Image Availability
Stage | Create | Update | Delete |
PRE | NO | NO | NO |
Post | Yes | Yes | NO |
Update records using Execute Multiple Request
public void ReadCustomerData(IOrganizationService service)
{
int count = 0;
ExecuteMultipleRequest multipleRequest = BulkUpdateRequest();
QueryExpression query = new QueryExpression()
{
ColumnSet = new ColumnSet(new string[] { "new_start", "new_end", "new_expected" }),
EntityName = "new_reporte"
};
ConditionExpression cond = new ConditionExpression("new_startdate", ConditionOperator.Null);
FilterExpression filter = new FilterExpression();
filter.AddCondition(cond);
query.Criteria = filter;
EntityCollection results = service.RetrieveMultiple(query);
if (results != null && results.Entities.Count > 0)
{
foreach (Entity res in results.Entities)
{
Entity ent = new Entity()
{
LogicalName = res.LogicalName,
Id = res.Id
};
string satart = res.Attributes.Contains("new_start") ? res.GetAttributeValue("new_start") : "";
string end = res.Attributes.Contains("new_end") ? res.GetAttributeValue("new_end") : "";
string estimatedDate = res.Attributes.Contains("new_expected") ? res.GetAttributeValue("new_expected") : "";
if (!string.IsNullOrEmpty(satart))
{
var list = satart.Split(' ');
if (list != null && list.Length > 0)
{
DateTime dt = DateTime.ParseExact(list[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
ent["new_startdate"] = Convert.ToDateTime(dt);
}
}
if (!string.IsNullOrEmpty(end))
{
var list = end.Split(' ');
if (list != null && list.Length > 0)
{
DateTime dt = DateTime.ParseExact(list[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
ent["new_enddate"] = Convert.ToDateTime(dt);
}
}
if (!string.IsNullOrEmpty(estimatedDate))
{
var list = estimatedDate.Split(' ');
if (list != null && list.Length > 0)
{
DateTime dt = DateTime.ParseExact(list[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
ent["new_expected"] = Convert.ToDateTime(dt);
}
}
UpdateRequest updateRequest = new UpdateRequest()
{
Target = ent
};
multipleRequest.Requests.Add(updateRequest);
count++;
Console.WriteLine(count);
if (count == 1000)
{
BulkCreateResponse(service, multipleRequest);
count = 0;
multipleRequest = BulkUpdateRequest();
}
}
if (multipleRequest.Requests.Count < 1000)
BulkCreateResponse(service, multipleRequest);
Console.WriteLine(count);
// Console.ReadLine();
}
}
public ExecuteMultipleRequest BulkUpdateRequest()
{
var multipleRequest = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
return multipleRequest;
// Execute all the requests in the request collection using a single web method call.
}
public void BulkUpdateResponse(IOrganizationService service, ExecuteMultipleRequest multipleRequest)
{
ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
Send Email request In MS CRM
Entity email = new Entity(“email”);
Entity fromParty = new Entity(“activityparty”);
Entity toParty = new Entity(“activityparty”);
fromParty[“partyid”] = new EntityReference(“systemuser”, userId);
toParty[“partyid”] = new EntityReference(“account”, accountId);
email[“from”] = new Entity[] { fromParty };
email[“to”] = new Entity[] { toParty };
email[“subject”] = “email subject – ” + DateTime.Now.ToString();
email[“description”] = “email description”;
email[“regardingobjectid”] = new EntityReference(“account”,accountId);
Guid emailId = service.Create(email);
if (emailId != Guid.Empty)
{
SendEmailRequest sendEmailreq = new SendEmailRequest()
{
EmailId = emailId,
TrackingToken = “”,
IssueSend = true
};
SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
}
Convert Numeric to Word
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function convertNumericsToWords() {
var Number = Xrm.Page.getAttribute("new_amount").getValue().toFixed(2);
var stringValue = conversion(Number);
if (stringValue != null && stringValue != "") {
stringValue = stringValue +" "+ "cents";
Xrm.Page.getAttribute("new_numerictoword").setValue(stringValue);
Xrm.Page.getAttribute("new_numerictoword").setSubmitMode("always");
}
}
function conversion(s) {
// debugger;
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1)
x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) { // 0235
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'hundred ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk)
str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var count=0;
var y = s.length;
str += 'dollars and'+" ";
for (var i = x + 1; i < y; i++)
{
if(count==0)
str += tw[n[i]-2] + ' ';
else
if(n[i]!=0)
str += dg[n[i]];
count++;
}
}
return str.replace(/\s+/g, ' ');
}
Share record in Dynamics CRM
GrantAccessRequest grantAccessRequest = new GrantAccessRequest()
{
PrincipalAccess = new PrincipalAccess
{
AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.AssignAccess, // here i am giving Read , write and Assign access to selected team
Principal = new EntityReference(“team”, New Guid(“A07C0CD1-D8C5-E511-810D-3863BB347D90”))
},
Target = new EntityReference(“account”, new Guid(“B07D0CD1-D8C5-E511-810D-3863BB347D90”))
};
service.Execute(grantAccessRequest);
How to assign record to other user in CRM using C#
AssignRequest assignRequest = new AssignRequest()
{
Assignee = new EntityReference
{
LogicalName = ent.LogicalName, //User or Team logical name
Id = ent.Id // User Id or Team Id
},
Target = new EntityReference(“account”, new Guid(“B07D0CD1-D8C5-E511-810D-3863BB347D90”))
};
service.Execute(assignRequest);
OAuth Authentication (with out using ADAL) to Dynamics 365 using Azure Apps
Here I am going to show with out using ADAL(active directory authentication library) how to get the authentication token and how to connect to CRM from a standalone HTML Page using the web-api.
I am not going into detail on how to register an APP in azure and give it access to Dynamics CRM. There are so many wonderful blogs which explains in detail. For App registration follow this blog powerobjects.com
Change “oauth2AllowImplicitFlow” property value from “false” to “True” and save it, in Azure app Manifest
Once you’re done with Azure app registration use below code to get the OAuth token.
$.support.cors = true;
var microsoftTokenUrl = "https://login.microsoftonline.com/4060bfe9-7199-xxxxxxx-xxxxxxx/oauth2/token"; //Add your endpoint URL
var clientId = "xxxxxxxx-9715-xxxx-xxxx-3a1fac0cc5fe"; // Add your app ID
var clientSecret = "xxxxxxMJTQmtu4V73cRyduZ6vS40AlkAtSxxxxxxx";//Add your Secret Key
var resource = "https://xxxxxxx.crm5.dynamics.com";//Add your CRM Url
var grantType = "client_credentials";
function GetAuthroisationToken() {
var token=null;
$.ajax({
url: microsoftTokenUrl,
type: "POST",
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: "json",
async: false,
data: {
'resource': resource,
'client_id': clientId,
'client_secret': clientSecret,
'grant_type': grantType
},
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, xhr) {
token= data.access_token;
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}});
return token;
}
Here is the sample code to create lead in CRM (Design your HTML as your wish)
var entity = {};
entity.subject = $("#subject").val();
entity.firstname = $("#fname").val();
entity.lastname = $("#lname").val();
var salutation = $("#title option:selected").val();
entity.address1_postalcode = $("#postalcode").val();
entity.address1_city = $("#city").val();
entity.address1_stateorprovince = $("#state").val();
entity.address1_country = $("#country").val();
entity.address1_line1 = $("#address").val();
entity.emailaddress1 = $("#email").val();
entity.telephone1 = $("#phone").val();
entity.companyname = $("#company").val();
entity.jobtitle = $("#function").val();
entity.leadsourcecode = 8;
var token = GetAuthroisationToken();
if(token!=null)
webApi_Create("leads", entity, false,token);
function webApi_Create(entityName,entityObject,isAsync,token)
{
var newEntityId = null;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: resource + "/api/data/v8.2/" + entityName,
data: JSON.stringify(entityObject),
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("Authorization", "Bearer " + token);
},
async: isAsync,
success: function (data, textStatus, xhr) {
var uri = xhr.getResponseHeader("OData-EntityId");
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(uri);
newEntityId = matches[1];
if (newEntityId !== null)
alert("Record Created!");
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
return newEntityId;
}
CRM Client Side Scripts
Get the value from a CRM field
var value = Xrm.Page.getAttribute(“CRMFieldLogicalName”).getValue();
Set the value of a CRM field
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setValue(“New Value”);
Get the value from a CRM OptionSet field
var value = Xrm.Page.getAttribute(“CRMOptionSetLogicalName”).getValue();
Get the text from a CRM OptionSet field
var text = Xrm.Page.getAttribute(“CRMOptionSetLogicalName”).getText();
Set the value of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMOptionSetLogicalName”).setValue(“1″); // OptionSet Value
Get the selected text of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMOptionSetLogicalName”).getSelectedOption().text;
Get the selected value of a CRM OptionSet field
Xrm.Page.getAttribute(“CRMOptionSetLogicalName”).getSelectedOption().value;
Get the text and value of a CRM Lookup field
var lookupObject = Xrm.Page.getAttribute(“CRMLookupLogicalName”).getValue();
lookupObject[0].name; // text of lookup
lookupObject[0].id; // Guid of lookup
Set the value of a CRM Lookup field
var lookupData = new Array();
var lookupItem = new Object();
lookupItem.id = “4A2A54CB-349C-E111-8D26-1CC1DEE8DA78″; // Guid of record
lookupItem.name = “New Contact”; // Entity record name
lookupItem.entityType = “EntityLogicalName”;
lookupData[0] = lookupItem;
Xrm.Page.getAttribute(“CRMLookupLogicalName”).setValue(lookupData);
Disable CRM field
Xrm.Page.ui.controls.get(“CRMFieldLogicalName”).setDisabled(true);
Hide CRM field
Xrm.Page.ui.controls.get(“CRMFieldLogicalName”).setVisible(false);
Hide a Tab in CRM
Xrm.Page.ui.tabs.get(“tabName”).setVisible(false);
Hide a Section in CRM
var tab = Xrm.Page.ui.tabs.get(“tabName”);
tab.sections.get(“sectionName”).setVisible(false);
Set the Requirement level in CRM
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setRequiredLevel(“recommended”);
Set Focus on a field in CRM
Xrm.Page.ui.controls.get(“CRMFieldLogicalName”).setFocus(true);
Cancelling Onsave Event in CRM
event.returnValue = false;
return false;
Check IsDirty in CRM field
var isDirty = Xrm.Page.getAttribute(“CRMFieldLogicalName”).getIsDirty();
alert(isDirty); // returns true if the field is dirty
Check IsDirty for all the fields in CRM
var isDirty = Xrm.Page.data.entity.getIsDirty();
alert(isDirty); // returns true if any of the field is dirty in the entire form.
Force Submit a read only field in CRM
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setSubmitMode(“always”);
Preventing an attribute to be saved in CRM form
Xrm.Page.getAttribute(“CRMFieldLogicalName”).setSubmitMode(“never”);
Get Unique Organization Name in CRM
Xrm.Page.context.getOrgUniqueName();
Get Server url in CRM
Xrm.Page.context.getServerUrl();
Get the record Id in CRM
Xrm.Page.data.entity.getId();
Get the User Id in CRM
Xrm.Page.context.getUserId();
Get the Entity Logical Name in CRM
Xrm.Page.data.entity.getEntityName();
Get the UserRole Id’s in CRM
var userRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < userRoles.length; i++)
{
var userRole = userRoles[i]; // returns the Role Id
}
Get the Form Type in CRM
Xrm.Page.ui.getFormType();
Form Types in CRM
Is the user creating a new record?
Xrm.Page.ui.getFormType() == 1
Is the user updating an existing record?
Xrm.Page.ui.getFormType() == 2
Is the user unable to update this record?
Xrm.Page.ui.getFormType() == 3
Is this record deactivated?
Xrm.Page.ui.getFormType() == 4
Is the user using the Quick Create form?
Xrm.Page.ui.getFormType() == 5
Is the user using the Bulk Edit form?
Xrm.Page.ui.getFormType() == “6″
Save a record in CRM
Xrm.Page.data.entity.save(); // for saving a record
Xrm.Page.data.entity.save(“saveandclose”); // for save and close
Xrm.Page.data.entity.save(“saveandnew”); // for save and new
Close the form in CRM
Xrm.Page.ui.close();
Open EntityForm in CRM
Xrm.Utility.openEntityForm(“opportunity”, Xrm.Page.data.entity.getId());
Get all Active process Stages
var ProcessStages = Xrm.Page.data.process.getActiveProcess().getStages().getAll();
Set Business process Satage
Xrm.Page.getAttribute(“stageid”).setValue(ProcessStages[0].getId());