wait for database files to be released before trying to write in them
continuous-integration/drone/push Build is passing Details

master
Maxime BATISTA 2 years ago
parent e6ccd28f20
commit d472579ccf

@ -76,38 +76,38 @@ namespace LocalEndpoint.Data
return usersData[user].Rates[recipe];
}
public async void InsertInUserList(Guid userId, Guid recipeId, uint persAmount)
public void InsertInUserList(Guid userId, Guid recipeId, uint persAmount)
{
usersData[userId].RecipesList[recipeId] = persAmount;
Save(USERS_FILENAME, USERS_SERIALIZER, usersData);
}
public async void RemoveFromUserList(Guid userId, Guid recipeId)
public void RemoveFromUserList(Guid userId, Guid recipeId)
{
usersData[userId].RecipesList.Remove(recipeId);
Save(USERS_FILENAME, USERS_SERIALIZER, usersData);
}
public async void InsertRecipe(Recipe recipe)
public void InsertRecipe(Recipe recipe)
{
recipesData[recipe.Info.Id] = new RecipeData(recipe.Info, recipe.Owner.Id, recipe.Ingredients, recipe.Steps);
Save(RECIPES_FILENAME, RECIPES_SERIALIZER, recipesData);
}
public async void InsertUser(User user)
public void InsertUser(User user)
{
usersData[user.Id] = new UserData(user, new Dictionary<Guid, RecipeRate>(), new Dictionary<Guid, uint>());
Save(USERS_FILENAME, USERS_SERIALIZER, usersData);
}
public async void InsertRate(Guid userId, Guid recipeId, RecipeRate rate)
public void InsertRate(Guid userId, Guid recipeId, RecipeRate rate)
{
usersData[userId].Rates[recipeId] = rate;
Save(USERS_FILENAME, USERS_SERIALIZER, usersData);
}
public async void RemoveRecipe(Guid id)
public void RemoveRecipe(Guid id)
{
recipesData.Remove(id);
Save(RECIPES_FILENAME, RECIPES_SERIALIZER, recipesData);
@ -154,8 +154,35 @@ namespace LocalEndpoint.Data
private async void Save<K, T>(string fileName, DataContractSerializer serializer, Dictionary<K, T> dict)
{
string json = JsonSerializer.Serialize(dict);
File.WriteAllText(dbPath + "/" + fileName, json);
using (var stream = WaitForFile(fileName, FileMode.Open, FileAccess.Write, FileShare.Write))
{
var bytes = Encoding.ASCII.GetBytes(json);
await stream.WriteAsync(bytes, 0, bytes.Length);
}
}
// This is a workaround function to wait for a file to be released before opening it.
// This was to fix the Save method that used to throw sometimes as the file were oftenly being scanned by the androids' antivirus.
// Simply wait until the file is released and return it. This function will never return until
private static FileStream WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share)
{
for (int attempt = 0 ; attempt < 20; attempt++) //20 attempts equals to 2 seconds of wait
{
FileStream? fs = null;
try
{
fs = new FileStream(fullPath, mode, access, share);
return fs;
}
catch (IOException)
{
if (fs != null)
fs.Dispose();
Thread.Sleep(100);
}
}
throw new TimeoutException("Could not access file '" + fullPath + "', maximum attempts reached.");
}
}
}

Loading…
Cancel
Save