I have the following code,
I am sending an array of data to a web service, the response from the web service gets displayed currently in a web form as shown below.
private void Form1_Load(object sender, EventArgs e)
{
int ASent;
int CSent;
webservice.Results returned = convert();
txtResult.Text = System.Convert.ToString(returned.status);
txtMoreRes1.Text = returned.errorDetails[0].errorDetails;
txtMoreRes2.Text = returned.errorDetails[1].errorDetails;
txtMoreRes3.Text = returned.errorDetails[2].errorDetails;
txtMoreRes4.Text = returned.errorDetails[3].errorDetails;
date.Text = System.Convert.ToString(DateTime.Today);
time.Text = System.Convert.ToString(DateTime.Now.TimeOfDay);
}
What I now need is for the results 'returned' to be converted from an xml response into a .csv file. Then have the code save that .csv to a location on the C drive. How can I change my code to do this?
Thanks for your time!
StringBuilder SbCSV = new StringBuilder();
int ActualSent;
int CommitmentSent;
webservice.summaryResults returned = convert(out ActualSent, out CommitmentSent);
//txtResult.Text = System.Convert.ToString(returned.status);
SbCSV.Append(System.Convert.ToString(returned.status));
//txtMoreRes1.Text = returned.errorDetails[0].errorDetails;
SbCSV.Append("," + returned.errorDetails[0].errorDetails);
//txtMoreRes2.Text = returned.errorDetails[1].errorDetails;
SbCSV.Append("," + returned.errorDetails[1].errorDetails);
// Similary ...
txtMoreRes3.Text = returned.errorDetails[2].errorDetails;
txtMoreRes4.Text = returned.errorDetails[3].errorDetails;
actualSum.Text = System.Convert.ToString(returned.actualSum);
commitmentSum.Text = System.Convert.ToString(returned.commitmentSum);
date.Text = System.Convert.ToString(DateTime.Today);
time.Text = System.Convert.ToString(DateTime.Now.TimeOfDay);
actualsumsent.Text = ActualSent.ToString();
commitmentsumsent.Text = CommitmentSent.ToString();
errorposition1.Text = System.Convert.ToString(returned.errorDetails[0].errorPosition);
errorposition2.Text = System.Convert.ToString(returned.errorDetails[1].errorPosition);
errorposition3.Text = System.Convert.ToString(returned.errorDetails[2].errorPosition);
errorposition4.Text = System.Convert.ToString(returned.errorDetails[3].errorPosition);
TextWriter Tw = new StreamWriter("Your_FilePath_Name.csv");
Tw.Write(SbCSV.ToString());
Tw.Close();
Tw.Dispose();
You could also use FileHelpers to do this stuff.
You must create a class named MyClass with attributes that match your .csv format (each column = one attribute)
you build a List of such class objects and convert to csv this way using FileHelper :
FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
MyClass[] res = null; //Fill your array here from your code.
// To Write Use:
engine.WriteFile("FileOut.txt", res);
You can also do this with an XML Transformation.
Related
I am trying to create a process in .NET to convert a PDF and all it's pages + attachments to PNGs. I am evaluating libraries and came across PDFiumSharp but it is not working for me. Here is my code:
string Inputfile = "input.pdf";
string OutputFolder = "Output";
string fileName = Path.GetFileNameWithoutExtension(Inputfile);
using (PdfDocument doc = new PdfDocument(Inputfile))
{
for (int i = 0; i < doc.Pages.Count; i++)
{
var page = doc.Pages[i];
using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, false))
{
page.Render(bitmap);
var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
bitmap.Save(targetFile);
}
}
}
When I run this code, I get this exception:
screenshot of exception
Does anyone know how to fix this? Also does PDFiumSharp support extracting PDF attachments? If not, does anyone have any other ideas on how to achieve my goal?
PDFium does not look like it supports extracting PDF attachments. If you want to achieve your goal, then you can take a look at another library that supports both extracting PDF attachments as well as converting PDFs to PNGs.
I am an employee of the LEADTOOLS PDF SDK which you can try out via these 2 nuget packages:
https://www.nuget.org/packages/Leadtools.Pdf/
https://www.nuget.org/packages/Leadtools.Document.Sdk/
Here is some code that will convert a PDF + all attachments in the PDF to separate PNGs in an output directory:
SetLicense();
cache = new FileCache { CacheDirectory = "cache" };
List<LEADDocument> documents = new List<LEADDocument>();
if (!Directory.Exists(OutputDir))
Directory.CreateDirectory(OutputDir);
using var document = DocumentFactory.LoadFromFile("attachments.pdf", new LoadDocumentOptions { Cache = cache, LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments });
if (document.Pages.Count > 0)
documents.Add(document);
foreach (var attachment in document.Attachments)
documents.Add(document.LoadDocumentAttachment(new LoadAttachmentOptions { AttachmentNumber = attachment.AttachmentNumber }));
ConvertDocuments(documents, RasterImageFormat.Png);
And the ConvertDocuments method:
static void ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat)
{
using var converter = new DocumentConverter();
using var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD);
ocrEngine.Startup(null, null, null, null);
converter.SetOcrEngineInstance(ocrEngine, false);
converter.SetDocumentWriterInstance(new DocumentWriter());
foreach (var document in documents)
{
var name = string.IsNullOrEmpty(document.Name) ? "Attachment" : document.Name;
string outputFile = Path.Combine(OutputDir, $"{name}.{RasterCodecs.GetExtension(imageFormat)}");
int count = 1;
while (File.Exists(outputFile))
outputFile = Path.Combine(OutputDir, $"{name}({count++}).{RasterCodecs.GetExtension(imageFormat)}");
var jobData = new DocumentConverterJobData
{
Document = document,
Cache = cache,
DocumentFormat = DocumentFormat.User,
RasterImageFormat = imageFormat,
RasterImageBitsPerPixel = 0,
OutputDocumentFileName = outputFile,
};
var job = converter.Jobs.CreateJob(jobData);
converter.Jobs.RunJob(job);
}
}
I am trying to make a small program to read a URLs from a DB and attach them to SAP B1 Deliveries.
Example source URL :
http://xxxx/xx/xxx/xxx/xxx/x/xxxx.pdf
Code:
oAttDelv.Lines.SourcePath = Path.GetDirectoryName(row.AttachURL);
oAttDelv.Lines.FileName = Path.GetFileNameWithoutExtension(row.AttachURL);
oAttDelv.Lines.FileExtension = Path.GetExtension(row.AttachURL);
int iErr = oAttDelv.Add();
int AttEntry = 0;
int temp_int = lErrorCode;
string temp_string = sErrorMsg;
oCompany.GetLastError(out temp_int, out temp_string);
The error shown in temp_string is as in the image. How do I resolve the two periods before pdf and get just one?
Errors:
temp_int = -5002
temp_string = "Source file does not exist , 'http:\\*****************\\jspui\\bitstream\\123456789\\2444\\1\\500393..pdf'"
Try this:
var temp_string = #"Source file does not exist , 'http:\*****************\jspui\bitstream\123456789\2444\1\500393..pdf'";
var file_name = temp_string.Substring(temp_string.LastIndexOf(#"\") + 1).Replace("..", ".");
Guys am trying to read a csv file from the view, get its data , format it and write back into an empty csv file. presently have been able to achieve the first approach, where the challenge is right now is writing back into an empty csv file created , but it happens that the csv file is always blank after writing in the file. can someone help me out if am missing anything. Note " am just reading and writing the field , have got nothing to do with the hearder because the csv file has no header" Am using csvhelper library.
if (file.ContentLength > 0)
{
string origin = "FORMATERCSV";
string destination = "FORMATERCSVDESTINATION";
string curretnDate = Convert.ToString(DateTime.Now.ToShortDateString().Replace(#"/", "_"));
var fileName = Path.GetFileName(file.FileName);
var pathfound = Server.MapPath( #"/" + "Content" + "/" + origin + "/" + curretnDate + "/");
var pathfoundDestination = Server.MapPath(#"/" + "Content" + "/" + destination + "/" + curretnDate + "/");
if (!Directory.Exists(pathfound)) Directory.CreateDirectory(pathfound);
if (!Directory.Exists(pathfoundDestination)) Directory.CreateDirectory(pathfoundDestination);
string PathToStore = string.Format(#"{0}\{1}", pathfound, fileName);
string PathToStoreDestination = string.Format(#"{0}\{1}", pathfoundDestination, fileName);
var path = Path.Combine(pathfound,fileName);
file.SaveAs(PathToStore);
file.SaveAs(PathToStoreDestination);
System.IO.File.WriteAllText(PathToStoreDestination,string.Empty);
StreamReader sr = new StreamReader(PathToStore);
CsvReader csvread = new CsvReader(sr);
csvread.Read();
var shedule = new Shedule()
{
RSA_PIN = csvread.GetField<string>(0),
EMPLOYEE_NAME = csvread.GetField<string>(1),
EMPLOYER_CONTRIBUTION = csvread.GetField<double>(2),
EMPLOYER_VC = csvread.GetField<double>(3),
EMPLOYEE_CONTRIBUTION = csvread.GetField<double>(4),
EMPLOYEE_VC = csvread.GetField<double>(5),
TOTAL_CONTRIBUTION = csvread.GetField<double>(6),
FROM_MONTH = csvread.GetField<string>(7),
FROM_YEAR = csvread.GetField<string>(8),
TO_MONTH = csvread.GetField<string>(9),
TO_YEAR = csvread.GetField<string>(10),
EMPLOYER_CODE = csvread.GetField<string>(11),
EMPLOYER_NAME = csvread.GetField<string>(12),
PTID = csvread.GetField<string>(13),
RECEIVED_DATE = csvread.GetField<string>(14),
};
StreamWriter sw = new StreamWriter(PathToStoreDestination);
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
scvwrite.Flush();
// Gets field by position returning int
// var field = csv.GetField<int>(0);
}
return RedirectToAction("Index");
}
Several things could actually occure.
1) are you sure the file from the view is not empty?
2) If you use a break point when you instantiate your class Schedule. Do you get the data from the CSV.
3) Do you really need to do this 2 step, wouldn't it be better to directly write the content of the original file to the new file?
4) Last but not least don't forget to close your streamwriter or do like so :
using(var sw = new StreamWriter(PathToStoreDestination)){
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.Flush();
}
Doing so you don't even need to specify to flush.
using (var sw = new StreamWriter(PathToStoreDestination))
{
sw.AutoFlush = true;
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYER_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
//scvwrite.Flush();
}
I am new to Windows form application I want to Save Data in file except in (Sql) or database.I tried many things and I am able to store only one value in text file using it
TextWriter txt = new System.IO.StreamWriter("E:\\Tahir\\ScaleSystemDataSave\\First.txt");
txt.Write(txtFirsrWeight.Text);
txt.Close();
but I Want to Store an Object in file how can I Do it My object is like this
private void btnSave_Click(object sender, EventArgs e)
{
FirstTime obj = new FirstTime();
obj.CardNo = txtCardNo.Text;
obj.DateTime = txtDateTimePicker.Value;
obj.VehicleNo = txtVehicalNo.Text;
obj.WeightType = Convert.ToString(cbxWeigtType.SelectedItem);
obj.FirstWeight = txtFirsrWeight.Text;
if (rbtWithDriver.Checked == true)
{
obj.IsDriver = (int)Status.WithDriver;
}
else if (rbtWithouDriver.Checked == true)
{
obj.IsDriver = (int)Status.withOutDriver;
}
}
You have 2 options available to you.
Format the text file yourself like a comma delimited file and then read the file back in, parse it and assign the values back to your object.
Use a known serialization technique such as XML or JSON.
Below is an example of JSON serialization that achieves what you need.
var first = new FirstTime()
{
CardNo = "121515611",
Date = DateTime.Now.Date,
VehicleNo = "MNRG23434",
WeightType = "MyWeight",
FirstWeight = "FirstWeight"
};
var fileText = JsonConvert.SerializeObject(first);
TextWriter txt = new StreamWriter("C:\\First.txt");
txt.Write(fileText);
txt.Close();
var fileStream = File.Open("C:\\First.txt",FileMode.Open);
var fileReader = new StreamReader(fileStream);
var contents = fileReader.ReadToEnd();
var restoredObject = JsonConvert.DeserializeObject<FirstTime>(contents);
This stores the data in format as per the below
{"CardNo":"121515611","Date":"2017-03-16T00:00:00+00:00","VehicleNo":"MNRG23434","WeightType":"MyWeight","FirstWeight":"FirstWeight"}
Hope that helps you.
I have some problems with Telerik reports.
Feels like i have missed something...
I wanna create a list of reports, and then write them to ONE file.
But when i write it out i only get one page.
The writer writer over page 1 all foreach, so it just write one page.
But i want several pages... in this case 10.
Have tried write with FileStream, File and more...
Does anyone have a good idea?
public void WriteToFile()
{
string path = #"C:\";
string test = "test";
var report = new Report2();
var procceser = new ReportProcessor();
var list = new List<RenderingResult>();
for (int i = 0; i < 10; i++)
{
var res = procceser.RenderReport("PDF", report, null);
list.Add(res);
}
string filePath = Path.Combine(path, test);
var Writer = new BinaryWriter(File.Create(filePath));
foreach (var renderingResult in list)
{
Writer.Write(renderingResult.DocumentBytes);
}
Writer.Flush();
Writer.Close();
}