Добавьте файлы проекта.
This commit is contained in:
64
Repositories/ContactRepository.cs
Normal file
64
Repositories/ContactRepository.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
using Microsoft.Win32;
|
||||
using System;
|
||||
using System.Runtime;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ContactsApp
|
||||
{
|
||||
public class ContactRepository : IContactRepository
|
||||
{
|
||||
List<Contact> Contacts = new ();
|
||||
|
||||
|
||||
public void AddContact(Contact contact)
|
||||
{
|
||||
CheckUnique(contact);
|
||||
Contacts.Add(contact);
|
||||
}
|
||||
|
||||
public void UpdateContact(Guid id, Contact contact)
|
||||
{
|
||||
CheckUnique(contact);
|
||||
Contact previous = GetContactById(id);
|
||||
if (previous == null)
|
||||
{
|
||||
Contacts.Add(contact);
|
||||
return;
|
||||
}
|
||||
|
||||
previous.Name = contact.Name;
|
||||
previous.Email = contact.Email;
|
||||
previous.Phone = contact.Phone;
|
||||
}
|
||||
|
||||
public void DeleteContact(Guid id)
|
||||
{
|
||||
var contact = GetContactById(id);
|
||||
if (contact == null)
|
||||
return;
|
||||
Contacts.Remove(contact);
|
||||
}
|
||||
|
||||
public Contact GetContactById(Guid id)
|
||||
{
|
||||
return Contacts.Find(x => x.Id == id);
|
||||
}
|
||||
public void LoadJSON(string json)
|
||||
{
|
||||
var list = JsonSerializer.Deserialize<List<Contact>>(json);
|
||||
Contacts.AddRange(list);
|
||||
}
|
||||
public string SaveJSON()
|
||||
{
|
||||
return JsonSerializer.Serialize(Contacts, new JsonSerializerOptions { WriteIndented = true });
|
||||
}
|
||||
|
||||
public IEnumerable<Contact> GetAll() => Contacts;
|
||||
private void CheckUnique(Contact contact)
|
||||
{
|
||||
if (Contacts.FirstOrDefault(x => x.Equals(contact)) != null)
|
||||
throw new Exception("Такой контакт уже есть");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user