Reading existing json and add new record - c#

I am trying to build an app that will allow users to add new entries to a local json file. I can easily write the record to a file but I cannot get it to update it. Here is the code I have at this point:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
...
public partial class frmGvhs : Form
{
List<FacultyMember> memberList = new List<FacultyMember>();
String filename = #"C:\Users\John\test.json";
public frmGvhs()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
FacultyMember member = new FacultyMember();
member.firstName = txtFirstName.Text;
member.lastName = txtLastName.Text;
member.email = txtEmail.Text;
member.ext = txtExt.Text;
member.department = cmbDepartments.Text;
memberList.Add(member);
String json = JsonConvert.SerializeObject(memberList.ToArray());
System.IO.File.WriteAllText(filename, json);
}
private void frmGvhs_Load(object sender, EventArgs e)
{
if (System.IO.File.Exists(filename))
{
System.IO.StreamReader re = new System.IO.StreamReader(filename);
JsonTextReader reader = new JsonTextReader(re);
JsonSerializer se = new JsonSerializer();
object parsedData = se.Deserialize(reader);
String json = JsonConvert.SerializeObject(parsedData);
Console.Write(json);
}
}
}
public class FacultyMember
{
public String firstName { get; set; }
public String lastName { get; set; }
public String email { get; set; }
public String ext { get; set; }
public String department { get; set; }
public FacultyMember()
{
}
}
Now when the app loads up I see the string of the existing json data. So now since its a string I cannot work with it. Do I need to loop through the object [parsedData]? I would like to basically add the existing data to the List<FacultyMember> memberList variable.

Read file content and deserialize to memberList. Then add them and save again.
memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));
Example
class Program
{
static List<FacultyMember> memberList = new List<FacultyMember>();
static String filename = #"C:\test.json";
static void Main(string[] args)
{
Save();
Load();
}
static void AddNew()
{
FacultyMember member = new FacultyMember();
member.firstName = "Test";
member.lastName = "Test";
member.email = "test";
member.ext = "test";
member.department = "Test";
memberList.Add(member);
Save();
}
static void Save()
{
String json = JsonConvert.SerializeObject(memberList);
System.IO.File.WriteAllText(filename, json);
}
static void Load()
{
memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));
AddNew();
Save();
}
}

A couple of things:
You need to deserialize as the type of object you want then cast the result (in this case an array of FacultyMembers.
When you read from the file you should surround it with a using statement so it closes.
Here is a sample:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Foo
{
static String filename = #"C:\test.json";
public static void Save()
{
FacultyMember member = new FacultyMember();
member.firstName = Guid.NewGuid().ToString();
member.lastName = "Bar";
member.email = "Email";
member.ext = "Ext";
member.department = "Dept";
List<FacultyMember> existing = new List<FacultyMember>();
existing.AddRange(Load());
existing.Add(member);
String json = JsonConvert.SerializeObject(existing.ToArray());
System.IO.File.WriteAllText(filename, json);
}
public static FacultyMember[] Load()
{
if (System.IO.File.Exists(filename))
{
using (System.IO.StreamReader re = new System.IO.StreamReader(filename))
{
JsonTextReader reader = new JsonTextReader(re);
JsonSerializer se = new JsonSerializer();
object obj = se.Deserialize(reader, typeof (FacultyMember[]));
return (FacultyMember[]) obj;
}
}
return new FacultyMember[0];
}
}
public class FacultyMember
{
public String firstName { get; set; }
public String lastName { get; set; }
public String email { get; set; }
public String ext { get; set; }
public String department { get; set; }
public FacultyMember()
{
}
}

Related

Reading CSV file - Object Oriented way

I'd like to parse a csv file in my course that I attend, The cvs file looks like this:
john; 3.5; 32111
etc
I've created a Class for that:
class Student
{
public string name { get; set; }
public double average { get; set; }
public int social_number { get; set; }
public Student(string name, double average, int social_number)
{
this.name = name;
this.average = average;
this.social_number = social_number;
}
public void CSV_digest(string csv_line)
{
if (csv_line != "")
{
string[] chunks = csv_line.Split(';');
name = chunks[0];
average = Convert.ToDouble(chunks[1]);
social_number = Convert.ToInt32(chunks[2]);
}
}
}
I don't really know how to propagate the Student type array:
class Program
{
static void Main(string[] args)
{
StreamReader csv = new StreamReader("students.csv", Encoding.UTF8);
string[] csv_lines = csv.ReadToEnd().Split('\n');
Student[] students = new Student[csv_lines.Length - 1];
for (int i = 0; i < csv_lines.Length; i++)
{
students[i] =
}
Console.ReadKey();
}
}
Could you please help me with this? I'd really like to utilize classes.
There is really no reason to use a library when the code to read CSV is very simple. See my code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string filename = #"c:\temp\test.csv";
static void Main(string[] args)
{
StreamReader csv = new StreamReader(filename);
string line = "";
List<Student> students = new List<Student>();
while((line = csv.ReadLine()) != null)
{
students.Add(new Student(line));
}
Console.ReadKey();
}
}
class Student
{
public string name { get; set; }
public double average { get; set; }
public int social_number { get; set; }
public Student(string csv_line)
{
if (csv_line != "")
{
string[] chunks = csv_line.Split(';');
name = chunks[0];
average = Convert.ToDouble(chunks[1]);
social_number = Convert.ToInt32(chunks[2]);
}
}
}
}

