Netsuite: Download XML Response via API - c#

Background: relatively new to C# and NetSuite.
Given a little netsuite method (via SuiteTalk) such as:
private void getInvoice()
{
RecordRef invoiceRef = new RecordRef
{
internalId = "111111",
type = RecordType.invoice,
typeSpecified = true
};
ReadResponse readResponse = _service.get(invoiceRef);
}//eof
How would I get the entirety of the readResponse as a file? It is an XML file on the front-end...can I download / read that to a file at the end of this script? I don't know if its being treated as a stream here or not either, which would make it a little easier to just turn it into a file.

In your example, a request would be made to NetSuite and the response will be loaded into your "readResponse" variable as a ReadResponse class. You would then need to convert the record returned into an Invoice:
Invoice invoiceRecord = (Invoice)readResponse.record;
if you want to write the response to a file, you could do something like this:
ReadResponse readResponse = _service.get(invoiceRef);
FileStream fs = System.IO.File.Create("response.xml");
XmlSerializer writer = new XmlSerializer(typeof(ReadResponse));
writer.Serialize(fs, readResponse);
fs.Close();

Related

Convert XmlWriter to Stream / char / byte []

I have an asp.net/C#/Blazor environment, where a button generates an XML with a specific class. With XML Writer, I can make the file, and even can save/download it, but it goes to the server-side (It must to be downloaded on client-side. please, do not argue about it).
I know Blazor implemented some instant download (https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-6.0) and it works perfect with blank/new files, but the problem is, I don't know how to "pass" or convert my previously generated XML with XML Writer method, because Blazor method(s) only allow Stream, char or byte Arrays downloads.
When I tried to convert it, the error
Some of my code is:
protected async Task CreateXmlFile(int correlativo,string idDocumento, string siglaDocumento, List<DocumentoXML> documentos = null, List<SignersXML> signersXMLs = null,
List<ContentXMLComplemento> complementos = null,
List<SignersXMLComplemento> signersComplemento = null)
{
_xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
Encoding = new UTF8Encoding(false)
};
string fullPath= "";
XmlWriter writer;
XmlSerializer serializer;
var documentoIngresoRaiz = new DocumentoIngresoRaiz
{
Content_XML = new List<ContentXML>
{
new ContentXML
{
sve_XML = new List<sveXML>
{
new sveXML
{
Documento_XML = documentos
}
}
}
},
Signers_XML = signersXMLs
};
fullPath = $"{mainPath}Ingreso-{correlativo}.xml";
var fileName = $"Ingreso-{correlativo}.xml";
writer = XmlWriter.Create(fullPath, _xmlWriterSettings);
serializer = new XmlSerializer(typeof(DocumentoIngresoRaiz));
serializer.Serialize(writer, documentoIngresoRaiz);
writer.Close();
//I've been trying with these 3 Blazor method lines, to send my xml as stream
var fileStream = new MemoryStream(writer);
using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}
Error CS1503: Argument 1: cannot convert from 'System.Xml.XmlWriter' to 'byte[]'
I've been looking all around StackOverflow and the Internet with no success.
I found some similar posts (I want to download XML file in C# which I created using XmlWriter.Create() on user's system) (How to get a Stream from an XMLWriter?), but they couldn't solve my problem. Any help or tip is welcome. Thank you in advance!
Since there was no way to convert the already generated XML file to byte/stream/char array, I found out that the solution was:
saving this XML file on server-side
and then immediately download it to local machine, via JavaScript code (pasted below), passing the fileURL (location of file on the server) and fileName (name of the file)
await JS.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);
function triggerFileDownload(fileName, url) {
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}

Ignore warning when creating excel from Memory Stream in C# MVC

