Xamarin iOS List Content not writing to json files - xamarin.ios

We are using Visual Studio 2017, for developing iOS Application. We are facing issue in writing the data displayed in the list to the json file and we are using function streamwriter.
Unhandled Exception: System.ArgumentException: Stream was not writable. occurred
Here I do want insert json file into ShopApp.Catalog_Master.json in portable project when clicking a saveButton:
private void saveButton_Clicked(object sender, EventArgs e)
{
var employee = new Activity
{
Act_ID = 12345,
Act_Name = "Peter",
Act_Date = "13122017",
Act_Rep = "Antony",
Act_Type = "SalesOder"
};
// Throwing Unhandled Exception
var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("ShopApp.Catalog_Master.json");
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(employee);
}
}

Related

Input output stream not working in Web Forms function

Can someone tell me why I keep getting a read and write timeout on this function? I have this as a code behind function on click even from a button. Everything as far as the data looks good until I get to the stream section and it still steps through, but when I check the Stream object contents after stepping into that object it states Read Timeout/Write Timeout: System invalid Operation Exception.
protected void SubmitToDB_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
{
try
{
if (SectionDropDownList.SelectedValue != null)
{
if (TemplateDropDownList.SelectedValue != null)
{
// This gets the full file path on the client's machine ie: c:\test\myfile.txt
string strFilePath = FileUploader.PostedFile.FileName;
//use the System.IO Path.GetFileName method to get specifics about the file without needing to parse the path as a string
string strFileName = Path.GetFileName(strFilePath);
Int32 intFileSize = FileUploader.PostedFile.ContentLength;
string strContentType = FileUploader.PostedFile.ContentType;
//Convert the uploaded file to a byte stream to save to your database. This could be a database table field of type Image in SQL Server
Stream strmStream = FileUploader.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
byte[] bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
saveFileToDb(strFileName, intFileSize, strContentType, bytUpfile); // or use FileUploader.SaveAs(Server.MapPath(".") + "filename") to save to the server's filesystem.
lblUploadResult.Text = "Upload Success. File was uploaded and saved to the database.";
}
}
}
catch (Exception err)
{
lblUploadResult.Text = "The file was not updloaded because the following error happened: " + err.ToString();
}
}
else
{
lblUploadResult.Text = "No File Uploaded because none was selected.";
}
}
Try something like this:
using (var fileStream = FileUploader.PostedFile.InputStream)
{
using (var reader = new BinaryReader(fileStream))
{
byte[] bytUpfile = reader.ReadBytes((Int32)fileStream.Length);
// SAVE TO DB...
}
}

iText7 for .NET - error while merging files

