Convert an IFile (JSON File) to MyObject - c#

I upload a JSON file with a HTML form as explained here in the first paragraph. I accept only 1 file at a time so this is my controller:
public IActionResult Upload(IFormFile file)
{
}
Now I want to convert the file containing JSON to an object. Just like this accepted answer of Cuong Le. How do I convert the file to lets say MyObject? How do i deserialize the file?
(Newtonsoft is the lib to import right?)

You can read the text from the file and then convert to JSON. You can try something like,
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<MyObject>(fileContent );
Yes, you can use Newtonsoft NuGet package for deserializing.

Related

Extracting and Sorting data from pdf using C# package

I'm working on a project where I have to extract specific text from a pdf so that I can send these info into an excel file.
I tried at first to convert my pdf into a .txt file thinking a .txt file format would be easier to convert into json.
But the result is not at all what I need (dictionary-style Json format) but instead a kind of giant messy string .
The pdf sample looks like this:
Analysis
Some text
Reference Date (Big space) 11/17/2021
Reference Price (Big space) USD 745
Client id (Big space) 4572845
I'd like to have something like this at the end:
{Analysis:Some text, Reference Date:11/17/2021, Reference Price:USD 745, Client id:4572845}
Currently the results give all the info mixed up between each others.
Here is my code:
First, I created a "Global" class where I will create the method "Extract_Row_Info_TS that will basically load the first page of the document (called a TS or Termsheet) and extract the text from the PDF and store it into a txt file called "result.txt":
class Global
{
public static void Extract_RowInfo_TS(string doc_Type, string docPath, int? nbrPage = null)
{
switch (doc_Type)
{
case "Pdf":
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
doc.LoadFromFile(docPath);
StringBuilder buffer = new StringBuilder();
//Extract text from the first page only
Spire.Pdf.PdfPageBase pagefirst = doc.Pages[0];
buffer.Append(pagefirst.ExtractText());
doc.Close();
//save text
String fileName = #"my_disk:\my_path\result.txt";
File.WriteAllText(fileName, buffer.ToString());
//Load File
System.Diagnostics.Process.Start(fileName);
break;
case "Excel":
Spire.Xls.Workbook Wb = new Spire.Xls.Workbook();
break;
case "Word":
Spire.Doc.Document doc_word = new Spire.Doc.Document();
break;
}
}
}
Come back to my main page, I call the above method "Extract_RowInfo_TS" from above Global class and when it created "result.txt" from the pdf infos, I'll try to convert this "result.txt" into a json format:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Extract_PDF_Click(object sender, EventArgs e)
{
Global.Extract_RowInfo_TS("Pdf", #"my_disk:\my_path\my_doc.pdf");
Convert_To_Json_Format(#"my_disk:\my_path\result.txt");
}
private void Convert_To_Json_Format(string baseTextFile)
{
string streamText = new StreamReader(baseTextFile).ReadToEnd();
//Serialize Json Data.
string serializeData = Serialize_into_Json(streamText);
string newFile = #"my_disk:\my_path\NEW_text_file_2.txt";
File.WriteAllText(newFile, serializeData);
System.Diagnostics.Process.Start(newFile);
}
private static string Serialize_into_Json(string json)
{
string jsonData = JsonConvert.SerializeObject(json);
return jsonData;
}
}
I'm stuck here trying to create a proper json format file (or anything alike actually, I just want to group info between them, maybe create a table first ? I don't know...) that I can use for sending into my Excel file. Any help would be much appreciated ! I'm using the Free version of Spire Nuget package v4.3.1 that contains Free Spire.PDF, Spire.Xls, Spire.Doc and more of them. But maybe there are some others solutions out there to achieve the goal I'm looking for.
Thanks in advance for helping and have a great day.

Get a Json file from a specific folder and serialize it

