CRM 2013: Deserializing within a sandboxed plugin - plugins

I have an XML string that I would like to deserialize into a strongly typed class. The below code works great until I put it into a sandboxed plugin, at which point I get a FileIOPermissions error because I am using the StringReader class. I am having issues trying to deserialize without using StringReader. Does anyone have a good alternative?
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
DataContractSerializer serializer = new DataContractSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
using (XmlTextReader xmlReader = new XmlTextReader(reader))
{
if (serializer.IsStartObject(xmlReader)) //Throws FileIOPermissions error
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)(serializer.ReadObject(xmlReader));
}
}
}

Try the following which I've run successfully in a sandbox plugin:
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
XmlSerializer serializer = new XmlSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)serializer.Deserialize(reader);
}

Related

What is the relevant code for getInputStream() in Swift 5?

In Android Studio, I use this code to get data from server
url = new URL(url);
HttpURLConnection connection = null;
try
{
HttpURLConnection.setFollowRedirects(false);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setInstanceFollowRedirects(false);
InputStream inputStream = connection.getInputStream();
this.header = connection.getHeaderFields();
this.status = connection.getResponseCode();
}
In Swift 5, I'm able to perform similar task by using URLSession.shared.dataTask(), but I couldn't find anything to replace InputStream inputStream = connection.getInputStream().
After I did some research on Swift 5 inputStream and outputStream, I'm getting more confused, can anyone provide some sample on how to replace this?
Use uploadTask(withStreamedRequest in order to work with streams https://developer.apple.com/documentation/foundation/urlsession/1410934-uploadtask

Unity Json.net bson Self referencing loop

I am trying to save content in my game with Json.net. with this resource I got my game saving to JSON but now I want to save it in the Bson format as I don't want my players to be able to easily edit the save files.
Here is the code works and is saving my game data to json.
File.WriteAllText(path, JsonConvert.SerializeObject(objectToSave, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
Here I am trying to save my game data in the bson format but I don't quite know how to turn off the ReferenceLoopHandling in the bson format.
using (var stream = new MemoryStream())
{
var serializer = new JsonSerializer();
var writer = new BsonWriter(stream);
serializer.ReferenceLoopHandling.Equals(false);
serializer.Serialize(writer, objectToSave);
File.WriteAllText(path, serializer.ToString());
}
When I run this code I get the following error.
JsonSerializationException: Self referencing loop detected for property 'graph' with type 'StoryGraph'. Path 'nodes[0]'.
You can use the factory methods JsonSerializer.CreateDefault(JsonSerializerSettings) or JsonSerializer.Create(JsonSerializerSettings) to manufacture a serializer with your required settings, then serialize directly to a file using the following extension methods:
public static partial class BsonExtensions
{
// In Json.NET 10.0.1 and later use https://www.nuget.org/packages/Newtonsoft.Json.Bson
public static void SerializeToFile<T>(T obj, string path, JsonSerializerSettings settings = null)
{
using (var stream = new FileStream(path, FileMode.Create))
using (var writer = new BsonWriter(stream)) // BsonDataWriter in Json.NET 10.0.1 and later
{
JsonSerializer.CreateDefault(settings).Serialize(writer, obj);
}
}
public static T DeserializeFromFile<T>(string path, JsonSerializerSettings settings = null)
{
using (var stream = new FileStream(path, FileMode.Open))
using (var reader = new BsonReader(stream)) // BsonDataReader in Json.NET 10.0.1 and later
{
var serializer = JsonSerializer.CreateDefault(settings);
//https://www.newtonsoft.com/json/help/html/DeserializeFromBsonCollection.htm
if (serializer.ContractResolver.ResolveContract(typeof(T)) is JsonArrayContract)
reader.ReadRootValueAsArray = true;
return serializer.Deserialize<T>(reader);
}
}
}
And then serialize as follows:
BsonExtensions.SerializeToFile(objectToSave, path,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
Notes:
Be sure to use the same settings when deserializing.
BSON support was moved into its own package Newtonsoft.Json.Bson in Json.NET 10.0.1. In this version or later you should use BsonDataWriter (and BsonDataReader) as BsonWriter has been made obsolete, and will eventually be removed.
serializer.ToString() is not going to return the serialized BSON; instead use MemoryStream.ToArray(), i.e.
File.WriteAllBytes(path, stream.ToArray());
However it's more efficient to stream directly to the file as shown in the extension methods above.
serializer.ReferenceLoopHandling.Equals(false); is not the correct way to set the ReferenceLoopHandling property in c#. Instead set it as if it were a field:
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
See: Using Properties (C# Programming Guide).
Demo fiddle here.
You can also directly set the serializer:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Fix: Ignore loops
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
...
This solved the issue for me in the Unity C# context.

send email with multiple attachment in scala

I have used the java mail API to send emails within our group. I am aware of the DataHandler objects that in turn uses FileDataSource to grab the files and attach as a multipart file. However, I am not able to use it in scala. Can anyone help me on this?
Heres my code:
def createMessage: Message = {
val properties = new Properties()
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port",smtpPort)
val session = Session.getDefaultInstance(properties, null)
return new MimeMessage(session)
}
var message: Message = null
message = createMessage
message.setFrom(new InternetAddress(from))
message.setSentDate(new Date())
message.setSubject(subject)
message.setText(content)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to))
def sendMessage {
Transport.send(message)
}
I can use message.sefileName to set file name of the attachment, but how can I attach the actual files. For example in Java, we can achieve similar results like the following:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
messageBodyPart2.setFileName(fdatasource.getName)
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(messageBodyPart1);
mpart.addBodyPart(messageBodyPart2);
message.setContent(mpart);
I don't know this mail API, but you should be able to use a Java API the same way in Scala that you would use it in Java. If you see something like this in Java:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
You usually want to translate it to something like this in Scala:
val messageBodyPart1: MimeBodyPart = new MimeBodyPart()
messageBodyPart1.setText(messageText)
Just translate the Java code you have posted to Scala this way and it should work as well (or not well) as it worked in Java.

GenerateAppearances = true; System.NullReferenceException

Got some legacy code using iTextSharp.
All documents have GenerateAppearances set to true regardless. and now its triggering an exception.
Took the basic code out and placed it into a Console app, same thing, Used a generic PDF (http://www.pdf995.com/samples/pdf.pdf) of the net same thing.
This is using version 5.5.12
class Program
{
static void Main(string[] args)
{
var reader = new PdfReader(#"C:\Users\me\Desktop\pdf.pdf");
var outStream = new MemoryStream();
var stamper = new PdfStamper(reader, outStream);
stamper.AcroFields.GenerateAppearances = true; <--- usually true before setting
stamper.FormFlattening = true;
}
}
An unhandled exception of type 'System.NullReferenceException' occurred in itextsharp.dll
Additional information: Object reference not set to an instance of an object.
Thanks
After years of production, I just changed it from:
if (stamper.AcroFields != null)
{
f.GenerateAppearances = true;
foreach(var field in f.Fields)
{
f.SetField(field.Key, f.GetField(field.Key));
}
stamper.FormFlattening = true;
}
to
if (stamper.AcroFields != null && stamper.AcroFields.GenerateAppearances == true)
I encounter the same issues as below:
When I set AcroFields.GenerateAppearances = true
an unhandled exception of type 'System.NullReferenceException' occurred in itextsharp.dll
Additional information: Object reference not set to an instance of an object.
I debugged this code and found that AcroFields is not null. but NullReferenceException still occourred.
After inverstigating, I found that the format of PDF file is aspose xfa rather than acroforms. So I solved this issue by converting the format of PDF from aspose xfa to acroforms.

Plug-In that Converted Note entity pre-existing attachment XML file into new .MMP file

strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.