Requirement
Create an attachment in Dynamics 365 CE from the stream, which will be available in the MultipartContent response.
Details
Let’s say we are getting MultipartContent in HttpResponse. This response contains a stream that we want to use to create and attach a pdf file in notes. We can use the following code.
if (httReqresponse != null && httReqresponse.IsSuccessStatusCode)
{
var multipartContent = await httReqresponse.Content.ReadAsMultipartAsync();
if (multipartContent != null && multipartContent.Contents.Count > 1)
{
HttpContent secondPart = multipartContent.Contents[1];
var streamContent = await secondPart.ReadAsStreamAsync();
byte[] bytesArrary;
using (MemoryStream ms = new MemoryStream())
{
streamContent.CopyTo(ms);
bytesArrary= ms.ToArray();
}
Entity notes = new Entity("annotation");
notes["objectid"] = new EntityReference("<<Parenentitylookupname>>", <<guid>>);
notes["objecttypecode"] = "<<Name of parent entity>>";
notes["subject"] = "Notes Subject";
notes["documentbody"] = Convert.ToBase64String(bytesArrary);
//set mimetpe
notes["mimetype"] = @"application/pdf";
notes["filename"] = "FileName.pdf";
service.Create(notes);
}
}
}
The code first checks if the HTTP response is not null and if the response status code indicates success. The response content is expected to be in a multipart format, which we are reading asynchronously. Once we have content, we can read the stream and create notes attachments.
Keep learning and Keep Sharing !!