PacktPublishing / Web-Development-with-Blazor-Second-Edition

Code Repository for Web Development with Blazor Second Edition Published by Packt
MIT License
43 stars 41 forks source link

Linux Docker Container Causes Path Issues #8

Open WeirdBeardDev opened 1 year ago

WeirdBeardDev commented 1 year ago

When I created my project I enabled the Docker container feature on the Server project. Since the container is Linux based this caused a few problems when creating the directory structure for the data. While this is not referenced in the book, I figured other people may be using the Docker container feature and learning Blazor at the same time.

I updated BlogApiJsonDirectAccess.cs to use Path.Combine() instead of the Windows specific separator. With these updates it works correctly in the container on the Windows host. Well at least as far as chapter 4 anyway. 😀

public BlogApiJsonDirectAccess(IOptions<BlogApiJsonDirectAccessSetting> option)
{
    _settings = option.Value;
    if (!Directory.Exists(_settings.DataPath))
    {
        Directory.CreateDirectory(Path.Combine(_settings.DataPath));
    }
    if (!Directory.Exists(Path.Combine(_settings.DataPath, _settings.BlogPostsFolder)))
    {
        Directory.CreateDirectory(Path.Combine(_settings.DataPath, _settings.BlogPostsFolder));
    }
    if (!Directory.Exists(Path.Combine(_settings.DataPath, _settings.CategoriesFolder)))
    {
        Directory.CreateDirectory(Path.Combine(_settings.DataPath, _settings.CategoriesFolder));
    }
    if (!Directory.Exists(Path.Combine(_settings.DataPath, _settings.TagsFolder)))
    {
        Directory.CreateDirectory(Path.Combine(_settings.DataPath, _settings.TagsFolder));
    }
}
private void Load<T>(ref List<T>? list, string folder)
{
    if (list == null)
    {
        list = new();
        var fullpath = Path.Combine(_settings.DataPath, folder);
        foreach (var f in Directory.GetFiles(fullpath))
        {
            var json = File.ReadAllText(f);
            var bp = JsonSerializer.Deserialize<T>(json);
            if (bp != null)
            {
                list.Add(bp);
            }
        }
    }
}
private async Task SaveAsync<T>(List<T>? list, string folder, string filename, T item)
{
    var filepath = Path.Combine(_settings.DataPath, folder, filename);
    await File.WriteAllTextAsync(filepath, JsonSerializer.Serialize<T>(item));
    if (list is null)
    {
        list = new();
    }
    if (!list.Contains(item))
    {
        list.Add(item);
    }
}
private void DeleteAsync<T>(List<T>? list, string folder, string id)
{
    var filepath = Path.Combine(_settings.DataPath, folder, $"{id}.json");
    try
    {
        File.Delete(filepath);
    }
    catch { }
}