Dynamics 365 Plugin parse Note attachment XML without using file - plugins

In Dynamics CRM online, I have a record in the annotation entity which has an XML attached.
From a plugin, I need to get the content of that attachment and create an XML element so I can deserialize its content as an object class and apply some logic.
As we are in an online implementation, I cannot do things like create a file and read its content.
So what we have is a document content in the attached file, which is a string with multiple characters, as you can see here (attachment is generated by a Power Automate flow):
Here is some of my code:
byte[] fileContentBytes = Encoding.Default.GetBytes(note.DocumentBody);
MemoryStream stream = new MemoryStream(fileContentBytes);
StreamReader globalReader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();
doc.Load(globalReader);
The error message says that Data at the root level is invalid. Line 1, position 1, as it's trying to parse as an XML something that is not parse-able as that.

Power Automate is generating JSON document, you are trying to parse it as XML, so failing.
Instead try some methods to convert to your needed format.

The document body is base 64 encoded.
Try the following
byte[] fileContentBytes = Convert.FromBase64String(note.DocumentBody);
MemoryStream stream = new MemoryStream(fileContentBytes);
StreamReader globalReader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();
doc.Load(globalReader);

Related

The api server cannot create the file when receives a put request

I am new in APIs. I have a java api server. In put method on server side, i receive a string and i create a arff file using that string. then i do some process on that file and return the result which is another string.
The problem is that when i do a put request the file is not created in local path, but when i run the code on a local application for test the file is created so the code works.
I have to generate a file of that string because i am using a machine learning algorithm that only works with files.Does anyone know why is that?
the method Classify text is called in put method in server side
public static int ClassifyText(String trained_model, String text) throws FileNotFoundException, IOException, Exception {
String evaluation_file = "..\toBeClassified_text.arff";
//create a arff file for the text
FileWriter fileWriter = new FileWriter(new File(evaluation_file));
PrintWriter printWriter = new PrintWriter(fileWriter);
The problem is solved by modifiying thisline:
String evaluation_file = "D:\toBeClassified_text.arff";

HttpWebRequest.GetRequestStream() is not working in MS Dynamics CRM Plugin

I have written a plugin wherein I am trying to get an XML response.
This is my code :
// Set the Method property of the request to POST.
string strXMLServer = "xxx";
var request = (HttpWebRequest)WebRequest.Create(strXMLServer);
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "xyz";
// Assuming XML is stored in strXML
byte[] byteArray = Encoding.UTF8.GetBytes(strXML);
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//(LINE 5) Get the request stream
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
This code works fine when its written in a console application. But when I copy the same code to a class library(plugin) and tries to debug it using plugin profiler, the application gets stopped abruptly when it reaches (LINE 5)
i.e. At Stream dataStream = request.GetRequestStream();
request.GetRequestStream() function is not working with plugin, but works fine within a console.
Any help would be appreciated :)
Thanks in advance
Note: I am using Dynamics 365 online trial version
There are a couple of things to take into consideration when building a plugin with web requests. Firstly, you need to use WebClient as it's widely supported by Microsoft products.
Secondly, your URL needs to be a DNS name and not an IP address, as this is a hosted plugin in sandbox mode.
Example from Microsoft's website: https://msdn.microsoft.com/en-us/library/gg509030.aspx
Reading material: https://crmbusiness.wordpress.com/2015/02/05/understanding-plugin-sandbox-mode/

Return Email Message from Web Api

I'm not sure if this is possible, but I need to return an email message from a web api controller. Essentially, it would then allow the user the open the file (an eml or msg), make some changes and then send it to the relevant person.
Code wise I have a service that returns a MailMessage.
I have a controller that returns a pdf, using the file's byte array as it's content, but a mail message doesn't seem the easiest thing to convert.
Is this possible? I would rather not write the message to disk first if I can help it, but I could if this is the only solution.
I have just faced the same problem, and I resolved it like this:
var stream = new MemoryStream(); // this has to contain your file content
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "test.eml"
};
If you want to know how to generate emails and do not send the but save them to disk instead, you can check the solution proposed here: How to save MailMessage object to disk as *.eml or *.msg file

AXIS 2 : java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl cannot be cast to org.apache.axiom.om.OMElement

I am using AXIS2 as client for handling SOAP response. The client stubs are generated using WSDL2JAVA command. To solve an issue, I am trying to read an xml response stored in .xml file in the generated stub, and assign to SOAPEnvelope. Below is the code written to load .xml content :
InputStream is = new ByteArrayInputStream((sb.toString()).getBytes());
javax.xml.parsers.DocumentBuilderFactory factory = avax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);
System.out.println("Got Document ..............");
is.close();
org.apache.axis2.saaj.util.SAAJUtil su = new org.apache.axis2.saaj.util.SAAJUtil();
org.apache.axiom.soap.SOAPEnvelope _returnEnv1 = su.getSOAPEnvelopeFromDOOMDocument(doc);
Am getting ClassCastException at the last line in the code (assigning to SOAPEnvelope).
Can someone please help me with this.
Axis2clients are used to send requests and receive response. Why are you trying to load response from a file? You should receive the response from the backend service. Check this guide to get to know about the clientapi. You can find detail guide in axis2 documentation also.

Playframework, binary pdf file attachment issue

I´ve got a pdf file as ByteArray and I want to know if there´s a way to attach it without creating the main file on the server.
The code provided by the Play documentation only allows real files to be attached.
EmailAttachment attachment = new EmailAttachment();
attachment.setDescription("A pdf document");
attachment.setPath(Play.getFile("rules.pdf").getPath());
I´m using the Playframework Mail module.
Thanks!
Since Play 1.x uses the Apache Commons Email library under the hood, you could use the MultiPartEmail#attach(DataSource ds, String name, String description) method:
import org.apache.commons.mail.*;
// create the mail
MultiPartEmail email = new MultiPartEmail();
email.setHostName("mail.myserver.com");
email.addTo("jdoe#somewhere.org", "John Doe");
email.setFrom("me#apache.org", "Me");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// get your inputstream from your db
InputStream is = new BufferedInputStream(MyUtils.getBlob());
DataSource source = new ByteArrayDataSource(is, "application/pdf");
// add the attachment
email.attach(source, "somefile.pdf", "Description of some file");
// send the email
email.send();
Upcoming Play Version 1.3 will introduce a method attachDataSource(), which can be called from within a Mailer class. This will allow you to attach a ByteArray as an attachment to emails easily without the need to save them to the disk first or without the need to use the Apache Commons Emails. You can then use the "standard" Play way.
Here is the corresponding feature request in the play bugtracker:
http://play.lighthouseapp.com/projects/57987/tickets/1500-adding-maillerattachdatasource-functionality