GenerateAppearances = true; System.NullReferenceException - itext

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.

Related

Can two ASP . NET Core 5.0 web api cause "The content may be already have been read by another component" errpr 400 if they accessed same db be4?

My API was as follows:
[HttpPut("{id}")]
public async Task<ActionResult<HomeContextModel>> EditHomeContext(int id, string title, string context, string subcontext, IFormFile imageFile)
{
HomeContextModel homeContextModel = await _context.HomeContext.Include(x => x.Image).Include(x => x.Button).Include(x => x.Logo).ThenInclude(y => y.Image)
.FirstOrDefaultAsync(m => m.Context_Id == id);
//HomeContextModel homeContextModel = await GetHomeContextModel(id);
if (homeContextModel == null)
{
return BadRequest("Context Id cannot be null");
}
if (imageFile != null)
{
ImageModel imageModel = homeContextModel.Image;
if (imageModel != null)
{
string cloudDomain = "https://privacy-web.conveyor.cloud";
string uploadPath = _webHostEnvironment.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string filePath = uploadPath + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imageModel.Image_Byte = memoryStream.ToArray();
}
imageModel.ImagePath = cloudDomain + "/Images/" + imageFile.FileName;
imageModel.Modify_By = "CMS Admin";
imageModel.Modity_dt = DateTime.Now;
//_context.Update(imageModel);
}
}
homeContextModel.Title = title;
homeContextModel.Context = context;
homeContextModel.SubContext = subcontext;
_context.Entry(homeContextModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HomeContextModelExists(homeContextModel.Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("Home Context Edit Successfully");
}
It's an API for the Content Management System (CMS) to change the content of the Homepage using a Flutter webpage that make put request onto this API.
Everything works fine. In the last few days, where I tested and tested again during the development. So before today, I've wrapped up them and submitted to the necessary place (It's a university FYP).
Until now it cause me this error when I was using this to prepare my presentation:
Error 400 failed to read the request form Unexpected end of stream ..."
After all the tested I tried:
Internet solutions
restore the database
repair Microsoft VS 2019 (As this issue was fixed before after I
updated my VS 2019 from 16.8. to the latest 16.11.7)
Use the ASP .NET file which didn't caused this issue before
Then I realized it may be because of I used another older ASP file to accessed the same database before. Does this really cause this matter?
If yes, then now how should I solved it, with the action I already done (listed as above)?
EDIT: Additional description to the situation
The above API I set breakpoint before, on the first line, using Swagger to test it.
It turns out that it didn't go into the API and straightaway return the error 400
REST API can have parameters in at least two ways:
As part of the URL-path
(i.e. /api/resource/parametervalue)
As a query argument
(i.e. /api/resource?parameter=value)
You are passing your parameters as a query instead of a path as indicated in your code. And that is why it is not executing your code and returning 400.

WebView.loadUrl raising UnsupportedOperationException

This exception raising only in android 5.1 (Samsung galaxy J3 2016)
Log:
Caused by java.lang.UnsupportedOperationException
java.util.Collections$SingletonMap$1$1.remove (Collections.java:355)
java.util.AbstractMap.remove (AbstractMap.java:397)
org.chromium.android_webview.AwContents.loadUrl (AwContents.java:1594)
org.chromium.android_webview.AwContents.loadUrl (AwContents.java:1458)
com.android.webview.chromium.WebViewChromium.loadUrl (WebViewChromium.java:496)
android.webkit.WebView.loadUrl (WebView.java:862)
I don't have this device, I receive a ton of such exceptions from my crashlytics report.
My WebView settings is below:
settings.loadWithOverviewMode = true
settings.useWideViewPort = true
#SuppressLint("SetJavaScriptEnabled")
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
webViewClient = WebViewClient()
And I am loading URL with extra headers provided:
val extraHeaders = mapOf("Referer" to "https://my.site.url")
webView.loadUrl(state.url, extraHeaders)
Ok, I found a problem:
In source code of AwContents in loadUrl method you can find such block:
final String REFERER = "referer";
Map<String, String> extraHeaders = params.getExtraHeaders();
if (extraHeaders != null) {
for (String header : extraHeaders.keySet()) {
if (REFERER.equals(header.toLowerCase(Locale.US))) {
params.setReferrer(new Referrer(extraHeaders.remove(header), 1));
params.setExtraHeaders(extraHeaders);
break;
}
}
}
interesting thing is extraHeaders.remove(header) because I'm creating immutable map, this causing throwing UnsupportedOperationException.
Made this change:
val extraHeaders = mutableMapOf("Referer" to "https://my.site.url")

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.

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.

CRM 2013: Deserializing within a sandboxed plugin

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);
}