I've created simple method that allows me to merge multiple PDF files.
Below is my code:
private void Merge(List<string> src, string dest)
{
Stopwatch sw = new Stopwatch();
sw.Start();
PdfDocument pdfDocument1 = new PdfDocument(new PdfReader(src[0]), new PdfWriter(dest));
for (int i = 1,max=src.Count; i < max; i++)
{
PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(src[i]));
var pagesCount = pdfDocument2.GetNumberOfPages();
pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
pdfDocument2.Close();
}
pdfDocument1.Close();
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
I've based my code on example from iText book: http://developers.itextpdf.com/examples/merging-pdf-documents/clone-merging-documents-bookmarks
For test purpose I've attached that method to button and I'm caling it like this:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").Take(100).ToList();
Merge(files,dest);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
From time to time (after n'th click on that button) I get exception saying:
Cant cast from 'iText.Kernel.Pdf.PdfNumber' to
'iText.Kernel.Pdf.PdfStream'.
Also first time I click my application takes about 100MB of memory, next time I click it increase to 150MB, next click and I get 230MB of memory used, so it look like it isn't releasing memory.
Is there a better way to merge multiple PDF's into one using iTextSharp 7?
As per request I'm adding StackTrace:
w iText.Kernel.Pdf.PdfPage.GetContentStream(Int32 index)
w iText.Kernel.Pdf.PdfPage.Flush(Boolean flushXObjects)
w iText.Kernel.Pdf.PdfPage.Flush()
w iText.Kernel.Pdf.PdfDocument.Close()
w iTextSharp7_Merge.Form1.Merge(List`1 src, String dest)
w c:\Users\Misiu\Documents\Visual Studio 2013\Projects\iTextSharp7_Merge\Form1.cs:wiersz 75
And here are exception details:
EDIT:
I've changed button click function so now it loads 100 file names from directory and calls Merge method 10 times with same list:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").OrderBy(x => x).Skip(0).Take(100).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 1; i <= 10; i++)
{
Debug.WriteLine(i);
Merge(files, dest1);
}
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
This way I've excluded random sort of Directory.GetFiles.
Here is sample output that comes from Visual Studio:
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'
1
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.kernel.dll'
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.io.dll'
A first chance exception of type 'System.NullReferenceException' occurred in itext.kernel.dll
2
3
The thread '<No Name>' (0x2dd0) has exited with code 0 (0x0).
4
5
A first chance exception of type 'System.InvalidCastException' occurred in itext.kernel.dll

MediaCapture.CapturePhotoToStreamAsync() and MediaCapture.CapturePhotoToStorageFileAsync() throw Argument exception

I'm trying to create an app that can use the camera for Windows Phone 8.1, using the Windows RT/XAML development model.
When I try to call either of the capture methods off of the MediaCapture class I get an ArgumentException with the message "The parameter is incorrect." Here is my code
private async Task Initialize()
{
if (!DesignMode.DesignModeEnabled)
{
await _mediaCaptureMgr.InitializeAsync();
ViewFinder.Source = _mediaCaptureMgr;
await _mediaCaptureMgr.StartPreviewAsync();
}
}
private async void ViewFinder_OnTapped(object sender, TappedRoutedEventArgs e)
{
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var stream = new InMemoryRandomAccessStream();
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
_bitmap = new WriteableBitmap((int) ViewFinder.ActualWidth, (int) ViewFinder.ActualHeight);
stream.Seek(0);
await _bitmap.SetSourceAsync(stream);
PreviewImage.Source = _bitmap;
PreviewElements.Visibility = Visibility.Visible;
ViewFinder.Visibility = Visibility.Collapsed;
Buttons.Visibility = Visibility.Visible;
Message.Visibility = Visibility.Collapsed;
stream.Seek(0);
var buffer = new global::Windows.Storage.Streams.Buffer((uint) stream.Size);
stream.ReadAsync(buffer, (uint) stream.Size, InputStreamOptions.None);
DataContext = buffer.ToArray();
if (PhotoCaptured != null)
PhotoCaptured(this, null);
}
The initialize method is called on page load, and the viewfinder_ontapped is called when they tap the CaptureElement I have in the xaml. The error is thrown on
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
What's really bizarre is that I downloaded the latest source for the winrt xaml toolkit http://winrtxamltoolkit.codeplex.com/ and tried their sample camera app, which uses similar code. It throws the same error on MediaCapture.CapturePhotoToStorageFileAsync(). Can anyone help me identify why?

Cannot convert HTML (http://www.google.co.in/) to PDF using iTextSharp

I am using iTextSharp to convert a HTML (source site is google: http://www.google.co.in/) to PDF.
My code :
protected void Page_Load(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string HTMLCode = wc.DownloadString("http://www.google.co.in/");
var result = createPDF(HTMLCode);
}
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
I have referred the createPDF function from here.
But I am encountering the below error
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.
Is it some problem with iTextSharp library? By the way I am using itextsharp-dll-core-5.3.0
No one listens!
HTMLWorker
is obsolete.
won't be maintained.
it's replaced with XML-Worker.

Merge memorystreams to one iText document

I have four MemoryStreams of data that I want to merge and then open the pdfDocument, without creating a single file.
It's possible to write them down to files and then merge them but that would be bad practice and that can also cause a few issues so I want to avoid that.
However, I can not find a way to merge the MemoryStreams with iText5 for .NET.
Right now, this is how I do it with files:
private static void ConcatenateDocuments()
{
var stream = new MemoryStream();
var readerFrontPage = new PdfReader(Folder + FrontPageName);
var readerDocA = new PdfReader(Folder + docA);
var readerDocB = new PdfReader(Folder + DocB);
var readerAppendix = new PdfReader(Folder + Appendix);
var pdfCopyFields = new PdfCopyFields(stream);
pdfCopyFields.AddDocument(readerFrontPage);
pdfCopyFields.AddDocument(readerDocA );
pdfCopyFields.AddDocument(readerDocB);
pdfCopyFields.AddDocument(readerAppendix);
pdfCopyFields.Close();
SavePdf(stream, FilenameReport);
}
Since I need to remove the use of files, I keep the MemoryStream's as the different parts are built from different resources. So I have references to these memorystreams.
How can this be done?
The error PDF header signature not found can be fixed in this case by setting the stream's Position back to 0. Since you're not getting the error Cannot access a closed Stream I'm assuming that you are already correctly setting the PdfWriter's CloseStream to false.
Below is a full working C# 2010 WinForm app targeting iTextSharp 5.1.1.0 that creates three PDFs in MemoryStreams and combines them. Since I don't have a web server handy I'm writing them to disk.
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Create three MemoryStreams
MemoryStream[] streams = { CreateDoc("Page 1"), CreateDoc("Page 2"), CreateDoc("Page 3") };
//I don't have a web server handy so I'm going to write my final MemoryStream to a byte array and then to disk
byte[] bytes;
//Create our final combined MemoryStream
using (MemoryStream finalStream = new MemoryStream())
{
//Create our copy object
PdfCopyFields copy = new PdfCopyFields(finalStream);
//Loop through each MemoryStream
foreach (MemoryStream ms in streams)
{
//Reset the position back to zero
ms.Position = 0;
//Add it to the copy object
copy.AddDocument(new PdfReader(ms));
//Clean up
ms.Dispose();
}
//Close the copy object
copy.Close();
//Get the raw bytes to save to disk
bytes = finalStream.ToArray();
}
//Write out the file to the desktop
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Combined.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
}
this.Close();
}
/// <summary>
/// Helper method to create temporary documents
/// </summary>
private MemoryStream CreateDoc(string name)
{
MemoryStream ms = new MemoryStream();
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
{
writer.CloseStream = false;
doc.Open();
doc.Add(new Paragraph(name));
doc.Close();
}
}
return ms;
}
}
}
While it seams the PdfReader can not take the stream, the array of the stream works.
var readerFrontPage = new PdfReader(streamFrontPage.ToArray());

Resources