-
Notifications
You must be signed in to change notification settings - Fork 23
/
DbHealthChecker.cs
86 lines (76 loc) · 2.42 KB
/
DbHealthChecker.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
using JPProject.Domain.Core.Exceptions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace JPProject.EntityFrameworkCore.MigrationHelper
{
public class DbHealthChecker
{
public static async Task TestConnection(DbContext context)
{
var maxAttemps = 10;
var delay = 5000;
for (int i = 0; i < maxAttemps; i++)
{
var canConnect = CanConnect(context);
if (canConnect)
{
return;
}
await Task.Delay(delay);
}
// after a few attemps we give up
throw new DatabaseNotFoundException("Error wating database. Check ConnectionString and ensure database exist");
}
public static async Task WaitForTable<T>(DbContext context) where T : class
{
var maxAttemps = 10;
var delay = 5000;
for (int i = 0; i < maxAttemps; i++)
{
var tableExist = await CheckTable<T>(context);
if (tableExist)
{
return;
}
await Task.Delay(delay);
}
// after a few attemps we give up
throw new DatabaseNotFoundException("Error wating database. Check ConnectionString and ensure database exist");
}
private static bool CanConnect(DbContext context)
{
try
{
context.Database.GetAppliedMigrations(); // Check the database connection
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Check if data table is exist in application
/// </summary>
/// <typeparam name="T">Class of data table to check</typeparam>
/// <param name="db">DB Object</param>
public static async Task<bool> CheckTableExists<T>(DbContext db) where T : class
{
await TestConnection(db);
return await CheckTable<T>(db);
}
private static async Task<bool> CheckTable<T>(DbContext db) where T : class
{
try
{
await db.Set<T>().AnyAsync();
return true;
}
catch (Exception)
{
return false;
}
}
}
}