I am creating excel file by convert .cshtml MVC Razor page into bytes and then converting it into Memory stream to create excel, but when opening that excel file I am getting a warning message, I want to ignore it or you can say remove it. How can I do that ( don't want to use External library like NPOI or EPPlus)
Here is my C# Code
var html = FakeController.RenderViewToString2(ControllerContext, "~/Views/Report/DistirbuterPriceListExcel.cshtml", distributerListModel, true);
var bytes = Encoding.ASCII.GetBytes(html);
MemoryStream ms = new MemoryStream(bytes);
var root = Server.MapPath("~/Uploads/ReportPDFFiles/");
var pathtosave = "../../Uploads/ReportPDFFiles/";
var CompURL = "";
var FileName = "";
var pdfname = String.Format("{0}.xls", Guid.NewGuid().ToString());
var pdfCompleteName = "Distributer-List.xls";
var path = Path.Combine(root, pdfname);
var path2 = Path.Combine(root, pdfCompleteName);
path = Path.GetFullPath(path);
path2 = Path.GetFullPath(path2);
var fileStream2 = new FileStream(path2, FileMode.Create, FileAccess.Write);
fileStream2.Write(bytes, 0, bytes.Length);
fileStream2.Close();
CompURL = pathtosave + pdfCompleteName;
FileName = pdfCompleteName;
return Json(new { CompURL, FileName }, JsonRequestBehavior.AllowGet);
Where distributerListModel= Model passed to view, I want to return url in JSON response.
I can create excel file, but it is opening and showing results, but showing warning error "the file you are trying to open is in different format", here is the image
I want to ignore or remove the above error, how can I do that?
As the HTML layout of table is quite complicated I don't want to use EPPlus and directly want to convert html/css code into excel.

how to load xml file in c#

Can any one give me a proper explain why i am unable to get updated XML content from URL. I have a XML file which will frequently update. But in my application i am getting old data. Until i restart my application.
Here i am placing my code that i have tried
XmlDocument doc = new XmlDocument();;
string str;
using (var wc = new WebClient())
{
str = wc.DownloadString(location.AbsoluteUri);
}
doc.LoadXml(str);
And also tried with below code
WebRequest req = HttpWebRequest.Create("url");
using (Stream stream = req.GetResponse().GetResponseStream())
{
xmldoc.Load(stream);
}
I got to know that raw git hub take time to update in all servers so it is taking time to update. So you can use other web services to get result you want.

Xamarin android data saving to json file

I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}

How to Download File

I have been following these links all listed below, i found the best way to write this SMALL create Excel and Download function. ( Using EPPlus for Excel )
Download file of any type in Asp.Net MVC using FileResult? + How to convert an Stream into a byte[] in C#?
Using a FileStreamResult with a MemoryStream in ASP.NET MVC 3
Writing A Custom File Download Action Result For ASP.NET MVC
It runs through the code perfectly without error every time I run this but does not "Kick out" the file to be downloaded ( in a save as dialogue or w/e ).
public ActionResult ShowReport()
{
using (var stream = new MemoryStream())
{
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
ws.Cells["A1"].Value = "Sample 1";
ws.Cells["A1"].Style.Font.Bold = true;
var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
shape.SetPosition(50, 200);
shape.SetSize(200, 100);
shape.Text = "Sample 1 text text text";
var fileDownloadName = "sample.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//System.Net.Mime.MediaTypeNames.Application.Octet
var fileStream = new MemoryStream();
pck.SaveAs(fileStream);
fileStream.Position = 0;
var fsr = new FileStreamResult(fileStream, contentType);
fsr.FileDownloadName = fileDownloadName;
byte[] fileBytes = ReadToEnd(fileStream);
string fileName = "example";
return File(fileBytes, contentType, fileName);
}
}
What am I doing wrong / missing? - Must i write that Dialogue myself?
PN: I have also attempted this way
byte[] fileBytes = ReadToEnd(fileStream);
string fileName = "example";
return File(fileBytes, contentType, fileName);
ofcourse i had to figure out how to convert Stream to Byte but it also did not show anything.
Image of Chrome's Network Development Tool
Sorry about the small image ( if you can't see it scroll in with ctl+MouseWheel ) if your in a supporting browswer.
(In response to the comment thread above.)
From the image posted it looks like the actual file request (the last one in the list) is coming from JavaScript code instead of from a normal document-level request. Given this, it's highly likely that the server-side code is working correctly and returning the correct response.
However, since it's an AJAX request, the browser doesn't actually know what to do with the response. There are some potential solutions here. Ideally, you'll want to make this a normal request and remove AJAX from the picture if possible. If that's not an option, you can still initiate a document-level request from JavaScript. Something as simple as this:
window.location = '#Url.Action("Method", "Controller")';
This would be initiated from JavaScript code as it currently is, but would be for the whole browser instead of an AJAX request. That should do the trick.
Using the memory stream you have you can simple pass that to the Response object once you have saved the Excel Package
Code:
Response.AddHeader("content-disposition", "attachment;filename=FILENAME.xlsx")
Response.Charset = String.Empty
Response.ContentType = "application/ms-excel"
Response.BinaryWrite(stream.ToArray())
Response.End()

Categories

Resources