How to read JSON file and display it in console app c# - c#

I have working method for saving data into JSON file.
Now i need to read that file and display in console.
What i'm missing?
Below is my code
My method for reading:
public static void Read(string path, Workspace workspace)
{
using (StreamReader file = new StreamReader(path))
{
try
{
string json = file.ReadToEnd();
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var workspace1 = JsonConvert.DeserializeObject<Workspace>(json, serializerSettings);
workspace = workspace1;
}
catch (Exception)
{
Console.WriteLine("Problem reading file");
}
}
}
In program.cs
Serializer.Save("C:\\Users\\user\\Desktop\\test.json", workspace);
Serializer.Read("C:\\Users\\user\\Desktop\\test.json", workspace);
Console.ReadKey();
On the left is my json file and on the right is what i would like to show in the console.

Correction should be made as follows
public static Workspace Read(string path)
{
using (StreamReader file = new StreamReader(path))
{
try
{
string json = file.ReadToEnd();
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
return JsonConvert.DeserializeObject<Workspace>(json, serializerSettings);
}
catch (Exception)
{
Console.WriteLine("Problem reading file");
return null;
}
}
}
static void Main(string[] args)
{
var data = Read("D:\\workspace.json");
Console.WriteLine("Hello World!");
}

You are missing the keyword ref:
public static void Read(string path, ref Workspace workspace)
That said, you should not use it. Make the function return a Workspace.

This could be little late for the answer. But Reading json became so easy with the new method File.ReadAllText();
String getStrinFromFile = File.ReadAllText("FilePathJson");
Console.WriteLine(getStrinFromFile);

Related

How do I display mysql data in csv file after I sucessfully read the data in c#

Below is my Connectionstring and sucessfully read the data. It will return total rows of my data.
private static async Task<List<OperatorErrorTransaction>> GetDevIndex()
{
try
{
var currentConnectionDev = new CurrentConnection(Configuration["ConnectionStrings:Default"], currentRequest);
Console.WriteLine("\nPress the Enter key to exit the application...\n");
var response = await currentConnectionDev.DbConnection.QuerySafeAsync<OperatorErrorTransaction>(GenerateGetDatabaseIndexQuery());
return response.ToList();
}
catch (Exception ex)
{
return new List<OperatorErrorTransaction>();
}
}
private static string GenerateGetDatabaseIndexQuery()
{
return #"SELECT * FROM test.operator_error_transaction";
}
Below is the csv CreateFile function. Right now i looking a way how to implement mysql data into the csv file.
public static void CreateFile(List<OperatorErrorTransaction> result)
{
string myFileName = String.Format("{0:yyyy-MM-dd-HHmm}{1}", DateTime.Now, ".csv");
string myFullPath = Path.Combine("D:\\", myFileName);
using (var mem = new MemoryStream())
using (StreamWriter writer = File.CreateText(myFullPath))
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.Configuration.Delimiter = ";";
csvWriter.WriteField(result);
csvWriter.NextRecord();
writer.Flush();
var result1 = Encoding.UTF8.GetString(mem.ToArray());
Console.WriteLine(result1);
}
}
I have created a class for the variables as well such as public string BetId { get; set; } etc...

An Error occured while parsing EntityName. Line 32, position 51