How do I replace a specific line in a textfile?

Good morning Stackoverflow,
I'm developing a time tracking web application with ASP.Net / C#.
There is a "coming" button that writes in a line of a textfile this: ID;Username;Date;Time.
At the other side, there is the "leaving" button. It should replace the line with the same content but add the time of leaving. So it should be looking like this: ID;Username;Date;TimeOfComing;TimeOfLeaving.
That's the problem. How do I replace the line? Every thing (ID, user etc.) is stored in variables of a helper class named "cZeile". So, how do I replace the line by pushing the "leaving" button aka btn_geht?
Code:
namespace Zieterfassung_0._0._2pre_alpha
{
public partial class Zeiten : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung`\obj\Debug\Zeiten.txt";`
tb_User.Text = WindowsIdentity.GetCurrent().Name.ToString();
tb_Datum.Text = DateTime.Now.ToString("dd.MM.yyyy");
tb_Zeit.Text = DateTime.Now.ToString("hh:mm");
cZeile KommtDatumZeit = new cZeile();
if (File.Exists(sPath))
{
using (StreamReader sr = new StreamReader(sPath))
{
while (!sr.EndOfStream)
{
KommtDatumZeit = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
}
}
tb_Kommt.Text = KommtDatumZeit.dtKommt.ToString();
}
protected void btn_Kommt_Click(object sender, EventArgs e)
{
string ID = DateTime.Now.ToString("yyyyMMdd_hhmm");
string sAusgabeKommt = string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};;", ID, tb_User.Text, tb_Datum.Text, tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
if (!fi.Exists)
{
fi.Create().Dispose();
}
using (StreamWriter sw = File.AppendText(sPath))
{
sw.Write(sAusgabeKommt);
}
}
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sAusgabeGeht = string.Format("{0:hh:mm}", tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
Geht.Geht = DateTime.Now.ToString("hh:mm");
Geht.dtGeht = DateTime.Now;
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
}
Helper Class:
namespace Prog
{
public static class cZeiterfassung
{
public static cZeile GetZeileObjectFromZeileString(string Zeile, string Trenner)
{
cZeile ZeileReturn = new cZeile();
string[] separators = { Trenner };
string[] arZeile = Zeile.Split(separators, StringSplitOptions.None);
ZeileReturn.ID = arZeile[0];
if (arZeile[1].IndexOf("\\") != -1)
{
ZeileReturn.Domain = arZeile[1].Substring(0, arZeile[1].IndexOf("\\"));
if (arZeile[1].Length >= arZeile[1].IndexOf("\\"))
ZeileReturn.User = arZeile[1].Substring(arZeile[1].IndexOf("\\") + 1);
}
else
ZeileReturn.User = arZeile[1];
ZeileReturn.Datum = arZeile[2];
ZeileReturn.Kommt = arZeile[3];
ZeileReturn.Geht = arZeile[4];
if(!string.IsNullOrEmpty(arZeile[2]))
ZeileReturn.dtDatum = Convert.ToDateTime(arZeile[2]);
if(!string.IsNullOrEmpty(arZeile[3]))
ZeileReturn.dtKommt = Convert.ToDateTime(arZeile[3]);
if (!string.IsNullOrEmpty(arZeile[4]))
ZeileReturn.dtGeht = Convert.ToDateTime(arZeile[4]);
return ZeileReturn;
}
}//cZeiterfassung
public class cZeile
{
public string ID { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Datum { get; set; }
public string Kommt { get; set; }
public string Geht { get; set; }
public DateTime dtDatum { get; set; }
public DateTime dtKommt { get; set; }
public DateTime dtGeht { get; set; }
public string Dauer { get; set; }
}
}

c# serialise model to objectContent

I have the following class I want to serialise:
public class UpdateDoorCommand : IXmlSerializable
{
// string such as D1
public string DoorId { get; }
public string Name { get; }
public string Notes { get; }
public UpdateDoorCommand(string doorId, string name, string notes)
{
DoorId = doorId;
Name = name;
Notes = notes;
}
public UpdateDoorCommand()
{
}
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Door");
writer.WriteAttributeString("Address", "D1");
writer.WriteElementString("Name", Name);
writer.WriteElementString("Notes", Notes);
writer.WriteEndElement();
}
}
I want the output to look like this:
<Door Address="D1">
<Name>Name1</Name>
<Notes>Notes1</Notes>
</Door>
I use the following code to serialise the object:
[TestMethod]
public async Task XmlSerialisationTest()
{
var model = new UpdateDoorCommand("D1", "Name1", "Notes1");
var mediaTypeFormatters = new MediaTypeFormatterCollection();
mediaTypeFormatters.XmlFormatter.UseXmlSerializer = true;
mediaTypeFormatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = true;
var content = new ObjectContent<UpdateDoorCommand>(model, mediaTypeFormatters.XmlFormatter);
// this does not look like the type
var str = await content.ReadAsStringAsync();
}
}
However the the output of the serialisation does not give the desired results.
The xml is wrapped in an element with the classname of the object.
How can I get desired xml output using the ObjectContent class?
Note that the code needs a reference to System.Net.Http.Formatting in order to run.
I'm not sure if the two ways are compatible but try this:
[XmlRoot(ElementName = "Door", DataType = "string")]
public class UpdateDoorCommand : IXmlSerializable
{
// *snip*
public void WriteXml(XmlWriter writer)
{
//writer.WriteStartElement("Door");
writer.WriteAttributeString("Address", "D1");
writer.WriteElementString("Name", Name);
writer.WriteElementString("Notes", Notes);
//writer.WriteEndElement();
}
}
Simple with Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
UpdateDoorCommand updateDoorCommand = new UpdateDoorCommand("D1","Name1","Note1");
updateDoorCommand.WriteXml();
}
}
public class UpdateDoorCommand
{
// string such as D1
public string DoorId { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public UpdateDoorCommand(string doorId, string name, string notes)
{
DoorId = doorId;
Name = name;
Notes = notes;
}
public UpdateDoorCommand()
{
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml()
{
XElement doorCommand = new XElement("Door", new object[] {
new XAttribute("Address", DoorId),
new XElement("Name", Name),
new XElement("Notes1", Notes)
});
}
}
}

System.IO.IOException: file used by another process when try to write to file

I searched over the internet and saw many questions about it, i tried many suggestion solutions, but nothing seems to work for me (maybe i am not implementing something right)
Here is my aspx.cs code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
public partial class Default : Page
{
static List<Member> memberList = new List<Member>();
static string fileName = #"C:\Users\Nir - PC\Desktop\public\gradesClient.json";
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(fileName))
{
using (StreamReader re = new StreamReader(fileName))
{
JsonTextReader reader = new JsonTextReader(re);
JsonSerializer se = new JsonSerializer();
object parsedData = se.Deserialize(reader);
string json = JsonConvert.SerializeObject(parsedData);
Console.Write(json);
}
}
}
protected void addBtn_Click(object sender, EventArgs e)
{
memberList = JsonConvert.DeserializeObject<List<Member>>(File.ReadAllText(fileName));
Member member = new Member();
member.id = 4;
member.name = name.Value;
member.email = email.Value;
member.Date = date.Value;
member.Address = address.Value;
member.Country = country.Value;
member.Zip = zip.Value;
member.Grade = Int32.Parse(grade.Value);
member.Course = course.Value;
memberList.Add(member);
string json = JsonConvert.SerializeObject(memberList.ToArray());
File.WriteAllText(fileName, json);
}
}
public class Member
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string Date { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string Zip { get; set; }
public int Grade { get; set; }
public string Course { get; set; }
public Member()
{
}
}
the error happens when it reach to line File.WriteAllText(fileName, json);
Please help me to fix the problem,
Please provide example code.
Thanks

