/// <summary> /// Save new contact information /// </summary> /// <param name="model">contact view model</param> /// <returns>unique identifier code</returns> public int SaveContact(ContactViewModel model) { JSONReadWrite readWrite = new JSONReadWrite(); List <ContactViewModel> contacts = JsonConvert.DeserializeObject <List <ContactViewModel> >(readWrite.Read("contacts.json", "data")); if (contacts == null) { contacts = new List <ContactViewModel>(); } // get lastly inserted index- Id int index = contacts.Max(c => c.Id); // Increment by one model.Id = index + 1; // add to collection contacts.Add(model); // write to json string jSONString = JsonConvert.SerializeObject(contacts); readWrite.Write("contacts.json", "data", jSONString); return(model.Id); }
/// <summary> /// Delete existing contact information /// </summary> /// <param name="id">unique identifier code</param> /// <returns>Is delete flag</returns> public bool DeleteContact(int id) { List <ContactViewModel> contacts = new List <ContactViewModel>(); JSONReadWrite readWrite = new JSONReadWrite(); contacts = JsonConvert.DeserializeObject <List <ContactViewModel> >(readWrite.Read("contacts.json", "data")); // find by id and remove record int index = contacts.FindIndex(x => x.Id == id); contacts.RemoveAt(index); // write to json string jSONString = JsonConvert.SerializeObject(contacts); readWrite.Write("contacts.json", "data", jSONString); return(true); }
/// <summary> /// Update existing contact information /// </summary> /// <param name="model">contact view model</param> /// <returns>unique identifier</returns> public int UpdateContact(ContactViewModel model) { JSONReadWrite readWrite = new JSONReadWrite(); List <ContactViewModel> contacts = JsonConvert.DeserializeObject <List <ContactViewModel> >(readWrite.Read("contacts.json", "data")); if (contacts == null) { contacts = new List <ContactViewModel>(); } // find by id and update record int index = contacts.FindIndex(x => x.Id == model.Id); contacts[index] = model; // write to json string jSONString = JsonConvert.SerializeObject(contacts); readWrite.Write("contacts.json", "data", jSONString); return(model.Id); }