User Impersonation using Web API - dynamics-crm

How can I retrieve records behalf of another user.
Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name&$top=3").then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
console.log(result.entities[i]);
}
// perform additional operations on retrieved records
},
function (error) {
console.log(error.message);
// handle error conditions
}
);

I know we can do impersonation using XMLHttpRequest by passing MSCRMCallerID header. Not sure we can achieve the same in Xrm.WebApi.
This is my Prod code, doing some update/assign operation under Admin impersonation from a HTML webresource.
var entity = {};
entity["ownerid#odata.bind"] = "/systemusers(" + currentUserId + ")";
var req = new XMLHttpRequest();
req.open("PATCH", parent.Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/new_customentity(" + opptyid + ")", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("MSCRMCallerID", "0AFB2F7E-D323-E511-80F0-C4346BAC29F0"); //CRM Admin impersoantion
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204) {
//Success - No Return Data - Do Something
} else {
//Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(entity));
Update
Passing header is the only way and Xrm.WebApi cannot accept request headers.
Documentation says:
There are two ways you can impersonate a user, both of which are made possible by passing in a header with the corresponding user id.
Preferred: Impersonate a user based on their Azure Active Directory (AAD) object id by passing that value along with the header CallerObjectId.
Legacy: To impersonate a user based on their systemuserid you can leverage MSCRMCallerID with the corresponding guid value.

Related

How to find child references for a specific entity record?

I can only distinguish parent references based on the data from the entity record I have retrieved. The question is
how to list all child references for a specific entity record?
I have an account entity and I want to find all related child entities (contacts ... etc) using REST API.
Try using below code to retrieve related child entities for parent:
function RetrieveRelatedChildEntities() {
var url = Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.0/EntityDefinitions(LogicalName='account')?$select=LogicalName,DisplayCollectionName&$expand=ManyToManyRelationships,ManyToOneRelationships,OneToManyRelationships";
req.open("GET", url, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.OneToManyRelationships.length; i++) {
}
}
}
}
}

How to create Entity record with the predefined Id?

