using System; using System.Collections.Generic; using System.Text; using Npgsql; using System.Collections; namespace SafeMobileLib { public class DBuserManager:DBmanager { public DBuserManager(string p_server, string p_dbname, string p_user, string p_password, string p_port) : base(p_server, p_dbname, p_user, p_password, p_port) { } public userResponse addUserToDb(USERTYPE uType, String _firstName, String _lastname, String _userName, String _password, int _backup_user_id) { userResponse resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = $"SELECT COUNT(login) FROM users WHERE login='{_userName}'"; object result = null; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { result = cmd.ExecuteScalar(); } string userid = string.Empty; if (result.ToString() == "0") { //============================== //===== INSERT users ===== //============================== command = "INSERT INTO users (user_type,firstName,lastName,login,password, backup_user_id) " + $"VALUES( {((int)uType).ToString()},'{_firstName}','{_lastname}','{_userName}','{_password}',{_backup_user_id}) RETURNING userid"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { userid = cmd.ExecuteScalar().ToString(); } //============================== //===== INSERT sip_manager ===== //============================== command = "INSERT INTO sip_manager (sip_id, id, type) " + $" VALUES( (SELECT max(sip_id) + 1 FROM sip_manager),{userid},{(int)ContactType.USER})"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } else { resp = userResponse.alreadyInDB; } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = userResponse.SQLerror; } return resp; } public userResponse deleteUser(string userName) { userResponse resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); object result = null; string command = $"SELECT COUNT(login) FROM users WHERE login='{userName}'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { result = cmd.ExecuteScalar(); } if (result.ToString() != "0") { command = $"DELETE FROM sip_manager sm USING users u WHERE sm.id = u.userid AND sm.type = {(int)ContactType.USER} AND u.login = '{userName}';" + $"DELETE FROM users where login = '{userName}';"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } else { resp = userResponse.userNotInDB; } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = userResponse.SQLerror; } return resp; } public Int32 countGeofencesForUser (int userID) { Int32 resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand($"SELECT COUNT(*) FROM zonename WHERE useridx = {userID}", connection)) { resp = Convert.ToInt32((object)cmd.ExecuteScalar()); } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = 0; } return resp; } public Int32 countLandmarksForUser(int userID) { Int32 resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand($"SELECT COUNT(*) FROM place WHERE useridx = {userID}", connection)) { resp = Convert.ToInt32((object)cmd.ExecuteScalar()); } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = 0; } return resp; } public userResponse resetallGeoFenceAndLandmarks(Int32 userID, Int32 newUserID = 0) { userResponse resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand($"UPDATE zonename SET useridx = {newUserID} WHERE useridx = {userID}", connection)) { cmd.ExecuteNonQuery(); } using (NpgsqlCommand cmd = new NpgsqlCommand($"UPDATE place SET useridx = {newUserID} WHERE useridx = {userID}", connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = userResponse.SQLerror; } return resp; } public userResponse updateUserToDb(USERTYPE uType, String _firstName, String _lastname, String _userName, String _password, Int32 _userId, int _backup_user_id) { userResponse resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); object result = null; string command = $"SELECT COUNT(login) FROM users WHERE userid = {_userId}"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { result = cmd.ExecuteScalar(); } if (Convert.ToInt32(result) > 0) { command = $"UPDATE users SET firstName='{_firstName}' " + $",lastName='{_lastname}', login='{_userName}'" + $",password='{_password}', user_type = {((int)uType).ToString()}" + $",backup_user_id = {_backup_user_id} " + $" WHERE userid= {_userId}"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } else { resp = userResponse.userNotInDB; } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = userResponse.SQLerror; } return resp; } public List getAllUsers() { List userList = new List(); try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = " SELECT firstName, lastName, login, password, userId, user_type, backup_user_id " + " FROM users where userid <> 0 ORDER BY login"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader Reader = cmd.ExecuteReader()) { while (Reader.Read()) { USERTYPE uType; if (Reader.GetInt32(5) == 0) { uType = USERTYPE.Dispatcher; } else if (Reader.GetInt32(5) == 1) { uType = USERTYPE.Admin; } else if (Reader.GetInt32(5) == 3) { uType = USERTYPE.TicketingAdmin; } else { uType = USERTYPE.LiteDispatcher; } User usr = new User() { UType = uType, FirstName = Reader.GetValue(0).ToString(), Lastname = Reader.GetValue(1).ToString(), UserName = Reader.GetValue(2).ToString(), Password = Reader.GetValue(3).ToString(), Id = Convert.ToInt32(Reader.GetValue(4)), BackupUserId = Convert.ToInt32(Reader.GetValue(6)) }; userList.Add(usr); } } } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return userList; } public Dictionary getAllUsersSpeedUnit() { Dictionary userSpeedUnit = new Dictionary(); try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = "SELECT u.userid, us.value FROM users u join \"userSettings\" us on us.user_id = u.userid " + " WHERE key = 'startUnits'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { userSpeedUnit.Add(reader.GetInt64(0), reader.GetString(1).Equals("0") ? "k" : "m"); } } } } } catch (Exception ee) { Console.WriteLine(ee.Message, ConsoleColor.Red); } return userSpeedUnit; } public List getAllUsersNames() { List userList = new List(); try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = "SELECT login FROM users where userid <> 0 ORDER by user_type"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { userList.Add(reader.GetString(0)); } } } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return userList; } public List getAllDispatcher() { List userList = new List(); try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = "SELECT firstName, lastName, login, password, userId, user_type, sm.sip_id, se.value as language" + " FROM users u " + " JOIN sip_manager sm on sm.id = u.userid " + " LEFT JOIN (SELECT us.user_id, us.key, us.value " + " FROM \"userSettings\" us WHERE us.key LIKE 'dispatcherLanguage') se on se.user_id = u.userId " + $" where u.userid != 0 and user_type != 1 and sm.type = {(int)ContactType.USER} order by login "; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader Reader = cmd.ExecuteReader()) { while (Reader.Read()) { USERTYPE uType; if (Convert.ToInt32(Reader.GetValue(5)) == 0) uType = USERTYPE.Dispatcher; else if (Convert.ToInt32(Reader.GetValue(5)) == 1) uType = USERTYPE.Admin; else if (Convert.ToInt32(Reader.GetValue(5)) == 3) uType = USERTYPE.TicketingAdmin; else uType = USERTYPE.LiteDispatcher; User usr = new User(uType, Reader.GetValue(0).ToString(), Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(), Reader.GetValue(3).ToString(), Convert.ToInt32(Reader.GetValue(4))); usr.SipID = Reader.IsDBNull(6) ? -1 : Reader.GetInt32(6); usr.Language = Reader.IsDBNull(Reader.GetOrdinal("language")) ? "en" : Reader.GetString(Reader.GetOrdinal("language")); userList.Add(usr); } } } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return userList; } public List CheckDispatcherCredentials(string userName, string password) { List userList = new List(); try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = $"SELECT firstName, lastName, login, password, userId, user_type" + $" FROM users u where user_type != 1 and login = '{userName}' and password='{password}'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader Reader = cmd.ExecuteReader()) { while (Reader.Read()) { USERTYPE uType; if (Convert.ToInt32(Reader.GetValue(5)) == 0) uType = USERTYPE.Dispatcher; else if (Convert.ToInt32(Reader.GetValue(5)) == 1) uType = USERTYPE.Admin; else if (Convert.ToInt32(Reader.GetValue(5)) == 3) uType = USERTYPE.TicketingAdmin; else uType = USERTYPE.LiteDispatcher; User usr = new User(uType, Reader.GetValue(0).ToString(), Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(), Reader.GetValue(3).ToString(), Convert.ToInt32(Reader.GetValue(4))); userList.Add(usr); } } } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return userList; } //get all users that are assigned to current vehicle public List getAllUsersForCurrentVehicle(String vehID) { List userList = new List(); string command = "SELECT firstName, lastName, login, password, userId, user_type " + " FROM users as u" + " INNER JOIN vehicle_user as vh on (vh.user_id=u.userID)" + $" WHERE vh.veh_id = {vehID} " + " AND u.user_type IN ( 0,2,3 ) " + //dispatcher , Lite Dispatcher, Ticket Admin " AND userid <> 0 " + " ORDER BY u.login"; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { USERTYPE uType = (reader.GetInt32(5) == 0) ? USERTYPE.Dispatcher : USERTYPE.Admin; User usr = new User(uType, reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString(), reader.GetValue(3).ToString(), reader.GetInt32(4)); userList.Add(usr); } } } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); } return userList; } //get all users that are not assigned to current vehicle public List getAllOtherUsersForCurrentVehicle(String vehId) { List userList = new List(); string command = "SELECT firstName, lastName, login, password, userId, user_type " + " FROM users as u " + " WHERE u.userID NOT IN " + $"( SELECT user_id FROM vehicle_user WHERE veh_id = {vehId} )" + " AND u.user_type IN (0, 2, 3 ) " //dispatcher , Lite Dispatcher, Ticket Admin + " AND userid <> 0 " + " ORDER BY u.login"; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { USERTYPE uType = (reader.GetInt32(5) == 0) ? USERTYPE.Dispatcher : USERTYPE.Admin; User usr = new User(uType, reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString(), reader.GetValue(3).ToString(), Convert.ToInt32(reader.GetValue(4))); userList.Add(usr); } } } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); } return userList; } //get user ID public int getUserId(string userLoginName) { int userid =-1; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand($"SELECT userid FROM users WHERE \"login\"='{userLoginName}'", connection)) { userid = Convert.ToInt32(cmd.ExecuteScalar()); } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return userid; } //get administrator password public string getAdminPsw() { string pass = ""; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT \"password\" FROM users WHERE \"login\"='administrator'", connection)) { pass = cmd.ExecuteScalar().ToString(); } } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } return pass; } //set default password for admin and default users public userResponse setPasswords(string adminPass, string defaultPass) { userResponse resp; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); object result = null; string command = "SELECT COUNT(login) FROM users WHERE login='administrator'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { result = cmd.ExecuteScalar(); } if (Convert.ToInt32(result) > 0) { command = $"UPDATE users SET password='{adminPass}' WHERE login='administrator'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } else { resp = userResponse.userNotInDB; } command = "SELECT COUNT(login) from users where login='default'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { result = cmd.ExecuteScalar(); } if (Convert.ToInt32(result) > 0) { command = $"UPDATE users SET password='{defaultPass}' WHERE login='default'"; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { cmd.ExecuteNonQuery(); } resp = userResponse.done; } else { resp = userResponse.userNotInDB; } } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); resp = userResponse.SQLerror; } return resp; } public Boolean CheckUserStatus(Int32 UserIdx) { Boolean ret = false; try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); Int32 temp = 0; using (NpgsqlCommand cmd = new NpgsqlCommand($"SELECT ison FROM users WHERE userid = {UserIdx}", connection)) { temp = Convert.ToInt32((object)cmd.ExecuteScalar()); } if (temp == 1) ret = true; } } catch (Exception ex) { Console.WriteLine(ex.Message, ConsoleColor.Red); } return ret; } public void SetUserStateForSipID(Int32 sipID, Boolean state) { try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = $"UPDATE users SET ison={(state == true ? 1 : 0)} " + " WHERE userid = (SELECT id FROM sip_manager WHERE sip_id = {sipID} AND type = 0) "; NpgsqlCommand cmd = new NpgsqlCommand(command, connection); { cmd.ExecuteNonQuery(); } } } catch(Exception ex) { Utils.WriteLine($"Set user state exception: {ex.Message}", ConsoleColor.Red); } } public void SetUserState(Int32 UserIdx, Boolean state) { try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); NpgsqlCommand cmd = new NpgsqlCommand($"UPDATE users SET ison = {(state == true ? 1 : 0)} WHERE userid={UserIdx}", connection); cmd.ExecuteNonQuery(); } } catch (Exception ex) { Utils.WriteLine($"Set user state {ex.Message}", ConsoleColor.Red); } } public void RefreshUserHT(ref Hashtable userHT) { try { using (NpgsqlConnection connection = new NpgsqlConnection()) { connection.ConnectionString = getConnectionString(); connection.Open(); string command = "SELECT userid, login FROM users WHERE userid <> 0 "; using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection)) { using (NpgsqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { User u = new User() { Id = reader.GetInt32(0), UserName = reader.GetString(1), Alive = true, LastUpdate = new DateTime(2010, 1, 1) }; string key = u.Id.ToString(); if (!userHT.ContainsKey(key)) userHT.Add(key, u); else { ((User)userHT[key]).UserName = u.UserName; } } } } } } catch (Exception ee) { Utils.WriteLine("RefreshUserHT error: " + ee.ToString(), ConsoleColor.Red); } } } public class User { private int id; public int Id { get { return id; } set { id = value; } } private int backup_user_id; public int BackupUserId { get { return backup_user_id; } set { backup_user_id = value; } } private int sipID; public int SipID { get { return sipID; } set { sipID = value; } } private USERTYPE uType; public USERTYPE UType { get { return uType; } set { uType = value; } } private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } private string lastname; public string Lastname { get { return lastname; } set { lastname = value; } } private string userName; public string UserName { get { return userName; } set { userName = value; } } private string password; public string Password { get { return password; } set { password = value; } } private string language; public string Language { get { return language; } set { language = value; } } private bool alive; public bool Alive { get { return alive; } set { alive = value; } } private DateTime lastUpdate; public DateTime LastUpdate { get { return lastUpdate; } set { lastUpdate = value; } } public User(USERTYPE uType,string firstN, string lastName, string userName, string password, Int32 id) { this.uType = uType; this.firstName = firstN; this.lastname = lastName; this.userName = userName; this.password = password; this.id = id; this.language = "en"; } public User() { // TODO: Complete member initialization } } public enum USERTYPE { Admin=1,Dispatcher=0,LiteDispatcher=2, TicketingAdmin=3 } public enum userResponse { done, alreadyInDB, SQLerror, userNotInDB } }