Read a JSON object

I'm trying to read a JSON object using JavaScriptSerializer. Currently i'm unable to read the JSON object with my code.
below is my JSON object.
{"data":[{"id":17,"name":"RedBug Project","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0}},{"id":14,"name":"RedRock","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0},"children":[{"id":16,"name":"WEB","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":14}}]}]}
Method to Read JSON
public Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in jsonObject)
{
var a = item;
dic.Add(item["id"], item["name"]);
}
return dic;
}
I need to read the below values to the dictionary
"id":17,"name":"RedBug Project"
"id":14,"name":"RedRock"
namespace WebApplication2
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = #"{""data"":[{""id"":17,""name"":""RedBug Project"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0}},{""id"":14,""name"":""RedRock"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0},""children"":[{""id"":16,""name"":""WEB"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":14}}]}]}";
ReadJSONProject(s);
}
protected Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
var data = jsonObject["data"];
foreach (var record in data)
{
var id = ((int)record["id"]).ToString();
var name = record["name"] as string;
dic.Add(id, name);
}
return dic;
}
}
}
Refer below example and modify according to your need.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Xml;
using ConsoleDemo.Controller;
using ConsoleDemo.Model;
using Microsoft.Practices.Unity;
namespace ConsoleDemo
{
class Program
{
static void Main(string[] args)
{
var data = #"{""Root"": {""data"": [{""CardName"": ""card1"",""functions"": [{""State"": ""OPEN""},{""State"": ""INHERENT""}]},{""CardName"": ""card2"",""functions"": [{""State"": ""CLOSED""},{""State"": ""INHERENT""}]}]}";
RootClass dynObj = JsonHelper.JsonDeserialize<RootClass>(data); //Get the object
Console.ReadKey();
}
}
[DataContract]
public class RootClass
{
[DataMember(Name = "Root")]
public Data Root { get; set; }
}
[DataContract]
public class Data
{
[DataMember(Name = "data")]
public List<Card> data { get; set; }
}
[DataContract]
public class Card
{
[DataMember(Name = "CardName")]
public string CardName { get; set; }
[DataMember(Name = "functions")]
public List<Function> Functions { get; set; }
}
[DataContract]
public class Function
{
[DataMember(Name = "State")]
public string State { get; set; }
}
public class JsonHelper
{
/// <summary>
/// JSON Serialization
/// </summary>
public static string JsonSerializer<T>(T t)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
ser.WriteObject(ms, t);
var jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
/// <summary>
/// JSON Deserialization
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var obj = (T)ser.ReadObject(ms);
return obj;
}
}
}
In the foreach-loop is retrieving the member "data" which is an array. You need to iterate the elements of this array to access "id" and "name."
Here is my implementation without using dynamics BTW you can use http://json2csharp.com/ to convert complex json to c# classes easily
public class Item
{
public string id { get; set; }
public string name { get; set; }
public bool can_modify { get; set; }
public string description { get; set; }
public string start_date { get; set; }
public string due_date { get; set; }
public bool is_active { get; set; }
public Item parent { get; set; }
public List<Item> children { get; set; }
}
public class RootObject
{
public List<Item> data { get; set; }
}
public Dictionary<string, string> ReadJSONProject(string jsObject)
{
var json = jsObject;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Deserialize<RootObject>(json);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var item in jsonObject.data)
{
dic.Add(item.id, item.name);
}
return dic;
}

Categories

Resources