I need to get json file from a specific folder in my solution. the name of the json file is "plaza.json" and the folder it is in is Data. Please see image below.
How do I get this file and serialize it? I have searched for some answers but the closest is this:
using (var streamReader = new StreamReader("plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
if I use that, it doesn't see my json file
using (var streamReader = new StreamReader(Server.MapPath("~/Data/plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
This should work, haven’t test but check this how file will be accessed
Depending on you project type it can be server.mappath or hostingenvironment.mappath
If desktop app like win forms or wpf use this
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Data/plaza.json");
Make sure to put copy file if modified property in build property

Access the RAW XML data in Web API

I am using Web API to receive XML data and convert it to an Object. Which is working fine.
public void Post([FromBody] trackermessages model)
{
try
{
How do I get the RAW XML data? Is there a way to get the XML data as the Request begins or inside this action?
I tried this:
public void Post([FromBody] trackermessages model, [FromBody] string rawText)
{
try
{
But this is not allowed.
I also tried this:
public void Post([FromBody] trackermessages model)
{
try
{
var strean = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
But I get the Exception:
This method or property is not supported after
HttpRequest.GetBufferlessInputStream has been invoked.
EDIT:
I am getting the Exception:
var stream = await Request.Content.ReadAsStreamAsync();
stream.Seek(0, System.IO.SeekOrigin.Begin); // On this Line
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
This is how I did it, because I had to read the RAW data then convert to Object:
public void Post(HttpRequestMessage request)
{
// Reading data as XML string to log to files - In case message structure is changed
var xmlDoc = new XmlDocument();
xmlDoc.Load(request.Content.ReadAsStreamAsync().Result);
var str = xmlDoc.InnerXml;
// Convert to model
var model = XMLHelper.FromXml<trackermessages>(str);
}
And the XMLHelper was copied from another question on stackoverflow: https://stackoverflow.com/a/3187539/1910735
Yes, you can get the raw XML. You do need to seek back to the start of the stream since it will have been read to the end when processing the Model.
public async void Post([FromBody]TestModel value)
{
var stream = await this.Request.Content.ReadAsStreamAsync();
stream.Seek(0, System.IO.SeekOrigin.Begin);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Console.Write(text);
}
The problem then is that your application is using GetBufferlessInputStream to read uploads without buffering them. While that is good for memory usage on the server, it means that after you've read the stream once it will no longer be available.
Your stream is being read like this when populating your model. By default GetBufferedInputStream is used which is why it works for me.
I suggest that you take the raw XML as input into the action and then manually deserialize into the model. Alternatively you can switch back to accepting posted data into a buffer.
You probably followed something like this to turn it on : https://blogs.msdn.microsoft.com/kiranchalla/2012/09/04/receiving-request-file-or-data-in-streamed-mode-at-a-web-api-service/ and should undo that to turn it off.

Read Json file containing umlaut in c#

I am trying to Read Json file containing umlaut in c#, following is the format of the file:
{
"BankCodeOertlich": "59000000",
"BicOertlich": "",
"ErgaenzungName": "Außenst. Sulzbach",
"HauptstelleAussenstellen": "Außenstelle v. Finanzamt Saarbrücken Am"
}
I am using following code to read the json in c#:
public static List<T> Load<T>(string filePath)
{
using (var stream = File.OpenRead(filePath))
{
var reader = new StreamReader(stream, Encoding.UTF8);
List<T> data = JsonConvert.DeserializeObject<List<T>>(reader.ReadToEnd());
return data;
}
}
I am getting the following output:
{
"BankCodeOertlich": "59000000",
"BicOertlich": "",
"ErgaenzungName": "Au?enst. Sulzbach",
"HauptstelleAussenstellen": "Au?enstelle v. Finanzamt Saarbr?cken Am"
}
This is just a example not a actual ouput. I tried to change to Encoding of StreamReader but its not working. is there any better way to do it?
The file is not encoded in UTF8, try Encoding.GetEncoding("iso-8859-1") instead.

Reading embedded XML file c#

How can I read from an embedded XML file - an XML file that is part of a c# project?
I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.
Any idea?
Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)
Set the "Build Action" property for the XML file to "Embedded Resource".
Use the following code to retrieve the file contents at runtime:
public string GetResourceTextFile(string filename)
{
string result = string.Empty;
using (Stream stream = this.GetType().Assembly.
GetManifestResourceStream("assembly.folder."+filename))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Whenever you want to read the file contents, just use
string fileContents = GetResourceTextFile("myXmlDoc.xml");
Note that "assembly.folder" should be replaced with the project name and folder containing the resource file.
Update
Actually, assembly.folder should be replaced by the namespace in which a class created in the same folder as the XML file would have by default. This is typically defaultNamespace.folder0.folder1.folder2......
You can also add the XML file as a Resource and then address its contents with Resources.YourXMLFilesResourceName (as a string, i.e. using a StringReader).
Set the Build Action to Embedded Resource, then write the following:
using (Stream stream = typeof(MyClass).Assembly.GetManifestResourceStream("MyNameSpace.Something.xml")) {
//Read the stream
}
You can use Reflector (free from http://www.red-gate.com/products/reflector/) to find the path to the embedded XML file.
Then, it's just a matter of
Assembly a = typeof(Assembly.Namespace.Class).Assembly;
Stream s = a.GetManifestResourceStream("Assembly.Namespace.Path.To.File.xml");
XmlDocument mappingFile = new XmlDocument();
mappingFile.Load(s);
s.Close();
Add the file to the project.
Set the "Build Action" property to "Embedded Resource".
Access it this way:
GetType().Module.Assembly.GetManifestResourceStream("namespace.folder.file.ext")
Notice that the resource name string is the name of the file,
including extension, preceded by the default namespace of the project.
If the resource is inside a folder, you also have to include it in the
string.
(from http://www.dotnet247.com/247reference/msgs/1/5704.aspx, but I used it pesonally)
#3Dave really helped (up vote given), however my resource helper was in a different assembly so I did the below
public string GetResourceFileText(string filename, string assemblyName)
{
string result = string.Empty;
using (Stream stream =
System.Reflection.Assembly.Load(assemblyName).GetManifestResourceStream($"{assemblyName}.{filename}"))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Called by
GetResourceFileText("YourFileNameHere.ext", Assembly.GetExecutingAssembly().GetName().Name);

Categories