-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseHelper.cs
More file actions
184 lines (166 loc) · 6.87 KB
/
Copy pathDatabaseHelper.cs
File metadata and controls
184 lines (166 loc) · 6.87 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MySql.Data.MySqlClient;
namespace GroupeV
{
/// <summary>
/// Helper class for database operations and health checks
/// </summary>
public static class DatabaseHelper
{
public static string ConnectionString =>
Environment.GetEnvironmentVariable("GROUPEV_CONNECTION_STRING")
?? "Server=127.0.0.1;Port=33066;Uid=db;Pwd=db;Database=db;Connection Timeout=10;Default Command Timeout=30;";
/// <summary>
/// Check if database connection is available
/// </summary>
public static async Task<(bool success, string message)> CheckConnectionAsync()
{
try
{
using var connection = new MySqlConnection(ConnectionString);
await connection.OpenAsync();
// Verify we can actually query the database
using var command = new MySqlCommand("SELECT 1", connection);
await command.ExecuteScalarAsync();
return (true, "Database connection successful");
}
catch (MySqlException ex)
{
var errorDetail = ex.Number switch
{
0 => "Unable to connect to MySQL/MariaDB server. Please verify:\n • DDEV is running (ddev start)\n • Server is accessible on 127.0.0.1:33066",
1042 => "Cannot resolve the database host address (127.0.0.1)",
1045 => "Access denied. Check DDEV database username and password",
1049 => "Database 'db' does not exist",
_ => $"MySQL Error {ex.Number}: {ex.Message}"
};
return (false, errorDetail);
}
catch (System.Net.Sockets.SocketException sockEx)
{
return (false, $"Network Error: Cannot reach database server.\n{sockEx.Message}");
}
catch (TimeoutException)
{
return (false, "Connection timeout. Database server is not responding.");
}
catch (Exception ex)
{
return (false, $"Connection Error: {ex.Message}");
}
}
/// <summary>
/// Check if required tables exist in database
/// </summary>
public static async Task<(bool success, string message)> VerifyTablesAsync()
{
try
{
using var connection = new MySqlConnection(ConnectionString);
await connection.OpenAsync();
// Check required tables for seller application
var requiredTables = new[] { "Utilisateur", "Vendeur", "Produit", "Categorie", "Prevente" };
foreach (var tableName in requiredTables)
{
var exists = await TableExistsAsync(connection, tableName);
if (!exists)
{
return (false, $"Table '{tableName}' doesn't exist. Please ensure the database is set up correctly.");
}
}
return (true, "All required tables exist");
}
catch (Exception ex)
{
return (false, $"Table verification error: {ex.Message}");
}
}
/// <summary>
/// Check if a specific table exists
/// </summary>
private static async Task<bool> TableExistsAsync(MySqlConnection connection, string tableName)
{
var query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'db' AND table_name = @tableName";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@tableName", tableName);
var result = await command.ExecuteScalarAsync();
return Convert.ToInt32(result) > 0;
}
/// <summary>
/// Get database statistics
/// </summary>
public static async Task<DatabaseStats> GetStatsAsync()
{
try
{
using var context = new DatabaseContext();
var sellerCount = await context.Vendeurs.CountAsync();
var productCount = await context.Produits.CountAsync();
var categoryCount = await context.Categories.CountAsync();
var preventeCount = await context.Preventes.CountAsync();
return new DatabaseStats
{
SellerCount = sellerCount,
ProductCount = productCount,
CategoryCount = categoryCount,
PreventeCount = preventeCount,
Success = true
};
}
catch (Exception ex)
{
return new DatabaseStats
{
Success = false,
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Ensure database and tables are ready
/// </summary>
public static async Task<(bool success, string message)> EnsureDatabaseReadyAsync()
{
// Step 1: Check connection
var connectionResult = await CheckConnectionAsync();
if (!connectionResult.success)
{
return (false, $"Database connection failed:\n\n{connectionResult.message}\n\nPlease ensure:\n1. XAMPP MySQL is running\n2. MySQL service is started on localhost");
}
// Step 2: Verify tables
var tablesResult = await VerifyTablesAsync();
if (!tablesResult.success)
{
return (false, $"Database tables missing:\n\n{tablesResult.message}\n\nPlease:\n1. Open phpMyAdmin (http://localhost/phpmyadmin)\n2. Run the database_setup.sql script");
}
// Step 3: Test data access
try
{
var stats = await GetStatsAsync();
if (!stats.Success)
{
return (false, $"Database access error:\n\n{stats.ErrorMessage}");
}
return (true, $"Database ready: {stats.SellerCount} sellers, {stats.ProductCount} products");
}
catch (Exception ex)
{
return (false, $"Database validation error:\n\n{ex.Message}");
}
}
}
/// <summary>
/// Database statistics data class
/// </summary>
public class DatabaseStats
{
public int SellerCount { get; set; }
public int ProductCount { get; set; }
public int CategoryCount { get; set; }
public int PreventeCount { get; set; }
public bool Success { get; set; }
public string ErrorMessage { get; set; } = string.Empty;
}
}