From a8b93937648b5b7aaae0eb1aa278fbe1734082fa Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Wed, 20 Sep 2023 14:40:54 +0400 Subject: [PATCH 01/10] =?UTF-8?q?=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=BB=20?= =?UTF-8?q?=D0=B2=D1=81=D0=B5=20=D0=B8=D0=BD=D1=82=D0=B5=D1=80=D1=84=D0=B5?= =?UTF-8?q?=D0=B9=D1=81=D1=8B=20=D0=B8=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CSharpEducation.sln | 8 +++++++- Task4/DataBaseAdapter.cs | 12 ++++++++++++ Task4/EntityAdapter.cs | 12 ++++++++++++ Task4/FileAdapter.cs | 7 +++++++ Task4/IEntity.cs | 12 ++++++++++++ Task4/IRepository.cs | 12 ++++++++++++ Task4/Task4.csproj | 9 +++++++++ 7 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 Task4/DataBaseAdapter.cs create mode 100644 Task4/EntityAdapter.cs create mode 100644 Task4/FileAdapter.cs create mode 100644 Task4/IEntity.cs create mode 100644 Task4/IRepository.cs create mode 100644 Task4/Task4.csproj diff --git a/CSharpEducation.sln b/CSharpEducation.sln index 6b4d357..212d885 100644 --- a/CSharpEducation.sln +++ b/CSharpEducation.sln @@ -9,7 +9,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Task2", "Task2\Task2.csproj EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Practice", "Practice\Practice.csproj", "{F5E2E1BD-7248-4069-B991-520505CFDDC1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Task3", "Task3\Task3.csproj", "{70A7F1E7-2B00-4244-A0E2-55D56FDD0DB1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Task3", "Task3\Task3.csproj", "{70A7F1E7-2B00-4244-A0E2-55D56FDD0DB1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Task4", "Task4\Task4.csproj", "{9029EB45-ABCC-4879-9802-06FB2702E70F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -33,6 +35,10 @@ Global {70A7F1E7-2B00-4244-A0E2-55D56FDD0DB1}.Debug|Any CPU.Build.0 = Debug|Any CPU {70A7F1E7-2B00-4244-A0E2-55D56FDD0DB1}.Release|Any CPU.ActiveCfg = Release|Any CPU {70A7F1E7-2B00-4244-A0E2-55D56FDD0DB1}.Release|Any CPU.Build.0 = Release|Any CPU + {9029EB45-ABCC-4879-9802-06FB2702E70F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9029EB45-ABCC-4879-9802-06FB2702E70F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9029EB45-ABCC-4879-9802-06FB2702E70F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9029EB45-ABCC-4879-9802-06FB2702E70F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Task4/DataBaseAdapter.cs b/Task4/DataBaseAdapter.cs new file mode 100644 index 0000000..cd1fada --- /dev/null +++ b/Task4/DataBaseAdapter.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Task4 +{ + internal class DataBaseAdapter + { + } +} diff --git a/Task4/EntityAdapter.cs b/Task4/EntityAdapter.cs new file mode 100644 index 0000000..de4994a --- /dev/null +++ b/Task4/EntityAdapter.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Task4 +{ + internal class EntityAdapter + { + } +} diff --git a/Task4/FileAdapter.cs b/Task4/FileAdapter.cs new file mode 100644 index 0000000..8af20dd --- /dev/null +++ b/Task4/FileAdapter.cs @@ -0,0 +1,7 @@ +namespace Task4 +{ + public class Class1 + { + + } +} \ No newline at end of file diff --git a/Task4/IEntity.cs b/Task4/IEntity.cs new file mode 100644 index 0000000..5f87360 --- /dev/null +++ b/Task4/IEntity.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Task4 +{ + internal interface IEntity + { + } +} diff --git a/Task4/IRepository.cs b/Task4/IRepository.cs new file mode 100644 index 0000000..85d28c3 --- /dev/null +++ b/Task4/IRepository.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Task4 +{ + internal interface IRepository + { + } +} diff --git a/Task4/Task4.csproj b/Task4/Task4.csproj new file mode 100644 index 0000000..132c02c --- /dev/null +++ b/Task4/Task4.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + From f212c0afec7909970aef0d5eb0dbaee8020b4d0c Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Wed, 20 Sep 2023 20:01:07 +0400 Subject: [PATCH 02/10] =?UTF-8?q?=D0=9C=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B2?= =?UTF-8?q?=D1=81=D0=B5=D0=B3=D0=BE=20=D0=BF=D0=BE=D0=BD=D0=B0=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/{DataBaseAdapter.cs => DataBaseRepo.cs} | 0 Task4/{EntityAdapter.cs => EntityListRepository.cs} | 0 Task4/{FileAdapter.cs => FileRepo.cs} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Task4/{DataBaseAdapter.cs => DataBaseRepo.cs} (100%) rename Task4/{EntityAdapter.cs => EntityListRepository.cs} (100%) rename Task4/{FileAdapter.cs => FileRepo.cs} (100%) diff --git a/Task4/DataBaseAdapter.cs b/Task4/DataBaseRepo.cs similarity index 100% rename from Task4/DataBaseAdapter.cs rename to Task4/DataBaseRepo.cs diff --git a/Task4/EntityAdapter.cs b/Task4/EntityListRepository.cs similarity index 100% rename from Task4/EntityAdapter.cs rename to Task4/EntityListRepository.cs diff --git a/Task4/FileAdapter.cs b/Task4/FileRepo.cs similarity index 100% rename from Task4/FileAdapter.cs rename to Task4/FileRepo.cs From 5229964a6b2b137a1ea297a2ae7c5878c02f48c2 Mon Sep 17 00:00:00 2001 From: Alex Artsy <67740905+AlexArtsy@users.noreply.github.com> Date: Thu, 21 Sep 2023 09:02:41 +0400 Subject: [PATCH 03/10] Update README.md --- README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/README.md b/README.md index 46f813d..3af9b40 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,31 @@ ## Task1 Создать проект консольногно приложения и вывести на экран "Hello, World!". + ## Task2 ### Игра "Крестики-нолики" - Реализовано на классах - Можно менять размер поля - Навигация по полю кнопками со стрелками + + +## Task3 +### PhoneBook +* Должна быть реализована CRUD функциональность: + + Должен уметь принимать от пользователя номер и имя телефона. + + Сохранять номер в файле phonebook.txt. (При завершении программы либо при добавлении). + + Вычитывать из файла сохранённые номера. (При старте программы). + + Удалять номера. + + Получать абонента по номеру телефона. + + Получать номер телефона по имени абонента. +* Обращение к Phonebook должно быть как к классу-одиночке. +* Внутри должна быть коллекция с абонентами. +* Для обращения с абонентами нужно завести класс Abonent. С полями «номер телефона», «имя». +* Не дать заносить уже записанного абонента. + + +## Task4 +### Репозиторий сущностей +1. Создайте интерфейс IRepository для базовых операций с сущностями (CRUD) +2. Добавьте ограничение типа T интерфейсом IEntity +3. Создайте три реализации репозитория: для работы со списком сущностей в памяти, для работы с БД (саму БД можно не реализовывать), и для работы с файлами From 11b106c5a3fb8e77a2c19efcfce7449f03d40a27 Mon Sep 17 00:00:00 2001 From: Alex Artsy <67740905+AlexArtsy@users.noreply.github.com> Date: Thu, 21 Sep 2023 09:06:17 +0400 Subject: [PATCH 04/10] Update README.md: add Task5 description --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 3af9b40..70e7e3c 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ ## Task3 ### PhoneBook +Текст задания: * Должна быть реализована CRUD функциональность: + Должен уметь принимать от пользователя номер и имя телефона. + Сохранять номер в файле phonebook.txt. (При завершении программы либо при добавлении). @@ -31,6 +32,12 @@ ## Task4 ### Репозиторий сущностей +Текст задания: 1. Создайте интерфейс IRepository для базовых операций с сущностями (CRUD) 2. Добавьте ограничение типа T интерфейсом IEntity 3. Создайте три реализации репозитория: для работы со списком сущностей в памяти, для работы с БД (саму БД можно не реализовывать), и для работы с файлами + + +## Task5 +### Приложение для асинхронной загрузки файлов +Текст задания: приложение, которое загружает файлы из интернета и сохраняет их на локальном компьютере. Пользователь должен иметь возможность ввести URL-адрес файла и выбрать путь для сохранения. Решение должно использовать асинхронный код для выполнения загрузки и сохранения файлов. From dad4de537374174638dcaca2c646b184a86ebd94 Mon Sep 17 00:00:00 2001 From: Alex Artsy <67740905+AlexArtsy@users.noreply.github.com> Date: Thu, 21 Sep 2023 09:09:51 +0400 Subject: [PATCH 05/10] Update README.md: add Task6 --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 70e7e3c..85cbd2b 100644 --- a/README.md +++ b/README.md @@ -41,3 +41,8 @@ ## Task5 ### Приложение для асинхронной загрузки файлов Текст задания: приложение, которое загружает файлы из интернета и сохраняет их на локальном компьютере. Пользователь должен иметь возможность ввести URL-адрес файла и выбрать путь для сохранения. Решение должно использовать асинхронный код для выполнения загрузки и сохранения файлов. + + +## Task6 +### Тесты для Phonebook +Текст задания: Написать unit-тесты для проекта Phonebook From 27894c41d8c675b0ec342b6ed2182a83b0b650a2 Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Fri, 22 Sep 2023 19:21:59 +0400 Subject: [PATCH 06/10] =?UTF-8?q?=D0=9C=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B2?= =?UTF-8?q?=D1=81=D1=8F=D0=BA=D0=B8=D1=85=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/DataBaseRepo.cs | 39 +++++++++++++++++++++++++- Task4/EntityListRepo.cs | 52 +++++++++++++++++++++++++++++++++++ Task4/EntityListRepository.cs | 12 -------- Task4/FileRepo.cs | 51 ++++++++++++++++++++++++++++++++-- Task4/IEntity.cs | 3 +- Task4/IRepository.cs | 6 +++- Task4/Task4.csproj | 6 +++- 7 files changed, 151 insertions(+), 18 deletions(-) create mode 100644 Task4/EntityListRepo.cs delete mode 100644 Task4/EntityListRepository.cs diff --git a/Task4/DataBaseRepo.cs b/Task4/DataBaseRepo.cs index cd1fada..e8f6435 100644 --- a/Task4/DataBaseRepo.cs +++ b/Task4/DataBaseRepo.cs @@ -1,12 +1,49 @@ using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task4 { - internal class DataBaseAdapter + internal class DataBaseRepo : IRepository where T : IEntity { + #region Поля + private string connectionString; + private SqlConnection connection; + #endregion + + #region Свойства + #endregion + + #region Методы + public void Create(T entity) + { + + } + + public T Read(string id) + { + + } + + public void Update(T entity) + { + + } + + public void Delete(string id) + { + + } + #endregion + + #region Конструкторы + public DataBaseRepo(string connectionString) + { + this.connectionString = connectionString; + } + #endregion } } diff --git a/Task4/EntityListRepo.cs b/Task4/EntityListRepo.cs new file mode 100644 index 0000000..97b0d81 --- /dev/null +++ b/Task4/EntityListRepo.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace Task4 +{ + internal class EntityListRepository : IRepository where T : IEntity + { + #region Поля + #endregion + + #region Свойства + public List Storage { get; set; } + #endregion + + #region Методы + public void Create(T entity) + { + this.Storage.Add(entity); + } + + public T Read(string id) + { + return this.Storage.Find(e => e.Id == id); + } + + public void Update(T entity) + { + Storage[Storage.FindIndex(e => e.Id == entity.Id)] = entity; + } + + public void Delete(string id) + { + if (!Storage.Remove(Storage.Find(e => e.Id == id))) + { + throw new Exception("Удаление не произошло: сущность не обнаружена в памяти"); + return; + } + } + #endregion + + #region Конструкторы + public EntityListRepository(List storage) + { + this.Storage = storage; + } + #endregion + } +} diff --git a/Task4/EntityListRepository.cs b/Task4/EntityListRepository.cs deleted file mode 100644 index de4994a..0000000 --- a/Task4/EntityListRepository.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Task4 -{ - internal class EntityAdapter - { - } -} diff --git a/Task4/FileRepo.cs b/Task4/FileRepo.cs index 8af20dd..040819f 100644 --- a/Task4/FileRepo.cs +++ b/Task4/FileRepo.cs @@ -1,7 +1,54 @@ -namespace Task4 +using System.IO; +using System.Text.Json; + +namespace Task4 { - public class Class1 + public class FileRepo : IRepository where T : IEntity { + #region Поля + private readonly string filepath; + #endregion + + #region Свойства + #endregion + + #region Методы + public void Create(T entity) + { + var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + data.Add(entity); + File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + } + + public T Read(string id) + { + return JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)).Find(e => e.Id == id); + } + + public void Update(T entity) + { + var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + data[data.FindIndex(e => e.Id == entity.Id)] = entity; + File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + } + + public void Delete(string id) + { + var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + if (!data.Remove(data.Find(e => e.Id == id))) + { + throw new Exception("Удаление не произошло: сущность не обнаружена в файле"); + return; + } + File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + } + #endregion + #region Конструкторы + public FileRepo(string filepath) + { + this.filepath = filepath; + } + #endregion } } \ No newline at end of file diff --git a/Task4/IEntity.cs b/Task4/IEntity.cs index 5f87360..36206ed 100644 --- a/Task4/IEntity.cs +++ b/Task4/IEntity.cs @@ -6,7 +6,8 @@ namespace Task4 { - internal interface IEntity + public interface IEntity { + string Id { get; set; } } } diff --git a/Task4/IRepository.cs b/Task4/IRepository.cs index 85d28c3..2cfd636 100644 --- a/Task4/IRepository.cs +++ b/Task4/IRepository.cs @@ -6,7 +6,11 @@ namespace Task4 { - internal interface IRepository + public interface IRepository where T : IEntity { + void Create(T entity); + T Read(string id); + void Update(T entity); + void Delete(string id); } } diff --git a/Task4/Task4.csproj b/Task4/Task4.csproj index 132c02c..db909ea 100644 --- a/Task4/Task4.csproj +++ b/Task4/Task4.csproj @@ -1,4 +1,4 @@ - + net6.0 @@ -6,4 +6,8 @@ enable + + + + From e78a0c0972a4830dd2718e0411ce1afad4003378 Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Sat, 23 Sep 2023 09:24:12 +0400 Subject: [PATCH 07/10] =?UTF-8?q?=D0=9C=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B2?= =?UTF-8?q?=D1=81=D1=8F=D0=BA=D0=B8=D1=85=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/DataBaseRepo.cs | 60 ++++++++++++++++++++++++++++----- Task4/EntityListRepo.cs | 7 ++-- Task4/FileRepo.cs | 73 ++++++++++++++++++++++++++++++++++------- Task4/IEntity.cs | 3 ++ 4 files changed, 118 insertions(+), 25 deletions(-) diff --git a/Task4/DataBaseRepo.cs b/Task4/DataBaseRepo.cs index e8f6435..0340213 100644 --- a/Task4/DataBaseRepo.cs +++ b/Task4/DataBaseRepo.cs @@ -1,41 +1,83 @@ using System; using System.Collections.Generic; +using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; namespace Task4 { - internal class DataBaseRepo : IRepository where T : IEntity + internal class DataBaseRepo : IRepository where T : IEntity, new() { #region Поля - private string connectionString; - private SqlConnection connection; - #endregion - - #region Свойства + private readonly string connectionString; #endregion #region Методы public void Create(T entity) { - + using (SqlConnection connection = new SqlConnection(this.connectionString)) + { + SqlCommand command = new SqlCommand(); + command.CommandText = $"INSERT INTO {connection.Database}(Id, Name, Age) VALUES({entity.Id}, {entity.Name}, {entity.Age})"; + command.Connection = connection; + command.ExecuteNonQuery(); + } } public T Read(string id) { + T entity = new T(); + + using (SqlConnection connection = new SqlConnection(this.connectionString)) + { + SqlCommand command = new SqlCommand(); + command.CommandText = $"SELECT Id, Name, Age FROM {connection.Database} WHERE Id='{id}'"; + command.Connection = connection; + + using (SqlDataReader reader = command.ExecuteReader()) + { + if (reader.HasRows) + { + while (reader.Read()) + { + var Id = reader.GetString(0); + var name = reader.GetString(1); + var age = reader.GetInt32(2); + + entity.Id = Id; + entity.Name = name; + entity.Age = age; + } + } + } + } + return entity; } public void Update(T entity) { - + using (SqlConnection connection = new SqlConnection(this.connectionString)) + { + SqlCommand command = new SqlCommand(); + command.CommandText = $"UPDATE {connection.Database} SET Age={entity.Age}, Name='{entity.Name}' WHERE Id='{entity.Id}'"; + command.Connection = connection; + command.ExecuteNonQuery(); + } } public void Delete(string id) { - + using (SqlConnection connection = new SqlConnection(this.connectionString)) + { + SqlCommand command = new SqlCommand(); + command.CommandText = $"DELETE FROM {connection.Database} WHERE Id='{id}'"; + command.Connection = connection; + command.ExecuteNonQuery(); + } } #endregion diff --git a/Task4/EntityListRepo.cs b/Task4/EntityListRepo.cs index 97b0d81..15ebff6 100644 --- a/Task4/EntityListRepo.cs +++ b/Task4/EntityListRepo.cs @@ -7,11 +7,8 @@ namespace Task4 { - internal class EntityListRepository : IRepository where T : IEntity + internal class EntityListRepo : IRepository where T : IEntity { - #region Поля - #endregion - #region Свойства public List Storage { get; set; } #endregion @@ -43,7 +40,7 @@ public void Delete(string id) #endregion #region Конструкторы - public EntityListRepository(List storage) + public EntityListRepo(List storage) { this.Storage = storage; } diff --git a/Task4/FileRepo.cs b/Task4/FileRepo.cs index 040819f..cc96e34 100644 --- a/Task4/FileRepo.cs +++ b/Task4/FileRepo.cs @@ -3,44 +3,86 @@ namespace Task4 { - public class FileRepo : IRepository where T : IEntity + public class FileRepo : IRepository where T : IEntity, IDisposable { #region Поля private readonly string filepath; + private List fileData; + private bool disposed = false; + private FileInfo fileInfo; + private DateTime lastWriteTime; #endregion #region Свойства + #endregion #region Методы + #region CRUD public void Create(T entity) { - var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); - data.Add(entity); - File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + UpdateFileDataWhenChanged(); + + this.fileData.Add(entity); } public T Read(string id) { - return JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)).Find(e => e.Id == id); + UpdateFileDataWhenChanged(); + + return this.fileData.Find(e => e.Id == id); } public void Update(T entity) { - var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); - data[data.FindIndex(e => e.Id == entity.Id)] = entity; - File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + UpdateFileDataWhenChanged(); + + this.fileData[this.fileData.FindIndex(e => e.Id == entity.Id)] = entity; } public void Delete(string id) { - var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); - if (!data.Remove(data.Find(e => e.Id == id))) + UpdateFileDataWhenChanged(); + + if (!this.fileData.Remove(this.fileData.Find(e => e.Id == id))) { throw new Exception("Удаление не произошло: сущность не обнаружена в файле"); return; } - File.WriteAllText(this.filepath, JsonSerializer.Serialize(data)); + } + #endregion + + private void UpdateFileDataWhenChanged() + { + if (IsFileChanged()) + SetFileData(); + } + + private List SetFileData() + { + return JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + } + + private bool IsFileChanged() + { + return this.fileInfo.LastWriteTime != this.lastWriteTime; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposed) return; + if (disposing) + { + File.WriteAllText(this.filepath, JsonSerializer.Serialize(this.fileData)); + this.lastWriteTime = DateTime.Now; + } + disposed = true; } #endregion @@ -48,6 +90,15 @@ public void Delete(string id) public FileRepo(string filepath) { this.filepath = filepath; + this.fileInfo = new FileInfo(filepath); + this.fileData = SetFileData(); + } + #endregion + + #region Деструкторы + ~FileRepo() + { + Dispose(false); } #endregion } diff --git a/Task4/IEntity.cs b/Task4/IEntity.cs index 36206ed..79987bd 100644 --- a/Task4/IEntity.cs +++ b/Task4/IEntity.cs @@ -8,6 +8,9 @@ namespace Task4 { public interface IEntity { + // Например зададим следующие свойства. string Id { get; set; } + string Name { get; set; } + int Age { get; set; } } } From 76377a25049b8b71eefc2c00ec23b15b7381a54d Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Sat, 23 Sep 2023 09:24:37 +0400 Subject: [PATCH 08/10] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BB=20=D1=87=D1=82=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=B8=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D1=8C=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/FileRepo.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Task4/FileRepo.cs b/Task4/FileRepo.cs index cc96e34..8d301ed 100644 --- a/Task4/FileRepo.cs +++ b/Task4/FileRepo.cs @@ -13,10 +13,6 @@ public class FileRepo : IRepository where T : IEntity, IDisposable private DateTime lastWriteTime; #endregion - #region Свойства - - #endregion - #region Методы #region CRUD public void Create(T entity) From bf3684f2df537d5692d1327806187f90b28f096c Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Sat, 23 Sep 2023 09:42:02 +0400 Subject: [PATCH 09/10] =?UTF-8?q?=D0=92=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=D0=BE=D0=BC=20=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=B8=20=D1=80=D0=B5=D1=88=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D1=81=D0=B2=D0=BE=D0=B9=20"=D1=80=D0=B5=D0=BF?= =?UTF-8?q?=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D1=80=D0=B8=D0=B9=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D1=85=D1=80=D0=B0=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82=D0=B5=D0=B9=20=D0=B2?= =?UTF-8?q?=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82=D0=B8"=20=D0=B0=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=B8=D1=87=D0=B5=D1=81?= =?UTF-8?q?=D0=BA=D0=B8=D0=B9=20List?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/FileRepo.cs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/Task4/FileRepo.cs b/Task4/FileRepo.cs index 8d301ed..1eaaa7f 100644 --- a/Task4/FileRepo.cs +++ b/Task4/FileRepo.cs @@ -7,9 +7,8 @@ public class FileRepo : IRepository where T : IEntity, IDisposable { #region Поля private readonly string filepath; - private List fileData; + private EntityListRepo fileData; private bool disposed = false; - private FileInfo fileInfo; private DateTime lastWriteTime; #endregion @@ -19,32 +18,28 @@ public void Create(T entity) { UpdateFileDataWhenChanged(); - this.fileData.Add(entity); + this.fileData.Create(entity); } public T Read(string id) { UpdateFileDataWhenChanged(); - return this.fileData.Find(e => e.Id == id); + return this.fileData.Read(id); } public void Update(T entity) { UpdateFileDataWhenChanged(); - this.fileData[this.fileData.FindIndex(e => e.Id == entity.Id)] = entity; + this.fileData.Update(entity); } public void Delete(string id) { UpdateFileDataWhenChanged(); - if (!this.fileData.Remove(this.fileData.Find(e => e.Id == id))) - { - throw new Exception("Удаление не произошло: сущность не обнаружена в файле"); - return; - } + this.fileData.Delete(id); } #endregion @@ -54,14 +49,17 @@ private void UpdateFileDataWhenChanged() SetFileData(); } - private List SetFileData() + private void SetFileData() { - return JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + var data = JsonSerializer.Deserialize>(File.ReadAllText(this.filepath)); + this.fileData = new EntityListRepo(data); } private bool IsFileChanged() { - return this.fileInfo.LastWriteTime != this.lastWriteTime; + + var fileInfo = new FileInfo(this.filepath); + return fileInfo.LastWriteTime != this.lastWriteTime; } public void Dispose() @@ -86,8 +84,7 @@ protected virtual void Dispose(bool disposing) public FileRepo(string filepath) { this.filepath = filepath; - this.fileInfo = new FileInfo(filepath); - this.fileData = SetFileData(); + SetFileData(); } #endregion From 2603e79467b4c7c77d70d96bedab037f108c47dc Mon Sep 17 00:00:00 2001 From: Alex Arts Date: Mon, 25 Sep 2023 10:51:42 +0400 Subject: [PATCH 10/10] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BE=D1=82=D0=BA=D1=80=D1=8B=D1=82=D0=B8=D0=B5=20?= =?UTF-8?q?=D1=81=D0=BE=D0=B5=D0=B4=D0=B8=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=81=20=D0=91=D0=94=20=D0=B2=20=D1=8E=D0=B7=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task4/DataBaseRepo.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Task4/DataBaseRepo.cs b/Task4/DataBaseRepo.cs index 0340213..02e0f15 100644 --- a/Task4/DataBaseRepo.cs +++ b/Task4/DataBaseRepo.cs @@ -20,6 +20,7 @@ public void Create(T entity) { using (SqlConnection connection = new SqlConnection(this.connectionString)) { + connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = $"INSERT INTO {connection.Database}(Id, Name, Age) VALUES({entity.Id}, {entity.Name}, {entity.Age})"; command.Connection = connection; @@ -33,6 +34,7 @@ public T Read(string id) using (SqlConnection connection = new SqlConnection(this.connectionString)) { + connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = $"SELECT Id, Name, Age FROM {connection.Database} WHERE Id='{id}'"; command.Connection = connection; @@ -62,6 +64,7 @@ public void Update(T entity) { using (SqlConnection connection = new SqlConnection(this.connectionString)) { + connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = $"UPDATE {connection.Database} SET Age={entity.Age}, Name='{entity.Name}' WHERE Id='{entity.Id}'"; command.Connection = connection; @@ -73,6 +76,7 @@ public void Delete(string id) { using (SqlConnection connection = new SqlConnection(this.connectionString)) { + connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = $"DELETE FROM {connection.Database} WHERE Id='{id}'"; command.Connection = connection;