Is it possible to recreate the entity record with the predefined Id?
The purpose of this question is to figure out how to create the entity record with the id you have provided.
For example when I delete Account record with the id '00-00-02' it does not exist in MS Dynamics CRM anymore. So now I want to recreate this Account record using REST API with it`s old id ('00-00-02').
Can anyone suggest me how to do it (or it is not possible)?
D365 allows you to set the primary key Guid of an entity. Often when doing data migrations from one D365 org to another we'll push the id's across.
Here's an example of setting the accountId on a new account via the Web API. (Created in Jason Lattimer's CRMRESTBuilder):
var entity = {};
entity.accountid = "008A5AD9-59B7-43BB-BA41-BA59CB5B4769";
entity.name = "Acme Inc.";
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204) {
var uri = this.getResponseHeader("OData-EntityId");
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(uri);
var newEntityId = matches[1];
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(entity));
Here is an OrganizationService version of the same code:
Entity account = new Entity("account");
account.Id = new Guid("008A5AD9-59B7-43BB-BA41-BA59CB5B4769");
account["name"] = "Acme Inc.";
service.Create(account);

how to get label of optionset in crm

I'm using D-CRM 2016 I'm trying to get a label of optionset in client-side (js) ,I get an error and can't find a reason why:
thats my code:
SDK.Metadata.RetrieveAttribute("myEntity", "myFieldName", null, false,
function (result) {
alert(result);
for (var i = 0; i < result.OptionSet.Options.length; i++) {
var loopText = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;
var loopValue = result.OptionSet.Options[i].Value;
}
},
function (error) { }
,false);
My error:
Uncaught TypeError: _Context(...).getServerUrl is not a function
at _getUrl (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:451)
at Object.RetrieveAttribute (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:323)
at <anonymous>:1:14
at Mscrm.CommandHandler.$Ce_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.$Ag_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.handleCommand (JsProvider.ashx:8)
at Mscrm.CommandBarData.executeCommand (JsProvider.ashx:8)
at Mscrm.ButtonControl.executeCommand (ribbon.js:1)
at Mscrm.ButtonControl.click (ribbon.js:1)
at Mscrm.CommandBar.onClickHandler (ribbon.js:1)
Anytime you're attempting to do client side rest calls, I always recommend Jason Lattimer's CRM Rest Builder (https://github.com/jlattimer/CRMRESTBuilder) You can access the text labels using the "Formatted Values" option.
The principal problem is with the SDK you are using. I can't really debug it for you.
However, here's a working sample that is returning the label and the value. There a header (Prefer) you can add to tell the api to return the label as well:
var odataEndPoint = Xrm.Page.context.getClientUrl() + '/api/data/v8.2/';
function GetDomainName(entityId) {
var result = null;
var req = new XMLHttpRequest();
req.open("GET", odataEndPoint + 'systemusers(' + TrimGuid(entityId) + ')/', false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
if (this.status == 200) {
if (this.response) {
result = JSON.parse(this.response);
}
}
else {
var parsed = JSON.parse(this.response);
console.error(parsed.error.message)
}
}
};
req.send();
return result;
};

Logic Apps- Unable to Set To and From fields For Dynamics 365 Email Entity

I am trying to create an email entity in Dynamics 365 using Logic Apps.
I am filling in the From and Recipient fields but the when I check the record created in Dynamics, I see that these fields are empty. I know that to and from fields are activity parties in Dynamics 365 email entity. Do we have a sample json which I can use in Logic Apps to create an Email Activity with To and From fields set?
As per the product group its not available right now to create and set to and from fields of email entity from logic apps
Sorry, answering without access to laptop. And this is not straightforward answer for you. But just a start to build your own request Json object.
Replace your record guids in below snippet & execute this in browser console or CRM js web resource. Take the JSON.stringify(email) at the end & that's what you're looking for.
var serverURL = Xrm.Page.context.getClientUrl();
var email = {};
email["subject"] = "Email Subject";
email["description"] = "email body description";
email["regardingobjectid_contact#odata.bind"] = "/contacts(guid1)";
//activityparty collection
var activityparties = [];
//from party
var from = {};
from["partyid_systemuser#odata.bind"] = "/systemusers(guid2)";
from["participationtypemask"] = 1;
//to party
var to = {};
to["partyid_contact#odata.bind"] = "/contacts(guid3)";
to["participationtypemask"] = 2;
activityparties.push(to);
activityparties.push(from);
//set to and from to email
email["email_activity_parties"] = activityparties;
var req = new XMLHttpRequest();
req.open("POST", serverURL + "/api/data/v8.0/emails", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Prefer", "return=representation");
req.onreadystatechange = function() {
if (this.readyState == 4 /* complete */ ) {
req.onreadystatechange = null;
if (this.status == 201) {
var emailUri = this.getResponseHeader("OData-EntityId");
}
else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(JSON.stringify(email));
}
In case if you need it, Code referred from this blog.

Verify current user authenticity from Cloud Code

I have a Parse Cloud Code function that returns some user private data given a user id. How can I verify that the given user id is indeed the id of the currently logged in user?
I ended up creating this function and calling it from my other Cloud Code functions.
// Verifies that the given user is an authentic user
// Parameters: user
// Return: Promise
function verifyUserAuthenticity(user)
{
var promise = new Parse.Promise();
var userSessionToken = user.getSessionToken();
var query = new Parse.Query(Parse.Session);
query.equalTo("user", user);
query.equalTo("sessionToken", userSessionToken);
query.find({ useMasterKey: true }).then(
function(results)
{
if(results.length > 0)
{
promise.resolve("User is authentic.");
}
else
{
promise.reject("User is not authentic.");
}
},
function(error)
{
promise.reject("Error verifying user's authenticity: " + error);
}
);
return promise;
}

Resources