-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSeedDataService.cs
102 lines (91 loc) · 3.43 KB
/
SeedDataService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System.Text.Json;
using BRTDataTools.App.Models;
using Microsoft.Extensions.Logging;
namespace BRTDataTools.App.Data
{
public class SeedDataService
{
private readonly ProjectRepository _projectRepository;
private readonly TaskRepository _taskRepository;
private readonly TagRepository _tagRepository;
private readonly CategoryRepository _categoryRepository;
private readonly string _seedDataFilePath = "SeedData.json";
private readonly ILogger<SeedDataService> _logger;
public SeedDataService(ProjectRepository projectRepository, TaskRepository taskRepository, TagRepository tagRepository, CategoryRepository categoryRepository, ILogger<SeedDataService> logger)
{
_projectRepository = projectRepository;
_taskRepository = taskRepository;
_tagRepository = tagRepository;
_categoryRepository = categoryRepository;
_logger = logger;
}
public async Task LoadSeedDataAsync()
{
ClearTables();
await using Stream templateStream = await FileSystem.OpenAppPackageFileAsync(_seedDataFilePath);
ProjectsJson? payload = null;
try
{
payload = JsonSerializer.Deserialize(templateStream, JsonContext.Default.ProjectsJson);
}
catch (Exception e)
{
_logger.LogError(e, "Error deserializing seed data");
}
try
{
if (payload is not null)
{
foreach (var project in payload.Projects)
{
if (project is null)
{
continue;
}
if (project.Category is not null)
{
await _categoryRepository.SaveItemAsync(project.Category);
project.CategoryID = project.Category.ID;
}
await _projectRepository.SaveItemAsync(project);
if (project?.Tasks is not null)
{
foreach (var task in project.Tasks)
{
task.ProjectID = project.ID;
await _taskRepository.SaveItemAsync(task);
}
}
if (project?.Tags is not null)
{
foreach (var tag in project.Tags)
{
await _tagRepository.SaveItemAsync(tag, project.ID);
}
}
}
}
}
catch (Exception e)
{
_logger.LogError(e, "Error saving seed data");
throw;
}
}
private async void ClearTables()
{
try
{
await Task.WhenAll(
_projectRepository.DropTableAsync(),
_taskRepository.DropTableAsync(),
_tagRepository.DropTableAsync(),
_categoryRepository.DropTableAsync());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}