using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EgtBEAMWALL.DataLayer.DatabaseModels;
namespace EgtBEAMWALL.DataLayer.Controllers
{
public class DbController : IDisposable
{
#region Private Fields
private AdminContext adbCtx;
#endregion Private Fields
#region Public Fields
///
/// Singleton gestione
///
public static DbController man = new DbController();
#endregion Public Fields
#region Public Constructors
public DbController()
{
// Initialize database context for ADMIN
adbCtx = new AdminContext(DbConfig.ADMIN_CONNECTION_STRING);
}
#endregion Public Constructors
#region Public Methods
public bool checkCreateUser(string username, string pwd)
{
bool answ = false;
// ricerca utente...
var numUser = adbCtx
.UserList
.Where(x => x.User == username)
.ToList()
.Count;
if (numUser > 0)
{
answ = true;
}
if (!answ)
{
// creo utente
string sqlCommand = "FLUSH PRIVILEGES;";
//string sqlCommand = $"CREATE USER '{username}'@'localhost' IDENTIFIED BY '{pwd}'; GRANT ALL ON *.* TO '{username}'@'localhost'; FLUSH PRIVILEGES;";
//string sqlCommand = $"CREATE USER '{username}'@'localhost' IDENTIFIED BY '{pwd}'; GRANT ALL ON *.* TO '{username}'@'localhost'; FLUSH PRIVILEGES;";
adbCtx.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sqlCommand);
sqlCommand = $"CREATE USER '{username}'@'localhost' IDENTIFIED BY '{pwd}';";
adbCtx.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sqlCommand);
sqlCommand = $"GRANT ALL ON *.* TO '{username}'@'localhost';";
adbCtx.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sqlCommand);
sqlCommand = "FLUSH PRIVILEGES;";
adbCtx.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.DoNotEnsureTransaction, sqlCommand);
}
return answ;
}
public void Dispose()
{
// Clear database context
adbCtx.Dispose();
}
public bool ResetDb()
{
bool answ = false;
try
{
adbCtx
.Database
.SqlQuery("CALL stp_ResetDb()");
answ = true;
adbCtx.SaveChanges();
}
catch (Exception exc)
{
Console.WriteLine($"EXCEPTION on ResetDb: {exc}");
}
return answ;
}
#endregion Public Methods
}
}