Get sales order detail Dynamics web Microsoft 365 - dynamics-crm

I need to call the api from Java web to Dynamics 365 online web of Microsoft. I can acquire the access token. But I don't know how to call api to fetch a sales order detail.
I read the document from Microsoft but have no idea how to do.
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/web-api/salesorderdetail?view=dynamics-ce-odata-9

You can use this tool for generating API URL in dynamics CRM:
https://github.com/jlattimer/CRMRESTBuilder
first of all, you should import the solution in dynamics 365 after that you can open the app with a button on the solutions view

The web api endpoint to get particular salesorderdetail will look like: (with respective GUID)
https://crmdev.crm.dynamics.com/api/data/v9.1/salesorderdetails(00000000-0000-0000-0000-000000000000)
To get all the salesorderdetail records:
https://crmdev.crm.dynamics.com/api/data/v9.1/salesorderdetails
To get all the salesorderdetail records for particular salesorder:
https://crmdev.crm.dynamics.com/api/data/v9.1/salesorderdetails?$filter=_salesorderid_value eq 00000000-0000-0000-0000-000000000000
The complete code snippet will be like: (using XMLHttpRequest in JS)
var req = new XMLHttpRequest();
req.open("GET", "https://crmdev.crm.dynamics.com/api/data/v9.1/salesorderdetails?$filter=_salesorderid_value eq 00000000-0000-0000-0000-000000000000", 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.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.value.length; i++) {
var salesorderdetailid = results.value[i]["salesorderdetailid"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();

Related

Outlook Add-in - AttachmentId is malformed

We've been having issues intermittently where we get an error when downloading email item content from EWS "AttachmentId is malformed". This is for ItemAttachment (Especially .eml files)
We could not figure why or how this is happening and noticed that the ones that were failing had + and / in the id's. Searching across the web landed me on this article. Although this article is from 2015, wondering if this is still happening.
This article blew my mind and made sense (kind of) and implementing the conversion of + -> _ and / -> - worked fine, for a while.
We are now receiving the same error 'AttachmentId is malformed' and again could not find why, I removed the custom sanitizer function that replaces these characters and it started working again.
I have no idea what and why is this happening and how to reliably get attachment content. Currently, I've moved the sanitizer into the catch handler, so if for some reason the AttachmentId fails, we'll retry it by sanitizing it. Will have to keep an eye on how many fail.
Any light on this issue will be really appreciated.
Update 1.0 - Sample Code
Front-end
//At this point we've got the email and got the files
//We call EWS only if file.type == Office.MailboxEnums.AttachmentType.Item
//For all other files we call REST endpoint ~ Office.context.mailbox.restUrl + '/v2.0/'......
//Sample code below if only for EWS call
let files = this.email.attachments || [];
files.map(file => {
this._getEmailContent(file)
.then(res => {
return res;
});
})
//Get content from EWS
_getEmailContent(file, _failed){
//attachmentId
//Most of the times this will be fine, but at times when Id has a `+` or `/` if fails, Was expecting the convertToEwsId to handle any sanitization required.
let attachmentId = Office.context.mailbox.convertToEwsId(file.id, Office.MailboxEnums.RestVersion.v2_0);
return this.getToken(EWS)
.then(token => {
return this.http.post(`${endpoint}/downloadAttachment`,{
token: token,
url: Office.context.mailbox.ewsUrl,
id: attachmentId
},{
responseType: 'arraybuffer',
}).then(res => res.data);
}).catch(err => {
attachmentId = attachmentId.replace(/\+/g, "_");
this._getEmailContent(attachmentId, true);
})
}
Back-end
[HttpPost]
public DownloadAttachment(Request model){
var data = service.DownloadAttachment(model);
if(data == null)
{
return BadRequest("Error downloading content...");
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
return data;
}
}
//Inside service
public byte[] DownloadAttachment(Request request){
var ser = new ExchangeService
{
Credentials: request.token,
Url = request.url
}
//Here it fails intermittently, returning AttachmentId is malformed.
var attachment = ser.GetAttachments(new [] {request.attachmentId}, null, null).First();
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load();
return fileAttachment.Content;
}
}

Unable to remove Dynamics 365 Appointment's regardingobjectid value using Web API

I'm trying to remove value of field regardingobjectid from a appointment entity using Microsoft Dynamics 365 Web API. Not able to but it shows the below error:
{
"error": {
"code": "",
"message": "The property 'regardingobjectid' does not exist on type 'Microsoft.Dynamics.CRM.appointment'. Make sure to only use property names that are defined by the type."
Request
PATCH https://XXXXXXX.crm.dynamics.com/api/data/v8.2/appointments(9de8ba18-8303-e911-8147-3863bb2eb450)
Headers:
Content-Type: application/json
Authorization: Bearer *Token*
Body:
{
"subject": "Check Updates",
"ownerid#odata.bind": "/systemusers(51d09106-22b6-e811-8143-3863bb2ec140)",
"createdby#odata.bind": "/systemusers(51d09106-22b6-e811-8143-3863bb2ec140)",
"location": "",
"description": "nuldasddsadsal",
"statecode": 3,
"scheduledstart": "2018-12-19T06:45:00Z",
"scheduledend": "2018-12-19T07:15:00Z",
"isalldayevent": false,
"regardingobjectid": null,
"activitypointer_activity_parties": [
{
"partyid_account#odata.bind": "/accounts(4a2612e2-664b-e411-93ff-0050569469bd)",
"participationtypemask": "6"
}
]
}
Couple of things:
1.To update/overwrite a lookup field value using web api, we have to use single-valued navigation property regardingobjectid_account#odata.bind
var entity = {};
entity["regardingobjectid_account#odata.bind"] = "/accounts(1F496057-8DE7-E811-A97A-000D3A1A9EFB)";
var req = new XMLHttpRequest();
req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/appointments(6D78AD2C-5A16-E811-A955-000D3A1A9407)", 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) {
//Success - No Return Data - Do Something
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(entity));
2.As said above PATCH is for updating value of all field types, except for removing lookup value (updating null in lookup) - we have to use DELETE
My SO question and Community blog post

Error: Client is unauthorized to retrieve access tokens (ServiceAccountCredentials) nodejs

I have been trying to create an app to list all gmail labels of given user by using service account.
Service account have domain-wide delegation and it's raise error when I ran this script "Client is unauthorized to retrieve access tokens".
var {google} = require('googleapis');
const SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly'
];
var emailToLoginWith = 'useremail#anydomain.com';
var key = require('json_key_file_name.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
emailToLoginWith
);
jwtClient.authorize( function (err, tokens) {
if (err) {
console.log(err);
return;
}
console.log('tokens : ', tokens);
listLabels(jwtClient);
});
function listLabels(auth) {
var gmail = google.gmail({version: 'v1', auth: auth });
gmail.users.labels.list({
userId: 'user_id',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log('labels response', response);
var labels = response.labels;
if (labels.length == 0) {
console.log('No labels found.');
} else {
console.log('Labels:');
for (var i = 0; i < labels.length; i++) {
var label = labels[i];
console.log('- %s', label.name);
}
}
});
}
Client is unauthorized to retrieve access tokens.
This error normally happens when you have created the incorrect type of credentials on Google Developer console. You say that you are using a service account make sure that you have download the correct json file from. After that credentials and the code used to use them are diffrent. You cant use the credentials for a service account with code from browser you will get this error.
I am not a node developer but i found this
http://isd-soft.com/tech_blog/accessing-google-apis-using-service-account-node-js/
You may want to try to get the service account working with drive first. Then when that works move to gmail domain delegation with gmail and service accounts can be tricky sometimes its better to have an example you know works to build off of.

Issue on sending embedded image to gmail jquery c# mvc

I am facing an issue on sending email. Actually, I am trying to send an email with more text and many images in the body of the mail . I am using jquery and c# controller to make this work out.
The following code explains bit better:
In jquery, am using
$scope.SendEMailNew = function () {
var data = new FormData();
var ToEmail = $("#emailTo").val();
var CcEmail = $("#emailCc").val();
var Subject = $("#emailSubject").val();
var Message = document.getElementById(divID).outerHTML;
data.append("ToEmail", ToEmail);
data.append("CcEmail", CcEmail);
data.append("Subject", Subject);
data.append("Message", Message);
mailsendingIndicator();
$.ajax({
url: ApplicationUrl + 'SendEmail/MailSend',
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
hidemailsendingIndicator();
toastr.clear();
toastr.success("Mail sent successfully", opts);
},
error: function (er) {
hidemailsendingIndicator();
toastr.clear();
toastr.error("Something went wrong", opts);
}
});
In c# mvc controller, i am using
[AcceptVerbs(HttpVerbs.Post)]
public void MailSend(SendEmail MailDetails)
{
string result = string.Empty;
string from = "FromMail#gmail.com";
using (MailMessage mail = new MailMessage(from,MailDetails.ToEmail))
{
mail.Subject = MailDetails.Subject;
mail.Body = MailDetails.Message;
mail.IsBodyHtml = true;
if (!string.IsNullOrEmpty(MailDetails.CcEmail))
mail.CC.Add(MailDetails.CcEmail);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential("FromMail#gmail.com", "Password");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
}
}
After this code, the email could be sent with embedded images to my official mail id and to my client's mail id but to gmail and to outlook mails, the embedded images not displaying.
Especially, in outlook mails, I am not getting the option to download the image itself. In gmail, i am getting the image as base 64 code. Actually, the image is stored as bytes in database and retrieved to jquery through ajax call. I am facing this issue for long time.
What will be the solution for this kind of issue? Any idea will be a great help
Thanks

How to access POST data sent from a browser to Rikulo Steam Server

I ask the browser to POST JSON data to the stream v0.5.5 server using ajax. In the server side, how can I receive the data from the ajax request?
My client:(Google Chrome)
void ajaxSendJSON() {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
});
// POST the data to the server
var url = "/news";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(mapTOJSON()); // perform the async POST
}
String mapTOJSON() {
print('mapping json...');
var obj = new Map();
obj['title'] = usrTitle.value == null ? "none" : usrTitle.value;
obj['description'] = usrDesc.value == null ? "none" : usrDesc.value;
obj['photo'] = usrPhoto.value == "none";
obj['time'] = usrTime==null ? "none" : usrTime.value;
obj['ip']= '191.23.3.1';
//obj["ip"] = usrTime==null? "none":usrTime;
print('sending json to server...');
return Json.stringify(obj); // convert map to String i.e. JSON
//return obj;
}
My server:
void serverInfo(HttpConnect connect) {
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/news' && request.method == 'POST') {
response.addString('welcome from the server!');
response.addString('Content Length: ');
response.addString(request.contentLength.toString());
} else {
response.addString('Not found');
response.statusCode = HttpStatus.NOT_FOUND;
}
connect.close();
}
Again, I don't want the browser to ask for data from the server!
What am I doing is to asking the browser to submit the JSON data via ajax, and I just don't know how the server (Rikulo Stream v0.5.5) gets the "content" of data? All code is written in Google Dart Language M3. No Javascript!
POST is not supported well in Dart SDK, but Dart team planned to enhance it. Please stargaze it here: issue 2488.
On the other hand, since what you handle is JSON, you can listen to HttpRequest (I'm assuming the latest SDK) and convert List to String and then to JSON. Rikulo Commons provides a utility to simplify the job as follows:
import "package:rikulo_commons/io.dart";
IOUtil.readAsJson(request, onError: connect.error).then((jsonValue) {
//handle it here
});

Resources