Add attachment from MultipartContent Stream

Requirement

Create attachment in Dynamics 365 CE from the stream which will be available in MultipartContent response.

Details

Let’s say are getting MultipartContent in HttpResponse. This response contains stream which we want to use to create and attach pdf file in notes. We can use 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 contents, we can read stream and create notes attachment.

Hope it will help someone !!
Keep learning and Keep Sharing !!

Leave a Reply

Your email address will not be published. Required fields are marked *