I've tried looking at several different methods revolving around using XDocument class to load my xml file. However, this error and other variations have been appearing. If I use the absolute path, it displays an error of it cannot find the file.
The issue is my xml file has a combination of both English and Japanese used in it. The link should allow for anyone to view the xml file.
Here is my code and xml file:
public partial class MainWindow : Window
{
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0";
public MainWindow()
{
InitializeComponent();
XMLViewer();
}
private void XMLViewer()
{
try
{
XDocument Doc = XDocument.Load(URLSource);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
The URL you use don't contain a XML document but an HTML page :
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=0
You need to change the value of dl to 1, so Dropbox will return your XML document:
https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1
As #Florian said you should use second link, but maybe you have problem to read unicode xml, so its better using Request and ResponseStream:
private string URLSource = "https://www.dropbox.com/s/nh3bfzvhpj6e3x1/JapanseEnglish.xml?dl=1";
private void XMLViewer()
{
try
{
var request = (HttpWebRequest)WebRequest.Create(URLSource);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream, true))
{
XDocument Doc = XDocument.Load(sr);
var Kanji = from WordList in Doc.Descendants("Kanji")
select new
{
Word = WordList.Element("Kanji").Value
};
foreach (var Word in Kanji)
{
JpnTxt.ItemsSource = Word.ToString();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

Mono for Android Saving data

I created a homescreen widget, that gets a table of strings from a website. Instead of getting data from web on every update, I want to save the table to the phone and than read from the file on update. I'm using Mono for Android (C#).
Here is a method for saving data to the file system using XML Serialization
public static bool SaveData<T>(Context context, string fileName, T data)
{
try
{
using (Stream stream = context.OpenFileOutput(fileName, FileCreationMode.Private))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(stream, data);
}
return true;
}
catch (Exception)
{
return false;
}
}
And here is a method for loading serialized data from the file system
public static T LoadData<T>(Context context, string fileName)
{
Java.IO.File file = context.GetFileStreamPath(fileName);
if (file.Exists())
{
using (Stream openStream = context.OpenFileInput(fileName))
{
using (StreamReader reader = new StreamReader(openStream))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
var loadedObject = serializer.Deserialize(reader);
return (T)loadedObject;
}
catch (Exception ex)
{
// TODO Handle error
return default(T);
}
}
}
}
else
{
throw new Java.IO.FileNotFoundException("Could not find file " + fileName);
}
}
Using these methods you can easily save and load any serializable object such as a string[] you retrieved from the website.
string[] data = { "one", "two", "three" };
JavaIO.SaveData(this, "SavedData.txt", data);
string[] loadedData = JavaIO.LoadData<string[]>(this, "SavedData.txt");
If it's just a simple list, then you can use System.IO.File to load/save text - and you can use something like JSON.Net to convert your list to/from text.
If your data is more incremental, then you can use SQLite instead - try the the SQLite-net ORM wrapper on GitHub

Save email message as eml using C# in Lotus Notes

I need to export (save to) hard drive my Lotus Notes emails.
I figured out the way how to save attachments to HDD, but I can't figure out the way of how to save the whole email.
The code below shows how I export attachments. Can you suggest how can I modify it to save emails?
PS- I am new to programming.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domino;
using System.Collections;
namespace ExportLotusAttachments
{
class Class1
{
public void ScanForEmails()
{
String textBox1 = "c:\\1";
NotesSession session = new NotesSession();
session.Initialize("");
NotesDbDirectory dir = null;
dir = session.GetDbDirectory("");
NotesDatabase db = null;
db = dir.OpenMailDatabase();
NotesDatabase NDb = dir.OpenMailDatabase(); //Database connection
//ArrayList that will hold names of the folders
ArrayList LotusViews2 = new ArrayList();
foreach (NotesView V in NDb.Views)
{
if (V.IsFolder && !(V.Name.Equals("($All)")))
{
NotesView getS = V;
LotusViews2.Add(getS.Name);
}
}
foreach (String obj in LotusViews2)
{
NotesDocument NDoc;
NotesView nInboxDocs = NDb.GetView(obj);
NDoc = nInboxDocs.GetFirstDocument();
String pAttachment;
while (NDoc != null)
{
if (NDoc.HasEmbedded && NDoc.HasItem("$File"))
{
object[] AllDocItems = (object[])NDoc.Items;
foreach (object CurItem in AllDocItems)
{
NotesItem nItem = (NotesItem)CurItem;
if (IT_TYPE.ATTACHMENT == nItem.type)
{
String path = textBox1;
pAttachment = ((object[])nItem.Values)[0].ToString();
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(textBox1);
}
try
{
NDoc.GetAttachment(pAttachment).ExtractFile(#path + pAttachment);
}
catch { }
}
}
}
NDoc = nInboxDocs.GetNextDocument(NDoc);
}
}
}
}
}
This post by Bob Babalan explains how to export lotus documents using Java. The same principle should work in C# or VB. The document is cnverted into MIME and written to the disk.
Or in version 8.5.3 (I think it started witn 8.5.1) you can just drag and drop it from the mail file to the file system.
I know it is a bit late, but this is, what I did. (Based on Bob Babalan)
Bobs Solution helped me alot to understand NotesMIMEEntities, but in his solution, he only traversed the MIME-Tree to the second "layer". This will traverse multiple layers.
public static void GetMIME(StreamWriter writer, NotesMIMEEntity mimeEntity)
{
try
{
string contentType = null;
string headers = null;
string content = null;
string preamble = null;
MIME_ENCODING encoding;
contentType = mimeEntity.ContentType;
headers = mimeEntity.Headers;
encoding = mimeEntity.Encoding;
// message envelope. If no MIME-Version header, add one
if (!headers.Contains("MIME-Version:"))
writer.WriteLine("MIME-Version: 1.0");
writer.WriteLine(headers);
// for multipart, usually no main-msg content...
content = mimeEntity.ContentAsText;
if (content != null && content.Trim().Length > 0)
writer.WriteLine(content);
writer.Flush();
if (contentType.StartsWith("multipart"))
{
preamble = mimeEntity.Preamble;
NotesMIMEEntity mimeChild = mimeEntity.GetFirstChildEntity();
while (mimeChild != null)
{
GetMimeChild(writer, mimeChild);
mimeChild = mimeChild.GetNextSibling();
}
}
writer.WriteLine(mimeEntity.BoundaryEnd);
writer.Flush();
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
private void GetMimeChild(StreamWriter writer, NotesMIMEEntity mimeEntity)
{
string contentType = null;
string headers = null;
string content = null;
string preamble = null;
MIME_ENCODING encoding;
contentType = mimeEntity.ContentType;
headers = mimeEntity.Headers;
encoding = mimeEntity.Encoding;
if (encoding == MIME_ENCODING.ENC_IDENTITY_BINARY)
{
mimeEntity.EncodeContent(MIME_ENCODING.ENC_BASE64);
headers = mimeEntity.Headers;
}
preamble = mimeEntity.Preamble;
writer.Write(mimeEntity.BoundaryStart);
if (!content.EndsWith("\n"))
writer.WriteLine("");
writer.WriteLine(headers);
writer.WriteLine();
writer.Write(mimeEntity.ContentAsText);
if (contentType.StartsWith("multipart"))
{
preamble = mimeEntity.Preamble;
NotesMIMEEntity mimeChild = mimeEntity.GetFirstChildEntity();
while (mimeChild != null)
{
GetMimeChild(writer, mimeChild);
mimeChild = mimeChild.GetNextSibling();
}
}
writer.Write(mimeEntity.BoundaryEnd);
writer.Flush();
}
I would call this methods like this, to save the EML-File to a given path.
using (FileStream fs = new FileStream (path,FileMode.Create,FileAccess.ReadWrite,FileShare.None))
{
using (StreamWriter writer = new StreamWriter(fs))
{
NotesMimeEntity mimeEntity = notesDocument.GetMIMEEntity();
if (mimeEntity != null)
GetMIME(writer, mimeEntity);
}
}

WCF Streaming File Transfer ON .NET 4

I need a good example on WCF Streaming File Transfer.
I have found several and tried them but the posts are old and I am wokding on .net 4 and IIS 7 so there are some problems.
Can you gives me a good and up-to-date example on that.
The following answers detail using a few techniques for a posting binary data to a restful service.
Post binary data to a RESTful application
What is a good way to transfer binary data to a HTTP REST API service?
Bad idea to transfer large payload using web services?
The following code is a sample of how you could write a RESTful WCF service and is by no means complete but does give you an indication on where you could start.
Sample Service, note that this is NOT production ready code.
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class FileService
{
private IncomingWebRequestContext m_Request;
private OutgoingWebResponseContext m_Response;
[WebGet(UriTemplate = "{appName}/{id}?action={action}")]
public Stream GetFile(string appName, string id, string action)
{
var repository = new FileRepository();
var response = WebOperationContext.Current.OutgoingResponse;
var result = repository.GetById(int.Parse(id));
if (action != null && action.Equals("download", StringComparison.InvariantCultureIgnoreCase))
{
response.Headers.Add("Content-Disposition", string.Format("attachment; filename={0}", result.Name));
}
response.Headers.Add(HttpResponseHeader.ContentType, result.ContentType);
response.Headers.Add("X-Filename", result.Name);
return result.Content;
}
[WebInvoke(UriTemplate = "{appName}", Method = "POST")]
public void Save(string appName, Stream fileContent)
{
try
{
if (WebOperationContext.Current == null) throw new InvalidOperationException("WebOperationContext is null.");
m_Request = WebOperationContext.Current.IncomingRequest;
m_Response = WebOperationContext.Current.OutgoingResponse;
var file = CreateFileResource(fileContent, appName);
if (!FileIsValid(file)) throw new WebFaultException(HttpStatusCode.BadRequest);
SaveFile(file);
SetStatusAsCreated(file);
}
catch (Exception ex)
{
if (ex.GetType() == typeof(WebFaultException)) throw;
if (ex.GetType().IsGenericType && ex.GetType().GetGenericTypeDefinition() == typeof(WebFaultException<>)) throw;
throw new WebFaultException<string>("An unexpected error occurred.", HttpStatusCode.InternalServerError);
}
}
private FileResource CreateFileResource(Stream fileContent, string appName)
{
var result = new FileResource();
fileContent.CopyTo(result.Content);
result.ApplicationName = appName;
result.Name = m_Request.Headers["X-Filename"];
result.Location = #"C:\SomeFolder\" + result.Name;
result.ContentType = m_Request.Headers[HttpRequestHeader.ContentType] ?? this.GetContentType(result.Name);
result.DateUploaded = DateTime.Now;
return result;
}
private string GetContentType(string filename)
{
// this should be replaced with some form of logic to determine the correct file content type (I.E., use registry, extension, xml file, etc.,)
return "application/octet-stream";
}
private bool FileIsValid(FileResource file)
{
var validator = new FileResourceValidator();
var clientHash = m_Request.Headers[HttpRequestHeader.ContentMd5];
return validator.IsValid(file, clientHash);
}
private void SaveFile(FileResource file)
{
// This will persist the meta data about the file to a database (I.E., size, filename, file location, etc)
new FileRepository().AddFile(file);
}
private void SetStatusAsCreated(FileResource file)
{
var location = new Uri(m_Request.UriTemplateMatch.RequestUri.AbsoluteUri + "/" + file.Id);
m_Response.SetStatusAsCreated(location);
}
}
Sample Client, note that this is NOT production ready code.
// *********************************
// Sample Client
// *********************************
private void UploadButton_Click(object sender, EventArgs e)
{
var uri = "http://dev-fileservice/SampleApplication"
var fullFilename = #"C:\somefile.txt";
var fileContent = File.ReadAllBytes(fullFilename);
using (var webClient = new WebClient())
{
try
{
webClient.Proxy = null;
webClient.Headers.Add(HttpRequestHeader.ContentMd5, this.CalculateFileHash());
webClient.Headers.Add("X-DaysToKeep", DurationNumericUpDown.Value.ToString());
webClient.Headers.Add("X-Filename", Path.GetFileName(fullFilename));
webClient.UploadData(uri, "POST", fileContent);
var fileUri = webClient.ResponseHeaders[HttpResponseHeader.Location];
Console.WriteLine("File can be downloaded at" + fileUri);
}
catch (Exception ex)
{
var exception = ex.Message;
}
}
}
private string CalculateFileHash()
{
var hash = MD5.Create().ComputeHash(File.ReadAllBytes(#"C:\somefile.txt"));
var sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
private void DownloadFile()
{
var uri = "http://dev-fileservice/SampleApplication/1" // this is the URL returned by the Restful file service
using (var webClient = new WebClient())
{
try
{
webClient.Proxy = null;
var fileContent = webClient.DownloadData(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Categories