SafeDispatch/SafeMobileLIB_DLL/DBmanagers/DBvehiclesManager.cs

3265 lines
139 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Text;
using Npgsql;
using System.Collections;
using System.Data;
using System.IO;
namespace SafeMobileLib
{
public class DBvehiclesManager : DBmanager
{
public DBvehiclesManager(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)
{
}
#region ADD VEHICLE
public vehResponse addVehicleSierraToDb(string _imei, string _user, string _name, string _serialNumber, int DI, bool motoTRBO,
int gpsInterval, int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF, int arsInterval, string email, string phone, int gw_id,
int radio_gw_id, bool active, int unitType, MobileVehicles mv)
{
return AddVehicleIntoDB_Common(_imei, _user, _name, _serialNumber, DI, motoTRBO,
gpsInterval, imgID, gpsPOOR, gpsOFF, gpsMADEOFF, 0, email, phone, true, gw_id, radio_gw_id, active, unitType, mv);
}
public vehResponse addVehicleToDb(string _imei, string _user, string _name, string _serialNumber, int DI, bool motoTRBO,
int gpsInterval, int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF,int arsInterval, int gw_id,
int radio_gw_id, bool active, int unitType, MobileVehicles mv)
{
return AddVehicleIntoDB_Common(_imei, _user, _name, _serialNumber, DI, motoTRBO,
gpsInterval, imgID, gpsPOOR, gpsOFF, gpsMADEOFF, 0, "", "", false, gw_id, radio_gw_id, active, unitType, mv);
}
private vehResponse AddVehicleIntoDB_Common(string _imei, string _user, string _name, string _serialNumber, int DI, bool motoTRBO,
int gpsInterval, int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF,int arsInterval, string email, string phone, bool isSierra, int gw_id,
int radio_gw_id, bool active, int type, MobileVehicles mv)
{
string SerialNr = "";
if (!motoTRBO) SerialNr = _serialNumber;
NpgsqlCommand cmd = null;
NpgsqlTransaction transaction = null;
vehResponse resp;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
_imei = _imei.Trim();
_name = _name.TrimEnd();
cmd = new NpgsqlCommand($"SELECT count(imei) FROM subscriber WHERE imei='{_imei}'", connection);
object temp = cmd.ExecuteScalar();
if (temp.ToString() == "0")
{
string id_subscriber = "", id_vehicle = "", id_user = "";
cmd = new NpgsqlCommand("INSERT INTO vehicle (lp,name,driver_id,time_route,\"GPS_reporting_interval\",ars_interval,gps_poor,gps_off,made_off,active,type) "
+ $" VALUES('{SerialNr}','{_name}',{imgID}, 0, {gpsInterval},{arsInterval},{gpsPOOR},{gpsOFF},{gpsMADEOFF},{active},{type})", connection, transaction);
cmd.ExecuteNonQuery();
if (isSierra)
cmd = new NpgsqlCommand($"INSERT INTO subscriber (imei, phone, email) VALUES('{_imei}','{phone}','{email}')", connection, transaction);
else
cmd = new NpgsqlCommand($"INSERT INTO subscriber (imei) VALUES('{_imei}')", connection, transaction);
cmd.ExecuteNonQuery();
//get vehicle id
cmd = new NpgsqlCommand("SELECT max(id) FROM vehicle ", connection);
id_vehicle = cmd.ExecuteScalar().ToString();
//get subscriber id
cmd = new NpgsqlCommand("SELECT max(sc_id) FROM subscriber ", connection);
id_subscriber = cmd.ExecuteScalar().ToString();
//get user id
cmd = new NpgsqlCommand($"SELECT userId FROM users WHERE login ='{_user}'", connection);
id_user = cmd.ExecuteScalar().ToString();
if (id_vehicle.Length > 0 && id_subscriber.Length > 0 && id_user.Length > 0)
{
cmd = new NpgsqlCommand($"INSERT INTO vehicle_user(veh_id, user_id, assigned) VALUES({id_vehicle},{id_user},'2007-01-01')", connection, transaction);
cmd.ExecuteNonQuery();
cmd = new NpgsqlCommand($"INSERT INTO subscriber_history(sc_id, veh_id, assigned) VALUES({id_subscriber},{id_vehicle},'2007-01-01')", connection, transaction);
cmd.ExecuteNonQuery();
cmd = new NpgsqlCommand($"DELETE FROM lastpos where imei='{_imei}'", connection, transaction);
cmd.ExecuteNonQuery();
NpgsqlCommand cmd2 = new NpgsqlCommand();
cmd2.Connection = connection;
cmd2.Transaction = transaction;
cmd2.CommandText = "INSERT INTO lastpos (imei,lat,lng,speed,heading,di,dox,timeGMT) VALUES(@imei,@lat1,@lng1,0,0,0,0,0)";//42.06054,-88.02397
cmd2.Parameters.Add("@imei", NpgsqlTypes.NpgsqlDbType.Varchar).Value = _imei;//42.06054;
cmd2.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = 0.1;//42.06054;
cmd2.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = 0.1;//-88.02397;
cmd2.Prepare();
cmd2.ExecuteNonQuery();
if (!motoTRBO)
{
cmd = new NpgsqlCommand($"INSERT INTO emergdi (sc_id,DI) VALUES({id_subscriber},{DI})", connection, transaction);
cmd.ExecuteNonQuery();
}
cmd = new NpgsqlCommand("SELECT max(id) FROM subs_gateway ", connection);
string str_id_subs_gateway = cmd.ExecuteScalar().ToString();
int id_subs_gateway = 0;
int.TryParse(str_id_subs_gateway, out id_subs_gateway);
cmd = new NpgsqlCommand($"INSERT INTO subs_gateway (id, sc_id, gateway_id,radio_gw_id) VALUES( {id_subs_gateway + 1}, {id_subscriber},{(gw_id < 0 ? "null" : gw_id.ToString())},{(radio_gw_id < 0 ? "null" : radio_gw_id.ToString()) })", connection, transaction);
cmd.ExecuteNonQuery();
if (type == (int)DeviceType.SMARTPHONE)
{
string emergency = "";
if (mv.HasEmergency)
emergency = "1";
string updateSubscriberAlarm =
$"INSERT INTO \"subscriber_alarm\" (sc_id , emergency ,landmark ,\"zone\",loneworker ,speed ,email,emsound,empopup,geosound,geopopup,speedsound,speedpopup,telemsound,telempopup) VALUES ({id_subscriber},'{emergency}','','','','','',True,True,True,True,True,True,True,True);";
NpgsqlCommand cmd3 = new NpgsqlCommand();
cmd3.Connection = connection;
cmd3.Transaction = transaction;
cmd3.CommandText = "INSERT INTO subscriber_mobile (sc_id, phone_imei, first_name, last_name, company, os, phone_type, sip_pswd, has_gps, has_voice, has_text, has_ticketing, email, login, has_lone_worker, lone_worker_interval, has_man_down, has_emergency)"
+ " VALUES (@sc_id, @phone_imei, @first_name, @last_name, @company, @os, @phone_type, @sip_pswd, @has_gps, @has_voice, @has_text, @has_ticketing, @email, @login, @has_lone_worker, @lone_worker_interval, @has_man_down, @has_emergency);" + updateSubscriberAlarm;
cmd3.Parameters.Add("@sc_id", NpgsqlTypes.NpgsqlDbType.Integer).Value = Convert.ToInt32(id_subscriber);
cmd3.Parameters.Add("@phone_imei", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.IMEI;
cmd3.Parameters.Add("@first_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.FirstName;
cmd3.Parameters.Add("@last_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.LastName;
cmd3.Parameters.Add("@company", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Company;
cmd3.Parameters.Add("@os", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.OS;
cmd3.Parameters.Add("@phone_type", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.PhoneType;
cmd3.Parameters.Add("@sip_pswd", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipPswd;
cmd3.Parameters.Add("@has_gps", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasGPS;
cmd3.Parameters.Add("@has_voice", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasVoice;
cmd3.Parameters.Add("@has_text", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasText;
cmd3.Parameters.Add("@has_ticketing", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasTicketing;
cmd3.Parameters.Add("@email", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Email;
cmd3.Parameters.Add("@login", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipLogin;
cmd3.Parameters.Add("@has_lone_worker", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.IsLoneWorker;
cmd3.Parameters.Add("@lone_worker_interval", NpgsqlTypes.NpgsqlDbType.Integer).Value = mv.LoneWorkerInterval;
cmd3.Parameters.Add("@has_man_down", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasManDown;
cmd3.Parameters.Add("@has_emergency", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasEmergency;
cmd3.Prepare();
cmd3.ExecuteNonQuery();
}
cmd = new NpgsqlCommand($"INSERT INTO sip_manager (sip_id,id,type) VALUES((SELECT max(sip_id)+1 FROM sip_manager),{id_subscriber},{(int)ContactType.UNIT})", connection, transaction);
cmd.ExecuteNonQuery();
}
// commit all operations above
transaction.Commit();
resp = vehResponse.done;
}
else
{
resp = vehResponse.alreadyInDB;
}
}
}
catch (Exception ex)
{
// rollback the trasaction
transaction?.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
#endregion
#region ADD RANGE VEHICLES
public vehResponse addRangeVehicleSierraToDb(Hashtable hashlist, string _user, string _serialNumber, int DI, bool motoTRBO, int gpsInterval,
int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF, int arsInterval, string email, int gw_id, int rg_id, bool active, int type)
{
return addRangeVehicleToDb_Common(hashlist, _user, _serialNumber, DI, motoTRBO, gpsInterval,
imgID, gpsPOOR, gpsOFF, gpsMADEOFF, arsInterval, email, true,gw_id, rg_id, active, type);
}
public vehResponse addRangeVehicleToDb(Hashtable hashlist , string _user, string _serialNumber, int DI, bool motoTRBO, int gpsInterval,
int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF, int arsInterval, int gw_id, int radio_gw_id, bool active, int type)
{
return addRangeVehicleToDb_Common(hashlist, _user, _serialNumber, DI, motoTRBO, gpsInterval,
imgID, gpsPOOR, gpsOFF, gpsMADEOFF, arsInterval, "", false,gw_id,radio_gw_id, active, type);
}
public vehResponse addRangeVehicleToDb_Common(Hashtable hashlist , string _user, string _serialNumber, int DI, bool motoTRBO, int gpsInterval,
int imgID, int gpsPOOR, int gpsOFF, int gpsMADEOFF, int arsInterval, string email, bool isSierra, int gw_id, int radio_gw_id, bool active, int type)
{
string SerialNr = "";
if (!motoTRBO) SerialNr = _serialNumber;
NpgsqlCommand cmd = null;
NpgsqlTransaction transaction = null;
vehResponse resp;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
foreach (Int32 imei in hashlist.Keys)
{
String _imei = imei.ToString();
String _name = (String)hashlist[imei];
string id_subscriber = "", id_vehicle = "", id_user = "";
cmd = new NpgsqlCommand("INSERT INTO vehicle"
+ " (lp,name,driver_id,time_route,\"GPS_reporting_interval\",ars_interval,gps_poor,gps_off,made_off,active,type) VALUES('"
+ SerialNr + "' ,'" + _name + "'," + imgID + ",0," + gpsInterval.ToString() + "," + arsInterval.ToString() + "," + gpsPOOR.ToString() + "," + gpsOFF.ToString() + "," + gpsMADEOFF.ToString() + "," + active.ToString() + "," + type + ")", connection, transaction);
cmd.ExecuteNonQuery();
if (isSierra)
cmd = new NpgsqlCommand("INSERT INTO subscriber (imei, phone, email) VALUES('" + _imei + "','','" + _name + "@" + email + "')", connection, transaction);
else
cmd = new NpgsqlCommand("INSERT INTO subscriber (imei) VALUES('" + _imei + "')", connection, transaction);
cmd.ExecuteNonQuery();
//get vehicle id
cmd = new NpgsqlCommand("SELECT max(id) FROM vehicle ", connection);
id_vehicle = cmd.ExecuteScalar().ToString();
//get subscriber id
cmd = new NpgsqlCommand("SELECT max(sc_id) FROM subscriber ", connection);
id_subscriber = cmd.ExecuteScalar().ToString();
//get user id
cmd = new NpgsqlCommand("SELECT userId FROM users Where login ='" + _user + "'", connection);
id_user = cmd.ExecuteScalar().ToString();
if (id_vehicle.Length > 0 && id_subscriber.Length > 0 && id_user.Length > 0)
{
cmd = new NpgsqlCommand("INSERT INTO vehicle_user (veh_id, user_id, assigned) VALUES(" + id_vehicle + "," + id_user + ",'2007-01-01')", connection, transaction);
cmd.ExecuteNonQuery();
cmd = new NpgsqlCommand("INSERT INTO subscriber_history (sc_id, veh_id, assigned) VALUES(" + id_subscriber + "," + id_vehicle + ",'2007-01-01')", connection, transaction);
cmd.ExecuteNonQuery();
cmd = new NpgsqlCommand("DELETE FROM lastpos where imei='" + _imei + "'", connection, transaction);
cmd.ExecuteNonQuery();
NpgsqlCommand cmd2 = new NpgsqlCommand();
cmd2.Connection = connection;
cmd2.Transaction = transaction;
cmd2.CommandText = "INSERT INTO lastpos (imei,lat,lng,speed,heading,di,dox,timeGMT) VALUES('" + _imei + "',@lat1,@lng1,0,0,0,0,0)";//42.06054,-88.02397
cmd2.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = 0.1;//42.06054;
cmd2.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = 0.1;//-88.02397;
cmd2.Prepare();
cmd2.ExecuteNonQuery();
if (!motoTRBO)
{
cmd = new NpgsqlCommand("INSERT INTO emergdi (sc_id, DI) VALUES(" + id_subscriber + "," + DI.ToString() + ")", connection, transaction);
cmd.ExecuteNonQuery();
}
cmd = new NpgsqlCommand("SELECT max(id) FROM subs_gateway ", connection);
string str_id_subs_gateway = cmd.ExecuteScalar().ToString();
int id_subs_gateway = 0;
int.TryParse(str_id_subs_gateway, out id_subs_gateway);
cmd = new NpgsqlCommand($"INSERT INTO subs_gateway (id, sc_id, gateway_id,radio_gw_id) VALUES( {id_subs_gateway + 1}, {id_subscriber},{(gw_id < 0 ? "null" : gw_id.ToString())},{(radio_gw_id < 0 ? "null" : radio_gw_id.ToString()) })", connection, transaction);
cmd.ExecuteNonQuery();
if (type == (int)DeviceType.SMARTPHONE)
{
NpgsqlCommand cmd3 = new NpgsqlCommand();
cmd3.Connection = connection;
cmd3.Transaction = transaction;
cmd3.CommandText = "INSERT INTO subscriber_mobile (sc_id, phone_imei, first_name, last_name, company, os, phone_type, sip_pswd, has_gps, has_voice, has_text, has_ticketing, email, login, has_lone_worker, lone_worker_interval, has_man_down, has_emergency)"
+ " VALUES (@sc_id, @phone_imei, @first_name, @last_name, @company, @os, @phone_type, @sip_pswd, @has_gps, @has_voice, @has_text, @has_ticketing, @email, @login, @has_lone_worker, @lone_worker_interval, @has_man_down, @has_emergency)";
cmd3.Parameters.Add("@sc_id", NpgsqlTypes.NpgsqlDbType.Integer).Value = Convert.ToInt32(id_subscriber);
cmd3.Parameters.Add("@phone_imei", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@first_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@last_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@company", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@os", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@phone_type", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@sip_pswd", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "Password" + imei;
cmd3.Parameters.Add("@has_gps", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@has_voice", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@has_text", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@has_ticketing", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@email", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "";
cmd3.Parameters.Add("@login", NpgsqlTypes.NpgsqlDbType.Varchar).Value = "Login" + imei;
cmd3.Parameters.Add("@has_lone_worker", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@lone_worker_interval", NpgsqlTypes.NpgsqlDbType.Integer).Value = 1;
cmd3.Parameters.Add("@has_man_down", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Parameters.Add("@has_emergency", NpgsqlTypes.NpgsqlDbType.Boolean).Value = false;
cmd3.Prepare();
cmd3.ExecuteNonQuery();
}
cmd = new NpgsqlCommand($"INSERT INTO sip_manager (sip_id,id,type) VALUES((SELECT max(sip_id)+1 FROM sip_manager),{id_subscriber},{(int)ContactType.UNIT})", connection, transaction);
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
resp = vehResponse.done;
}
}
catch (Exception ex)
{
transaction.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
#endregion
public vehResponse deleteVehicle(string _imei)
{
vehResponse resp;
string scid = "0";
string vehid = "0";
string vehname = "0";
NpgsqlTransaction transaction = null;
try
{
//====== get subscriber id ========
scid = GetInt32Result($"SELECT sc_id FROM subscriber where imei='{_imei}'").ToString();
//====== get vehicule id ========
vehid = GetInt32Result($"SELECT veh_id FROM subscriber_history where sc_id={scid}").ToString();
//====== get vehicule name ========
vehname = GetStringResult($"SELECT name FROM vehicle WHERE id={vehid}");
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
object result = null;
using (NpgsqlCommand cmd = new NpgsqlCommand($"SELECT count(imei) FROM subscriber where imei='{_imei}'", connection))
{
result = cmd.ExecuteScalar();
}
if (result != null && result.ToString() != "0")
{
#region old DELETE UNIT
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM lastpos where imei='{_imei}'", connection))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM vehicle WHERE id={vehid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subscriber_stun WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subscriber_alarm WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM vehicle_user WHERE veh_id={vehid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subscriber_history where veh_id={vehid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM telemetry_history WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM telemetry WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subscriber WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM emergdi WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM messages WHERE sc_id={scid}", connection transaction))
//{
// cmd.ExecuteNonQuery();
//}
//// =============================
////delete alarm and SMS
//// =============================
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM speedalarm WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM emergalarm WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM geozoneinout WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM mototurbo WHERE imei='{_imei}'", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM sms WHERE sc_id_sour={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM sms WHERE sc_id_dest={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM vehicle_group WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subs_gateway WHERE sc_id = {scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM lastpos_ars WHERE imei='{_imei}'", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subscriber_mobile WHERE sc_id={scid}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM sip_manager WHERE id={scid} and type ={(int)ContactType.UNIT}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
#endregion
// commit transaction
using (NpgsqlCommand cmd = new NpgsqlCommand($"UPDATE vehicle SET is_deleted = TRUE , active = FALSE where id= {scid}", connection))
{
cmd.ExecuteNonQuery();
}
transaction.Commit();
resp = vehResponse.done;
}
else
{
resp = vehResponse.vehNontInDB;
}
}
}
catch (Exception ex)
{
// rollback trasaction
transaction?.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
public vehResponse deleteVehicleList(string _imeiList, string _IdList)
{
vehResponse resp;
NpgsqlTransaction transaction = null;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
object result = null;
using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT count(imei) FROM subscriber where imei in " + _imeiList, connection))
{
result = cmd.ExecuteScalar();
}
if (result != null && result.ToString() != "0")
{
#region old DELETE Multipe Units
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM lastpos where imei in " + _imeiList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM vehicle where id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_stun where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_alarm where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM vehicle_user where veh_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_history where veh_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
////=============================
//// telemetry
////=============================
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM telemetry_history where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM telemetry where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM emergdi where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM messages where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
////=============================
////delete alarm and SMS
////=============================
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM speedalarm where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM emergalarm where sc_id in " + _IdList, connection transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM geozoneinout where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM mototurbo where imei in " + _imeiList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM sms where sc_id_sour in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM sms where sc_id_dest in " + _IdList, connection transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM vehicle_group where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subs_gateway where sc_id in " + _IdList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM lastpos_ars where imei in " + _imeiList, connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_mobile where sc_id in" + _IdList + "", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
//using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM sip_manager where id in {_IdList} and type ={(int)ContactType.UNIT}", connection, transaction))
//{
// cmd.ExecuteNonQuery();
//}
#endregion
using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE vehicle SET is_deleted = TRUE, active = FALSE where id in " + _IdList, connection, transaction))
{
cmd.ExecuteNonQuery();
}
//=============================
// commit the transaction
//=============================
transaction.Commit();
resp = vehResponse.done;
}
else
{
resp = vehResponse.vehNontInDB;
}
}
}
catch (Exception ex)
{
//=============================
// rolback the trasaction
//=============================
transaction?.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
/// <summary>
/// Clean up DB of olds imeis that are hung up!!!!
/// </summary>
/// <returns></returns>
public List<SUID_AND_IMEI> getOrphanImeis()
{
List<SUID_AND_IMEI> suidList = new List<SUID_AND_IMEI>();
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = "SELECT sc_id ,imei FROM subscriber where sc_id NOT IN (select sc_id from subscriber_history)";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
SUID_AND_IMEI suidAndImei = new SUID_AND_IMEI(reader.GetInt32(0), reader.GetString(1));
suidList.Add(suidAndImei);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return suidList;
}
public vehResponse CleanupSC_ID(int scid)
{
vehResponse resp = vehResponse.SQLerror;
NpgsqlTransaction transaction = null;
2024-04-18 15:10:37 +00:00
using (NpgsqlConnection connection = new NpgsqlConnection())
2024-02-22 16:43:59 +00:00
{
2024-04-18 15:10:37 +00:00
try
2024-02-22 16:43:59 +00:00
{
2024-04-18 15:10:37 +00:00
2024-02-22 16:43:59 +00:00
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_stun where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber_alarm where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM emergdi where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
2024-04-18 15:10:37 +00:00
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM vehicle_group where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
2024-02-22 16:43:59 +00:00
2024-04-18 15:10:37 +00:00
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM geozoneinout where sc_id=" + scid, connection, transaction))
2024-02-22 16:43:59 +00:00
{
cmd.ExecuteNonQuery();
}
2024-04-18 15:10:37 +00:00
2024-02-22 16:43:59 +00:00
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subs_gateway where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
using (NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM subscriber where sc_id=" + scid, connection, transaction))
{
cmd.ExecuteNonQuery();
}
transaction.Commit();
resp = vehResponse.done;
}
2024-04-18 15:10:37 +00:00
catch (Exception ex)
2024-02-22 16:43:59 +00:00
{
2024-04-18 15:10:37 +00:00
try
{
transaction?.Rollback();
}
catch (Exception ex2)
{
Utils.WriteLine("COuld not roll back because: " + ex2.ToString());
}
2024-02-22 16:43:59 +00:00
2024-04-18 15:10:37 +00:00
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
2024-02-22 16:43:59 +00:00
}
return resp;
}
#region EDIT VEHICLE
public vehResponse editVehicleSierra(string _id, string _name, int _DI, string _lp, int gpsInterval, int imgID,
int gpsPOOR, int gpsOFF, int madeOFF, int arsInterval, string email, string phone, int gateway_id, int radio_gw_id, bool active, int type, MobileVehicles mv)
{
return editVehicle_Common(_id, _name, _DI, _lp, gpsInterval, imgID, gpsPOOR, gpsOFF, madeOFF, arsInterval, email, phone, true, gateway_id, radio_gw_id, active, type, mv);
}
public vehResponse editVehicle(string _id, string _name, int _DI, string _lp, int gpsInterval, int imgID,
int gpsPOOR, int gpsOFF, int madeOFF, int gateway_id, int radio_gw_id, bool active, int type, MobileVehicles mv,int arsInterval = 0)
{
return editVehicle_Common(_id, _name, _DI, _lp, gpsInterval, imgID, gpsPOOR, gpsOFF, madeOFF, arsInterval, "", "", false, gateway_id, radio_gw_id, active, type, mv);
}
public vehResponse editVehicle_Common(string _id, string _name, int _DI, string _lp, int gpsInterval, int imgID,
int gpsPOOR, int gpsOFF, int madeOFF, int arsInterval, string email, string phone, bool isSierra, int gateway_id, int radio_gw_id, bool active, int type, MobileVehicles mv)
{
vehResponse resp;
NpgsqlCommand cmd;
object updateResponse = null;
bool isDeleted = isUnitDeleted(_id);
NpgsqlTransaction transaction = null;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
//open trasaction
transaction = connection.BeginTransaction();
cmd = new NpgsqlCommand("select count(id) from vehicle where id=\'" + _id + "\'", connection);
object temp = cmd.ExecuteScalar();
cmd = new NpgsqlCommand("select sc_id from subscriber_history where veh_id=\'" + _id + "\'", connection);
object tmp_sc_id = cmd.ExecuteScalar();
if (Convert.ToInt32(temp) > 0)
{
if (isSierra)
{
cmd = new NpgsqlCommand($"UPDATE subscriber SET phone='{phone}', email='{email}' WHERE sc_id = {_id} ", connection, transaction);
cmd.ExecuteNonQuery();
}
if (isDeleted && active)
{
cmd = new NpgsqlCommand("UPDATE vehicle SET name='" + _name + "',lp='" + _lp +
"',\"GPS_reporting_interval\"=" + gpsInterval.ToString() +
",driver_id=" + imgID + ",ars_interval=" + arsInterval + ",gps_poor=" + gpsPOOR + ",gps_off=" + gpsOFF + ",made_off=" + madeOFF + ",active=" + active.ToString() + ",is_deleted= FALSE" + " where id=" + _id, connection, transaction);
cmd.ExecuteNonQuery();
}
else
{
cmd = new NpgsqlCommand("UPDATE vehicle SET name='" + _name + "',lp='" + _lp +
"',\"GPS_reporting_interval\"=" + gpsInterval.ToString() +
",driver_id=" + imgID + ",ars_interval=" + arsInterval + ",gps_poor=" + gpsPOOR + ",gps_off=" + gpsOFF + ",made_off=" + madeOFF + ",active=" + active.ToString() + " where id=" + _id, connection, transaction);
cmd.ExecuteNonQuery();
}
cmd = new NpgsqlCommand("update emergdi SET DI=" + _DI.ToString() + " where sc_id=" + Convert.ToInt32(tmp_sc_id), connection, transaction);
if (cmd.ExecuteNonQuery() == 0)
{
cmd = new NpgsqlCommand("insert into emergdi (sc_id,DI) VALUES(" + Convert.ToInt32(tmp_sc_id) + "," + _DI.ToString() + ")", connection, transaction);
cmd.ExecuteNonQuery();
}
cmd = new NpgsqlCommand($"UPDATE subs_gateway SET gateway_id = {(gateway_id < 0 ? "null" : gateway_id.ToString())}, radio_gw_id= {(radio_gw_id < 0 ? "null" : radio_gw_id.ToString()) } where sc_id =" + _id, connection, transaction);
if (cmd.ExecuteNonQuery() == 0)
{
cmd = new NpgsqlCommand("SELECT max(id) FROM subs_gateway ", connection);
string str_id_subs_gateway = cmd.ExecuteScalar().ToString();
int id_subs_gateway = 0;
int.TryParse(str_id_subs_gateway, out id_subs_gateway);
cmd = new NpgsqlCommand($"INSERT INTO subs_gateway (id, sc_id, gateway_id, radio_gw_id) VALUES( {id_subs_gateway + 1}, {tmp_sc_id}, {(gateway_id < 0 ? "null" : gateway_id.ToString())}, {(radio_gw_id < 0 ? "null" : radio_gw_id.ToString()) })", connection, transaction);
cmd.ExecuteNonQuery();
}
if (type == (int)DeviceType.SMARTPHONE)
{
if (mv.CanUpdate == true)
{
string emergency = "";
if (mv.HasEmergency)
emergency = "1";
string updateSubscriberAlarm = $"update subscriber_alarm set emergency = '{emergency}' where sc_id = {_id}";
NpgsqlCommand cmd3 = new NpgsqlCommand();
cmd3.Transaction = transaction;
cmd3.Connection = connection;
cmd3.CommandText = "UPDATE subscriber_mobile SET phone_imei=@phone_imei, first_name=@first_name, last_name=@last_name, company=@company, os=@os,"
+ " phone_type=@phone_type, sip_pswd=@sip_pswd, has_gps=@has_gps,has_voice =@has_voice, has_text=@has_text, has_ticketing=@has_ticketing,"
+ " email = @email, login = @login, has_lone_worker = @has_lone_worker, lone_worker_interval = @lone_worker_interval, has_man_down = @has_man_down, has_emergency = @has_emergency "
+ " WHERE sc_id=@sc_id "
+ " RETURNING sc_id; " + updateSubscriberAlarm;
cmd3.Parameters.Add("@sc_id", NpgsqlTypes.NpgsqlDbType.Integer).Value = Convert.ToInt32(_id);
cmd3.Parameters.Add("@phone_imei", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.IMEI;
cmd3.Parameters.Add("@first_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.FirstName;
cmd3.Parameters.Add("@last_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.LastName;
cmd3.Parameters.Add("@company", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Company;
cmd3.Parameters.Add("@os", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.OS;
cmd3.Parameters.Add("@phone_type", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.PhoneType;
cmd3.Parameters.Add("@sip_pswd", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipPswd;
cmd3.Parameters.Add("@has_gps", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasGPS;
cmd3.Parameters.Add("@has_voice", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasVoice;
cmd3.Parameters.Add("@has_text", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasText;
cmd3.Parameters.Add("@has_ticketing", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasTicketing;
cmd3.Parameters.Add("@email", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Email;
cmd3.Parameters.Add("@login", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipLogin;
cmd3.Parameters.Add("@has_lone_worker", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.IsLoneWorker;
cmd3.Parameters.Add("@lone_worker_interval", NpgsqlTypes.NpgsqlDbType.Integer).Value = mv.LoneWorkerInterval;
cmd3.Parameters.Add("@has_man_down", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasManDown;
cmd3.Parameters.Add("@has_emergency", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasEmergency;
cmd3.Prepare();
updateResponse = cmd3.ExecuteScalar();
if (updateResponse == null)
{
if (mv.HasEmergency)
emergency = "1";
updateSubscriberAlarm =
$"INSERT INTO \"subscriber_alarm\" (sc_id , emergency ,landmark ,\"zone\",loneworker ,speed ,email,emsound,empopup,geosound,geopopup,speedsound,speedpopup,telemsound,telempopup) VALUES ({_id},'{emergency}','','','','','',True,True,True,True,True,True,True,True);";
cmd3 = new NpgsqlCommand();
cmd3.Connection = connection;
cmd3.Transaction = transaction;
cmd3.CommandText = "INSERT INTO subscriber_mobile (sc_id, phone_imei, first_name, last_name, company, os, phone_type, sip_pswd, has_gps, has_voice, has_text, has_ticketing, email, login, has_lone_worker, lone_worker_interval, has_man_down, has_emergency)"
+ " VALUES (@sc_id, @phone_imei, @first_name, @last_name, @company, @os, @phone_type, @sip_pswd, @has_gps, @has_voice, @has_text, @has_ticketing, @email, @login, @has_lone_worker, @lone_worker_interval, @has_man_down, has_emergency); " + updateSubscriberAlarm;
cmd3.Parameters.Add("@sc_id", NpgsqlTypes.NpgsqlDbType.Integer).Value = Convert.ToInt32(_id);
cmd3.Parameters.Add("@phone_imei", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.IMEI;
cmd3.Parameters.Add("@first_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.FirstName;
cmd3.Parameters.Add("@last_name", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.LastName;
cmd3.Parameters.Add("@company", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Company;
cmd3.Parameters.Add("@os", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.OS;
cmd3.Parameters.Add("@phone_type", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.PhoneType;
cmd3.Parameters.Add("@sip_pswd", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipPswd;
cmd3.Parameters.Add("@has_gps", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasGPS;
cmd3.Parameters.Add("@has_voice", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasVoice;
cmd3.Parameters.Add("@has_text", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasText;
cmd3.Parameters.Add("@has_ticketing", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasTicketing;
cmd3.Parameters.Add("@email", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.Email;
cmd3.Parameters.Add("@login", NpgsqlTypes.NpgsqlDbType.Varchar).Value = mv.SipLogin;
cmd3.Parameters.Add("@has_lone_worker", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.IsLoneWorker;
cmd3.Parameters.Add("@lone_worker_interval", NpgsqlTypes.NpgsqlDbType.Integer).Value = mv.LoneWorkerInterval;
cmd3.Parameters.Add("@has_man_down", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasManDown;
cmd3.Parameters.Add("@has_emergency", NpgsqlTypes.NpgsqlDbType.Boolean).Value = mv.HasEmergency;
cmd3.Prepare();
cmd3.ExecuteNonQuery();
//}
}
}
}
transaction.Commit();
resp = vehResponse.done;
}
else
{
resp = vehResponse.vehNontInDB;
}
}
}
catch (Exception ex)
{
transaction?.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
#endregion
public vehResponse editGroupVehicle(string idlist, int _DI, string _lp, bool editGpsInterval, int gpsInterval, bool editImage, int imgID,
bool editgpsPOOR, int gpsPOOR, bool editgpsOFF, int gpsOFF, bool editmadeOFF, int madeOFF, bool editGW, RadioGateway rg, bool editActive, bool active, MobileVehicles mob, int arsInterval = 0)
{
vehResponse resp;
NpgsqlCommand cmd;
bool isDeleted;
2024-06-07 13:20:57 +00:00
string[] idListArray = idlist.Replace("(", "").Replace(")", "").Split(",".ToCharArray());
2024-02-22 16:43:59 +00:00
isDeleted = isUnitDeleted(idListArray[0]);
NpgsqlTransaction transaction = null;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
string commandText = "UPDATE vehicle SET lp='" + _lp + "'";
if (editGpsInterval) commandText += ",\"GPS_reporting_interval\"=" + gpsInterval.ToString();
if (editgpsPOOR) commandText += ",gps_poor=" + gpsPOOR;
if (editgpsOFF) commandText += ",gps_off=" + gpsOFF;
if (editmadeOFF) commandText += ",made_off=" + madeOFF;
if (editImage) commandText += ",driver_id=" + imgID.ToString();
if (isDeleted && active)
{
if (editActive) commandText += ",active=" + active.ToString() + ",is_deleted=FALSE";
}
else
{
if (editActive) commandText += ",active=" + active.ToString();
}
commandText += ",ars_interval=" + arsInterval;
commandText += " where id in " + idlist;
cmd = new NpgsqlCommand("select count(id) from vehicle where id in " + idlist, connection);
object temp = cmd.ExecuteScalar();
Utils.WriteLine("editGroupVehicle: " + commandText);
if (Convert.ToInt32(temp) > 0)
{
cmd = new NpgsqlCommand(commandText, connection, transaction);
cmd.ExecuteNonQuery();
cmd = new NpgsqlCommand("update emergdi SET DI=" + _DI.ToString() + " where sc_id in " + idlist, connection, transaction);
if (cmd.ExecuteNonQuery() == 0)
{
foreach (string tmp_sc_id in idListArray)
{
cmd = new NpgsqlCommand("insert into emergdi (sc_id,DI) VALUES(" + Convert.ToInt32(tmp_sc_id) + "," + _DI.ToString() + ")", connection);
cmd.ExecuteNonQuery();
}
}
if (editGW)
{
foreach (var id in idListArray)
{
cmd = new NpgsqlCommand($"update subs_gateway SET gateway_id= {(rg.Gw_id < 0 ? "null" : rg.Gw_id.ToString())}, radio_gw_id= {(rg.Id < 0 ? "null" : rg.Id.ToString()) } where sc_id = {id}", connection, transaction);
if (cmd.ExecuteNonQuery() == 0)
{
cmd = new NpgsqlCommand("SELECT max(id) FROM subs_gateway ", connection);
string str_id_subs_gateway = cmd.ExecuteScalar().ToString();
int id_subs_gateway = 0;
int.TryParse(str_id_subs_gateway, out id_subs_gateway);
cmd = new NpgsqlCommand($"insert into subs_gateway (id, sc_id,gateway_id,radio_gw_id) VALUES({id_subs_gateway + 1 }, {id},{(rg.Gw_id < 0 ? "null" : rg.Gw_id.ToString())} , {(rg.Id < 0 ? "null" : rg.Id.ToString()) } )", connection, transaction);
cmd.ExecuteNonQuery();
}
}
}
if (mob.CanUpdate)
{
string clause = "";
if (mob.ToggleStateDictionary.ContainsKey("HasGPS"))
{
if (mob.ToggleStateDictionary["HasGPS"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_gps={mob.HasGPS}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("HasVoice"))
{
if (mob.ToggleStateDictionary["HasVoice"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_voice={mob.HasVoice}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("HasText"))
{
if (mob.ToggleStateDictionary["HasText"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_text={mob.HasText}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("HasTicketing"))
{
if (mob.ToggleStateDictionary["HasTicketing"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_ticketing={mob.HasTicketing}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("IsLoneWorker"))
{
if (mob.ToggleStateDictionary["IsLoneWorker"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_lone_worker={mob.IsLoneWorker}, lone_worker_interval={mob.LoneWorkerInterval}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("HasManDown"))
{
if (mob.ToggleStateDictionary["HasManDown"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_man_down = {mob.HasManDown}";
}
}
if (mob.ToggleStateDictionary.ContainsKey("HasEmergency"))
{
if (mob.ToggleStateDictionary["HasEmergency"] != true)
{
if (clause != "")
clause += ",";
clause += $"has_emergency = {mob.HasEmergency}";
}
}
if (clause != "")
{
string emergency = "";
if (mob.HasEmergency)
emergency = "1";
string updateSubscriberAlarm = $"update subscriber_alarm set emergency = '{emergency}' where sc_id in {idlist}";
string command = $"update subscriber_mobile SET {clause} where sc_id in {idlist};" + updateSubscriberAlarm;
cmd = new NpgsqlCommand(command, connection, transaction);
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
resp = vehResponse.done;
}
else
{
resp = vehResponse.vehNontInDB;
}
}
}
catch (Exception ex)
{
Utils.WriteLine("editGroupVehicle Commnad: " + ex.ToString());
transaction?.Rollback();
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
resp = vehResponse.SQLerror;
}
return resp;
}
public int getSCID(string imei)
{
string command = $"SELECT sc_id FROM subscriber WHERE imei='{imei}'";
return GetInt32Result(command);
}
public ArrayList getListofSCID(Hashtable hash)
{
ArrayList toreturn = new ArrayList();
string buffer = string.Join(",", hash.Keys);
2024-02-22 16:43:59 +00:00
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = $"SELECT sc_id FROM subscriber WHERE imei in ( {buffer} )";
2024-02-22 16:43:59 +00:00
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
toreturn.Add(reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine("getListofSCID: " + ex.ToString(), ConsoleColor.Yellow);
}
return toreturn;
}
public string getIMEI(int sc_id)
{
string command = $"SELECT imei FROM subscriber WHERE sc_id={sc_id}";
return GetStringResult(command);
}
public bool isUniqueLogin(string login, int sc_id)
{
bool ret = true;
string cmdsql = "";
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
cmdsql = $"SELECT count(sc_id) FROM subscriber_mobile WHERE login = '{login}'";
if (sc_id != -1)
cmdsql = $"{cmdsql} AND sc_id <> {sc_id}";
using (NpgsqlCommand cmd = new NpgsqlCommand(cmdsql, connection))
{
object veh_id = cmd.ExecuteScalar();
if (veh_id.ToString() != "0")
{
ret = false;
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine("isUniqueLogin: " + ex.ToString(), ConsoleColor.Yellow);
}
return ret;
}
public MobileVehicles getMobileVehicle(int sc_id)
{
MobileVehicles result = new MobileVehicles();
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = $"SELECT sc_id, phone_imei , first_name, last_name, company, os, phone_type,"
+ " sip_pswd, has_gps, has_voice, has_text, has_ticketing, email, login, has_lone_worker, "
+ " lone_worker_interval, has_man_down, has_emergency"
+ " FROM subscriber_mobile"
+ $" WHERE sc_id= {sc_id}";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
result = new MobileVehicles()
{
IMEI = Reader.IsDBNull(Reader.GetOrdinal("phone_imei")) ? "" : Reader.GetString(Reader.GetOrdinal("phone_imei")),
FirstName = Reader.IsDBNull(Reader.GetOrdinal("first_name")) ? "" : Reader.GetString(Reader.GetOrdinal("first_name")),
LastName = Reader.IsDBNull(Reader.GetOrdinal("last_name")) ? "" : Reader.GetString(Reader.GetOrdinal("last_name")),
Company = Reader.IsDBNull(Reader.GetOrdinal("company")) ? "" : Reader.GetString(Reader.GetOrdinal("company")),
OS = Reader.IsDBNull(Reader.GetOrdinal("os")) ? "" : Reader.GetString(Reader.GetOrdinal("os")),
PhoneType = Reader.IsDBNull(Reader.GetOrdinal("phone_type")) ? "" : Reader.GetString(Reader.GetOrdinal("phone_type")),
SipPswd = Reader.IsDBNull(Reader.GetOrdinal("sip_pswd")) ? "" : Reader.GetString(Reader.GetOrdinal("sip_pswd")),
HasGPS = Reader.IsDBNull(Reader.GetOrdinal("has_gps")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_gps")),
HasVoice = Reader.IsDBNull(Reader.GetOrdinal("has_voice")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_voice")),
HasText = Reader.IsDBNull(Reader.GetOrdinal("has_text")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_text")),
HasTicketing = Reader.IsDBNull(Reader.GetOrdinal("has_ticketing")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_ticketing")),
Email = Reader.IsDBNull(Reader.GetOrdinal("email")) ? "" : Reader.GetString(Reader.GetOrdinal("email")),
SipLogin = Reader.IsDBNull(Reader.GetOrdinal("login")) ? "" : Reader.GetString(Reader.GetOrdinal("login")),
IsLoneWorker = Reader.IsDBNull(Reader.GetOrdinal("has_lone_worker")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_lone_worker")),
LoneWorkerInterval = Reader.IsDBNull(Reader.GetOrdinal("lone_worker_interval")) ? 0 : Reader.GetInt32(Reader.GetOrdinal("lone_worker_interval")),
HasManDown = Reader.IsDBNull(Reader.GetOrdinal("has_man_down")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_man_down")),
HasEmergency = Reader.IsDBNull(Reader.GetOrdinal("has_emergency")) ? false : Reader.GetBoolean(Reader.GetOrdinal("has_emergency"))
};
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine($"getMobileVehicle: {ex.ToString()}", ConsoleColor.Yellow);
}
return result;
}
public int getReportingInterval(string imei)
{
string command = "SELECT vehicle.\"GPS_reporting_interval\" FROM vehicle,subscriber,subscriber_history "
+ $" WHERE subscriber.imei = '{imei}'"
+ " AND subscriber.sc_id = subscriber_history.sc_id"
+ " AND subscriber_history.veh_id = vehicle.id ";
return GetInt32Result(command);
}
public List<TallysmanLostLog> getGetTallysmanLogs(int interval)
{
List<TallysmanLostLog> toRet = new List<TallysmanLostLog>();
int backwards = DateTime.UtcNow.GetSecondsFromDT() - interval * 60;
string command = "SELECT s.imei::int, tallysman_log_id FROM messages m " +
"JOIN subscriber s ON s.sc_id = m.sc_id " +
"JOIN lastpos l on l.imei = s.imei " +
"WHERE tallysman_log_id is not null " +
$"AND m.timegmt >= {backwards} " +
$"AND l.status not in ({(int)Status_for_tab.OFF},{(int)Status_for_tab.DISABLE},{(int)Status_for_tab.MADEOFF})";
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())
{
toRet.Add(new TallysmanLostLog()
{
RadioID = reader.GetInt32(0),
LogId = reader.GetInt32(1)
});
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine($"getGetTallysmanLogs: {ex.ToString()}", ConsoleColor.Red);
}
return toRet;
}
public uint getRRSInterval(string imei)
{
string command = "SELECT vehicle.ars_interval FROM vehicle,subscriber,subscriber_history "
+ "WHERE subscriber.imei = '" + imei + "'"
+ " AND subscriber.sc_id = subscriber_history.sc_id"
+ " AND subscriber_history.veh_id = vehicle.id ";
int result = GetInt32Result(command);
return (uint)(result <= 0 ? 0 : result);
}
public List<Vehicles> getAllSierraVehicles(out Boolean hasOnlyIntegerValues, string arg, bool getDeleted)
{
string whereClause = "";
if (arg == "GSM Only")
{
whereClause = "where length(imei) > 7";
whereClause += getDeleted ? " AND is_deleted = TRUE " : " AND is_deleted = FALSE ";
}
if (arg == "TETRA Based")
{
whereClause = "where length(imei) <= 7 AND is_deleted = FALSE ";
whereClause += getDeleted ? " AND is_deleted = TRUE " : " AND is_deleted = FALSE ";
}
string command = "SELECT veh.id,sub.imei,veh.lp,veh.name,em.di,veh.\"GPS_reporting_interval\",grp.name,veh.driver_id,veh.is_stolen,veh.ars_interval,veh.gps_poor,veh.gps_off,veh.made_off, "
+ " sub.phone, sub.email, "
+ " COALESCE(sgw.gateway_id, -1) gateway_id, COALESCE(sgw.radio_gw_id, -1) radio_gw_id,"
+ " veh.type, veh.active"
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) INNER JOIN subscriber as sub"
+ " on (sh.sc_id = sub.sc_id) LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id)"
+ " LEFT JOIN (select * from vehicle_group vg join groups gp on vg.grp_ip = gp.id and gp.type = " + (int)SafeMobileLib.GroupType.CATEGORY.value + " ) as v_grp ON (v_grp.sc_id = sub.sc_id) "
+ " LEFT JOIN groups as grp ON (grp.id = v_grp.grp_ip)"
+ " LEFT JOIN subs_gateway as sgw ON (sgw.sc_id = sub.sc_id)"
+ whereClause
+ " ORDER BY veh.name";
return getAllVehiclesFromCMD(command, out hasOnlyIntegerValues);
}
public List<Vehicles> getAllVehicles(out Boolean hasOnlyIntegerValues, bool getDeleted)
{
string command = "SELECT veh.id,sub.imei,veh.lp,veh.name,em.di,veh.\"GPS_reporting_interval\",grp.name,veh.driver_id,veh.is_stolen,veh.ars_interval,veh.gps_poor,veh.gps_off,veh.made_off,"
+ " coalesce(sgw.gateway_id, -1) as gateway_id, coalesce(sgw.radio_gw_id, -1) as radio_gw_id, "
+ " veh.type, veh.active"
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) INNER JOIN subscriber as sub"
+ " on (sh.sc_id = sub.sc_id) LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id)"
+ " LEFT JOIN (select * from vehicle_group vg join groups gp on vg.grp_ip = gp.id and gp.type = " + (int)SafeMobileLib.GroupType.CATEGORY.value + " ) as v_grp ON (v_grp.sc_id = sub.sc_id) "
+ " LEFT JOIN groups as grp ON (grp.id = v_grp.grp_ip)"
+ " LEFT JOIN subs_gateway as sgw ON (sgw.sc_id = sub.sc_id)";
command += getDeleted ? " WHERE is_deleted = TRUE" : " WHERE is_deleted = FALSE";
command +=" ORDER BY veh.name";
return getAllVehiclesFromCMD(command, out hasOnlyIntegerValues);
}
public List<Vehicles> getAllVehicles()
{
Boolean hasOnlyIntegerValues = false;
return getAllVehiclesFromCMD("SELECT veh.id,sub.imei,veh.lp,veh.name,em.di,veh.\"GPS_reporting_interval\",grp.name,veh.driver_id,veh.is_stolen,veh.ars_interval,veh.gps_poor,veh.gps_off,veh.made_off,"
+ " coalesce(sgw.gateway_id, -1) as gateway_id, coalesce(sgw.radio_gw_id, -1) as radio_gw_id,"
+ " veh.type, veh.active"
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) INNER JOIN subscriber as sub"
+ " on (sh.sc_id = sub.sc_id) LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id)"
+ " LEFT JOIN (select * from vehicle_group vg join groups gp on vg.grp_ip = gp.id and gp.type = " + (int)SafeMobileLib.GroupType.CATEGORY.value + " ) as v_grp ON (v_grp.sc_id = sub.sc_id) "
+ " LEFT JOIN groups as grp ON (grp.id = v_grp.grp_ip)"
+ " LEFT JOIN subs_gateway as sgw ON (sgw.sc_id = sub.sc_id)"
+ " WHERE is_deleted = FALSE"
+ " ORDER BY sub.imei", out hasOnlyIntegerValues);
}
private List<Vehicles> getAllVehiclesFromCMD(String command, out Boolean hasOnlyIntegerValues)
{
hasOnlyIntegerValues = true;
List<Vehicles> vehList = new List<Vehicles>();
Vehicles veh;
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())
{
if (Reader.IsDBNull(4)) veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", 0, Reader.GetInt32(5),
(Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(10), Reader.GetInt32(11), Reader.GetInt32(12));
else veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", Reader.GetInt32(4),
Reader.GetInt32(5), (Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(10), Reader.GetInt32(11), Reader.GetInt32(12));
if (command.Contains("email"))
veh.Email = Reader.IsDBNull(Reader.GetOrdinal("email")) ? "" : Reader.GetString(Reader.GetOrdinal("email"));
if (command.Contains("phone"))
veh.Phone = Reader.IsDBNull(Reader.GetOrdinal("phone")) ? "" : Reader.GetString(Reader.GetOrdinal("phone"));
if (command.Contains("gateway_id"))
veh.Gw_id = Reader.IsDBNull(Reader.GetOrdinal("gateway_id")) ? 0 : Reader.GetInt32(Reader.GetOrdinal("gateway_id"));
if (command.Contains("radio_gw_id"))
veh.Radio_gw_id = Reader.IsDBNull(Reader.GetOrdinal("radio_gw_id")) ? 0 : Reader.GetInt32(Reader.GetOrdinal("radio_gw_id"));
if (command.Contains("type"))
veh.Type = Reader.IsDBNull(Reader.GetOrdinal("type")) ? 0 : Reader.GetInt32(Reader.GetOrdinal("type"));
if (command.Contains("active"))
veh.Active = Reader.IsDBNull(Reader.GetOrdinal("active")) ? false : Reader.GetBoolean(Reader.GetOrdinal("active"));
int ars_interval = Reader.GetInt32(9);
veh.ArsInterval = ars_interval;
try
{
veh.IntImei = Convert.ToInt64(veh.Imei);
}
catch
{
hasOnlyIntegerValues = false;
}
vehList.Add(veh);
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
return vehList;
}
public List<Vehicles> getAllVehiclesWithSc_ID()
{
List<Vehicles> vehList = new List<Vehicles>();
Vehicles veh;
string command = "SELECT veh.id,sub.imei,veh.lp,veh.name,em.di,veh.\"GPS_reporting_interval\",grp.name,veh.driver_id,veh.is_stolen,veh.ars_interval,sub.sc_id,veh.gps_poor,veh.gps_off,veh.made_off"
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) "
+ " INNER JOIN subscriber as sub on (sh.sc_id = sub.sc_id) "
+ " LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id) "
+ " LEFT JOIN "
+ "( SELECT * FROM vehicle_group v_grp1 JOIN groups grp1 ON (grp1.id = v_grp1.grp_ip) WHERE grp1.type = " + (int)GroupType.CATEGORY.value + " )"
+ "as v_grp ON (v_grp.sc_id = sub.sc_id)"
+ " LEFT JOIN groups as grp ON (grp.id = v_grp.grp_ip)"
+ " WHERE is_deleted = FALSE"
+ " ORDER BY veh.name";
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())
{
if (Reader.IsDBNull(4)) veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", 0, Reader.GetInt32(5),
(Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(10), Reader.GetInt32(11), Reader.GetInt32(12), Reader.GetInt32(13), 0);
else veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", Reader.GetInt32(4),
Reader.GetInt32(5), (Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(10), Reader.GetInt32(11), Reader.GetInt32(12), Reader.GetInt32(13), 0);
int ars_interval = Reader.GetInt32(9);
veh.ArsInterval = ars_interval;
vehList.Add(veh);
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
return vehList;
}
public List<Vehicles> getAllVehiclesForCurrentUser(string _id, bool onlyActive)
{
Vehicles veh;
List<Vehicles> vehList = new List<Vehicles>();
string command = "SELECT DISTINCT veh.id,sub.imei,veh.lp,veh.name,em.di,veh.\"GPS_reporting_interval\",grp.name,veh.driver_id,veh.is_stolen,veh.gps_poor,veh.gps_off,veh.made_off"
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) "
+ " INNER JOIN subscriber as sub on (sh.sc_id = sub.sc_id) "
+ " LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id)"
+ " LEFT JOIN "
+ "( SELECT * FROM vehicle_group v_grp1 JOIN groups grp1 ON (grp1.id = v_grp1.grp_ip) WHERE grp1.type = " + (int)GroupType.CATEGORY.value + " )"
+ " as v_grp ON (v_grp.sc_id = sub.sc_id)"
+ " LEFT JOIN groups as grp ON (grp.id = v_grp.grp_ip)"
+ " INNER JOIN vehicle_user as vh on(vh.veh_id=veh.id)"
+ $" WHERE vh.user_id={_id} AND is_deleted = FALSE #allOrOnlyActive#"
+ " ORDER BY sub.imei";
if (onlyActive)
command = command.Replace("#allOrOnlyActive#", " AND active = TRUE ");
else
command = command.Replace("#allOrOnlyActive#", "");
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())
{
if (Reader.IsDBNull(4)) veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", 0, Reader.GetInt32(5),
(Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(9), Reader.GetInt32(10), Reader.GetInt32(11));
else veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)),
Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", Reader.GetInt32(4),
Reader.GetInt32(5), (Reader.IsDBNull(6)) ? "" : Reader.GetString(6),
Reader.GetInt32(7), Reader.GetInt32(8), Reader.GetInt32(9), Reader.GetInt32(10), Reader.GetInt32(11));
vehList.Add(veh);
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
vehList.Sort(delegate (Vehicles c1, Vehicles c2) { return c1.VehName.CompareTo(c2.VehName); });
return vehList;
}
//get all vehicles for current user ( active and inactive )
public List<Vehicles> getAllVehiclesForCurrentUser(string _id)
{
return getAllVehiclesForCurrentUser(_id, false);
}
//get all vehicles that are not assigned to current user
public List<Vehicles> getAllOtherVehiclesForCurrentUser(string _id)
{
List<Vehicles> vehList = new List<Vehicles>();
string command = "SELECT DISTINCT veh.id,sub.imei,veh.lp,veh.name,em.DI,veh.\"GPS_reporting_interval\",veh.gps_poor,veh.gps_off,veh.made_off, veh.driver_id "
+ " FROM vehicle as veh "
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) "
+ " INNER JOIN subscriber as sub on (sh.sc_id = sub.sc_id) "
+ " LEFT JOIN emergdi as em on (sub.sc_id = em.sc_id) "
+ " LEFT JOIN vehicle_user as vh on(vh.veh_id = veh.id) "
+ " WHERE veh.id NOT IN (SELECT veh_id FROM vehicle_user WHERE user_id = " + _id + ") AND is_deleted = FALSE "
+ " ORDER BY sub.imei";
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader Reader = cmd.ExecuteReader())
{
Vehicles veh;
while (Reader.Read())
{
if (Reader.IsDBNull(4))
veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)), Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", 0, Reader.GetInt32(5), "", Reader.GetInt32(9), 0, Reader.GetInt32(6), Reader.GetInt32(7), Reader.GetInt32(8));
else
veh = new Vehicles(Convert.ToInt32(Reader.GetValue(0)), Reader.GetValue(1).ToString(), Reader.GetValue(2).ToString(),
Reader.GetValue(3).ToString(), "", Reader.GetInt32(4), Reader.GetInt32(5), "", Reader.GetInt32(9), 0, Reader.GetInt32(6), Reader.GetInt32(7), Reader.GetInt32(8));
vehList.Add(veh);
}
}
}
}
}
catch (Exception ee)
{
SM.Debug(command);
Console.WriteLine($"getAllOtherVehiclesForCurrentUser : {ee.ToString()}", ConsoleColor.Yellow);
}
vehList.Sort(delegate(Vehicles c1, Vehicles c2) { return c1.VehName.CompareTo(c2.VehName); });
return vehList;
}
public class VehiclesIDComparer : IComparer
{
public VehiclesIDComparer() : base() { }
int IComparer.Compare(object x, object y)
{
Vehicles X = x as Vehicles;
Vehicles Y = y as Vehicles;
return (X.VehName.CompareTo(Y.VehName)>0) ? 1 : -1;
}
}
// add connection between user and vehicle
public vehResponse addVehicleUserConnection(string vehId, string userId)
{
vehResponse resp = vehResponse.done;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = $"SELECT count(veh_id) FROM vehicle_user where veh_id='{vehId}' AND user_id ='{userId}'";
using (NpgsqlCommand cmd2 = new NpgsqlCommand(command, connection))
{
object result = cmd2.ExecuteScalar();
if (result.ToString() == "0")
{
command = $"INSERT INTO vehicle_user VALUES({vehId},{userId},{String.Format("'{0:yyyy-MM-dd}'", DateTime.UtcNow)})";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
cmd.ExecuteNonQuery();
}
}
}
}
}
catch (Exception ee)
{
Console.WriteLine($"{ee.Message} {ee.StackTrace} {ee.Source}", ConsoleColor.Yellow);
resp = vehResponse.SQLerror;
}
return resp;
}
// add connection between user and vehicle
public vehResponse assignVehiclesToUser(List<string> vehIds, string userId)
{
vehResponse resp = vehResponse.done;
StringBuilder sb = new StringBuilder(1024);
try
{
sb.Append("INSERT INTO vehicle_user VALUES ");
for (int i = 0; i < vehIds.Count; i++)
{
String vehId = vehIds[i];
sb.Append($"({vehId},{userId},{String.Format("'{0:yyyy-MM-dd}'", DateTime.UtcNow)})");
if (i < vehIds.Count - 1)
sb.Append(",");
}
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sb.ToString(), connection))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ee)
{
Console.WriteLine($"{ee.Message} {ee.StackTrace} {ee.Source} ");
resp = vehResponse.SQLerror;
}
return resp;
}
// remove connection between user and vehicle
public vehResponse removeVehiclesToUser(List<string> vehIds, string userId)
{
vehResponse resp = vehResponse.done;
StringBuilder sb = new StringBuilder(1024);
try
{
sb.Append("DELETE FROM vehicle_user WHERE ");
for (int i = 0; i < vehIds.Count; i++)
{
String vehId = vehIds[i];
sb.Append($" (veh_id ='{vehId}' AND user_id='{userId}') ");
if (i < vehIds.Count - 1)
sb.Append(" OR ");
}
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sb.ToString(), connection))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ee)
{
Console.WriteLine($"{ee.Message} {ee.StackTrace} {ee.Source}");
resp = vehResponse.SQLerror;
}
return resp;
}
//remove connection between user and vehicle
public vehResponse removeVehicleUserConnection(string vehId, string userId)
{
vehResponse resp = vehResponse.done;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = $"DELETE FROM vehicle_user WHERE veh_id ='{vehId}' AND user_id ='{userId}'";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ee)
{
Console.WriteLine($"{ee.Message} {ee.StackTrace} {ee.Source}", ConsoleColor.Yellow );
resp = vehResponse.SQLerror;
}
return resp;
}
public sqlResponse assignUnit2GW(int radioID, int gwID, string r_gw_ip)
{
sqlResponse resp = sqlResponse.SQLerror;
NpgsqlTransaction transaction = null;
try
{
int scid = getSCID(radioID.ToString());
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
// open a transaction
transaction = connection.BeginTransaction();
//get radioGW ID from it's IP
int r_gwID = -1;
string command = $"SELECT \"ID\" FROM radio_gw WHERE \"IP\"='{r_gw_ip}' AND \"GW_ID\" = {gwID}";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
r_gwID = Reader.GetInt32(0);
}
}
}
if (r_gwID == -1)
{
resp = sqlResponse.SQLerror;
SM.Debug("radio GW ip = " + r_gw_ip + " not found in DB.Please go in SUM and add this radioGW");
return resp;
}
//delete previous entry
using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM subs_gateway where sc_id = {scid}", connection, transaction))
{
cmd.ExecuteNonQuery();
}
//add new entry
string str_id_subs_gateway = string.Empty;
using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT max(id) FROM subs_gateway ", connection))
{
str_id_subs_gateway = cmd.ExecuteScalar().ToString();
}
int id_subs_gateway = 0;
int.TryParse(str_id_subs_gateway, out id_subs_gateway);
using (NpgsqlCommand cmd = new NpgsqlCommand($"INSERT INTO subs_gateway (id, sc_id, gateway_id, radio_gw_id) VALUES( {id_subs_gateway + 1},{scid},{(gwID < 0 ? "null" : gwID.ToString())}, {(r_gwID < 0 ? "null" : r_gwID.ToString()) })", connection, transaction))
{
cmd.ExecuteNonQuery();
}
transaction.Commit();
resp = sqlResponse.done;
}
}
catch (Exception o)
{
transaction?.Rollback();
Console.WriteLine(o.Message.ToString());
throw new ArgumentException(o.Message.ToString());
}
return resp;
}
/// <summary>
/// gets the radio position in system (gateway ID, radio dateway ID)
/// </summary>
/// <param name="sc_id">unit sc_id</param>
/// <returns>returns null if incorect sc_id</returns>
public UnitSysPosition getSystemPosition(int sc_id)
{
UnitSysPosition pos = new UnitSysPosition(0, 0);
try
{
using (NpgsqlConnection conn = new NpgsqlConnection(getConnectionString()))
{
conn.Open();
string command = $"SELECT coalesce(gateway_id, -1) as gateway_id, coalesce(radio_gw_id, -1) radio_gw_id FROM subs_gateway WHERE sc_id = {sc_id}";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, conn))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int gateway_id = Convert.ToInt32(reader["gateway_id"]);
int radio_gw_id = Convert.ToInt32(reader["radio_gw_id"]);
pos = new UnitSysPosition(gateway_id, radio_gw_id);
}
reader.Close();
}
}
conn.Close();
}
}
catch (Exception ex)
{
Utils.WriteLine("getSystemPosition " + ex.ToString(), ConsoleColor.Red);
}
return pos;
}
/// <summary>
/// gets the radio position in system (gateway ID, radio dateway ID)
/// </summary>
/// <param name="sc_id">unit sc_id</param>
/// <returns>returns null if incorect sc_id</returns>
public UnitSysPosition getSystemPositionIMEI(String IMEI)
{
UnitSysPosition pos = null;
try
{
using (NpgsqlConnection conn = new NpgsqlConnection(getConnectionString()))
{
conn.Open();
string command = "SELECT distinct coalesce(sg.gateway_id, -1) as gateway_id, coalesce(sg.radio_gw_id, -1) as radio_gw_id "
+ " FROM subs_gateway sg "
+ " INNER JOIN subscriber sb ON sb.sc_id = sg.sc_id "
+ $" WHERE sb.imei ='{IMEI}'";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, conn))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int gateway_id = Convert.ToInt32(reader["gateway_id"]);
int radio_gw_id = Convert.ToInt32(reader["radio_gw_id"]);
pos = new UnitSysPosition(gateway_id, radio_gw_id);
}
reader.Close();
}
}
conn.Close();
}
}
catch (Exception ex)
{
Utils.WriteLine("getSystemPositionIMEI " + ex.ToString(), ConsoleColor.Red);
}
return pos;
}
/// <summary>
/// gets the radio position in system (gateway ID, radio dateway ID)
/// </summary>
/// <param name="sc_id">unit sc_id</param>
/// <returns>returns null if incorect sc_id</returns>
public Hashtable getSystemPosition_for_all_scid()
{
Hashtable ret = new Hashtable();
string command = "SELECT coalesce(gateway_id, -1) as gateway_id, coalesce(radio_gw_id, -1) as radio_gw_id, sc_id FROM subs_gateway";
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())
{
long sc_id = Convert.ToInt64(reader["sc_id"]);
int gateway_id = Convert.ToInt32(reader["gateway_id"]);
int radio_gw_id = Convert.ToInt32(reader["radio_gw_id"]);
if(!ret.ContainsKey(sc_id))
ret.Add(sc_id, new UnitSysPosition(gateway_id, radio_gw_id));
2024-02-22 16:43:59 +00:00
}
reader.Close();
}
}
connection.Close();
}
}
catch (Exception ee)
{
SM.Debug(command);
Console.WriteLine($"getSystemPosition_for_all_scid: {ee.ToString()}", ConsoleColor.Yellow);
}
return ret;
}
public UnitSysPosition getSystemPosition_for_group(string cps_id)
{
UnitSysPosition pos = null;
//string command = "SELECT DISTINCT coalesce(sub.gateway_id, -1) as gateway_id, coalesce(sub.radio_gw_id, -1) as radio_gw_id "
// + " FROM groups as grp "
// + " INNER JOIN vehicle_group as vgrp ON (grp.id=vgrp.grp_ip) "
// + "INNER JOIN subs_gateway as sub ON (vgrp.sc_id = sub.sc_id) "
// + " WHERE grp.cps_id=" + cps_id.ToString();
string command = "SELECT DISTINCT coalesce(sub.\"GW_ID\", -1) as gateway_id, coalesce(grp.r_gw_id, -1) as radio_gw_id " +
" FROM groups as grp " +
" INNER JOIN radio_gw as sub ON(grp.r_gw_id = sub.\"ID\") " +
$" WHERE grp.cps_id = {cps_id}";
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())
{
int gateway_id = Convert.ToInt32(reader["gateway_id"]);
int radio_gw_id = Convert.ToInt32(reader["radio_gw_id"]);
pos = new UnitSysPosition(gateway_id, radio_gw_id);
if ((gateway_id > 0) && (radio_gw_id > 0)) break;
}
reader.Close();
}
}
connection.Close();
}
}
catch (Exception ee)
{
SM.Debug(command);
Console.WriteLine($"getSystemPosition_for_group : {ee.ToString()}", ConsoleColor.Yellow);
}
return pos;
}
public ArrayList get_all_car_picture()
{
ArrayList ret = new ArrayList();
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = "SELECT name, id, pattern, displayed_name from car ORDER by name";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Car obj = new Car();
obj.Name = reader["name"].ToString();
obj.idx = Convert.ToInt32(reader["id"]);
obj.iconPattern = reader["pattern"].ToString();
obj.DisplayedName = reader["displayed_name"].ToString();
ret.Add(obj);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"get_all_car_picture : {ex.ToString()}", ConsoleColor.Yellow);
}
return ret;
}
/// <summary>
/// set the unit stolon status(0-ok, 1- stolen)
/// </summary>
/// <param name="radioID">remote radio id</param>
/// <param name="status">0-ok, 1- stolen</param>
/// <returns></returns>
public sqlResponse setStolenStatus(string radioID, int status)
{
NpgsqlCommand cmd;
sqlResponse resp = sqlResponse.SQLerror;
try
{
int scid = getSCID(radioID.ToString());
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
cmd = new NpgsqlCommand("SELECT veh_id FROM subscriber_history WHERE sc_id=\'" + scid + "\'", connection);
object tmp_veh_id = cmd.ExecuteScalar();
if (tmp_veh_id != null)
{
cmd = new NpgsqlCommand("UPDATE vehicle SET is_stolen=" + status + " WHERE id=" + tmp_veh_id, connection);
cmd.ExecuteNonQuery();
resp = sqlResponse.done;
}
}
}
catch (Exception o)
{
Console.WriteLine(o.Message.ToString());
throw new ArgumentException(o.Message.ToString());
}
return resp;
}
public Int32 getActiveVehiclesCount(int totalUnits, bool isSierraWireless, out int totaldbunits)
{
totaldbunits = 0;
if (totalUnits == 0)
return totalUnits;
Int32 result = 0;
NpgsqlCommand cmd;
try
{
string selectClause = isSierraWireless ?
"SELECT COUNT(id) FROM vehicle v " +
"JOIN subscriber s ON s.sc_id = v.id WHERE active = true " +
"AND length(imei) <= 7" :
"SELECT COUNT(id) FROM vehicle WHERE active = true";
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
cmd = new NpgsqlCommand(selectClause, connection);
int.TryParse(cmd.ExecuteScalar().ToString(), out result);
if (result > totalUnits)
{
//BRAINFUCK
string updateClause = isSierraWireless ?
$"UPDATE vehicle SET active = false WHERE id NOT IN ((SELECT id from vehicle v join subscriber s ON s.sc_id = v.id WHERE active = true and length(imei) <= 7 order by id limit {totalUnits}) UNION SELECT id FROM vehicle v join subscriber s ON s.sc_id = v.id WHERE active = true AND length(imei) > 7 )" :
$"UPDATE vehicle SET active = false WHERE id NOT IN (SELECT id from vehicle where active = true order by id limit {totalUnits} )";
cmd = new NpgsqlCommand(updateClause, connection);
cmd.ExecuteNonQuery();
result = totalUnits;
}
2024-02-22 16:43:59 +00:00
cmd = new NpgsqlCommand("SELECT COUNT(id) FROM vehicle v WHERE is_deleted = FALSE", connection);
int.TryParse(cmd.ExecuteScalar().ToString(), out totaldbunits);
connection.Close();
}
}
catch (Exception o)
{
Console.WriteLine(o.Message.ToString());
throw new ArgumentException(o.Message.ToString());
}
return result;
}
/// Get all the units that are marked as ON in lastpos_ars table
/// Time is GMT format
/// </summary>
/// <returns>ARSstatus</returns>
public List<ARSstatus> Get_ARS_ON_info_GMT()
{
List<ARSstatus> ret = new List<ARSstatus>();
string command = "SELECT ars.imei,ars.timegmt,ars.status,veh.ars_interval " +
" FROM lastpos_ars as ars" +
" INNER JOIN subscriber as sub ON (ars.imei = sub.imei)" +
" INNER JOIN subscriber_history as sh ON (sub.sc_id = sh.sc_id)" +
" INNER JOIN vehicle as veh ON (veh.id = sh.veh_id)" +
" WHERE ars.status = 1";
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())
{
ARSstatus obj = new ARSstatus();
obj.Imei = reader["imei"].ToString();
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
obj.Timegmt = dt.AddSeconds(Convert.ToDouble(reader["timegmt"]));
obj.Status = Convert.ToInt32(reader["status"]);
obj.ArsInterval = Convert.ToInt32(reader["ars_interval"]);
ret.Add(obj);
}
reader.Close();
}
}
connection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine($"Get_ARS_ON_info_GMT : {ex.ToString()}", ConsoleColor.Yellow);
}
return ret;
}
public List<UnitGpsPos> GetLastPos()
{
List<UnitGpsPos> lastPosList = new List<UnitGpsPos>();
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = "SELECT imei, lat, lng, speed, status, timegmt, address FROM lastpos";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UnitGpsPos lp = new UnitGpsPos();
lp.IMEI = reader["imei"].ToString();
lp.lat = Convert.ToDouble(reader["lat"]).ToString();
lp.lng = Convert.ToDouble(reader["lng"]).ToString();
lp.speed = Convert.ToInt32(reader["speed"]);
lp.status = Convert.ToInt32(reader["status"]);
lp.timeGMT = Convert.ToInt32(reader["timegmt"]);
lp.adr = reader["address"].ToString();
lastPosList.Add(lp);
}
reader.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"GetLastPos : {ex.ToString()}", ConsoleColor.Yellow);
}
return lastPosList;
}
public Dictionary<String, PositionData> getImeiLastPosDictionary(bool activeUnits)
{
Dictionary<String, PositionData> result = new Dictionary<string, PositionData>();
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
string command = "SELECT veh.id, sub.imei, veh.lp, veh.name, veh.\"GPS_reporting_interval\" as rep,veh.driver_id, lp.imei, lp.lat, lp.lng, lp.speed, lp.status, lp.timegmt "
+ " FROM vehicle as veh"
+ " INNER JOIN subscriber_history as sh ON (veh.id = sh.veh_id) INNER JOIN subscriber as sub "
+ " ON (sh.sc_id = sub.sc_id) "
+ " INNER JOIN lastpos lp on lp.imei = sub.imei"
+ (activeUnits ? " WHERE veh.active = true" : " ")
+ " ORDER BY lp.imei::int; ";
using (NpgsqlCommand cmd = new NpgsqlCommand(command, connection))
{
using (NpgsqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// read last position value and reporting interval
PositionData pos = new PositionData()
{
Lat = dr.GetDouble(dr.GetOrdinal("lat")),
Lng = dr.GetDouble(dr.GetOrdinal("lng")),
Speed = dr.GetInt32(dr.GetOrdinal("speed")),
TimeGMT = dr.GetInt32(dr.GetOrdinal("timegmt")),
ReportingInterval = dr.GetInt32(dr.GetOrdinal("rep")),
};
string imei = dr.GetString(dr.GetOrdinal("imei"));
// add imei and position only if not exists
if (!result.ContainsKey(imei))
result.Add(imei, pos);
}
dr.Close();
}
}
connection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine($"getImeiLastPosDictionary : {ex.ToString()}", ConsoleColor.Yellow);
}
return result;
}
public List<UnitGpsPos> GetLastPosUserID(Int32 userID)
{
List<UnitGpsPos> lastPosList = new List<UnitGpsPos>();
string command = "SELECT l.imei, l.lat, l.lng, l.speed, l.status, l.timegmt, l.address " +
"FROM lastpos l " +
"INNER JOIN subscriber as s ON (l.imei = s.imei) " +
"INNER JOIN subscriber_history as h ON (h.sc_id = s.sc_id) " +
"INNER JOIN vehicle as v on (v.id = h.veh_id) " +
"INNER JOIN vehicle_user as u on (u.veh_id = v.id) " +
$"WHERE u.user_id = {userID}";
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())
{
UnitGpsPos lp = new UnitGpsPos();
lp.IMEI = reader["imei"].ToString();
lp.lat = Convert.ToDouble(reader["lat"]).ToString();
lp.lng = Convert.ToDouble(reader["lng"]).ToString();
lp.speed = Convert.ToInt32(reader["speed"]);
lp.status = Convert.ToInt32(reader["status"]);
lp.timeGMT = Convert.ToInt32(reader["timegmt"]);
lp.adr = reader["address"].ToString();
lastPosList.Add(lp);
}
reader.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"GetLastPosUserID : {ex.ToString()}", ConsoleColor.Yellow);
}
return lastPosList;
}
public Boolean isUnitDeleted(string id)
{
object temp = null;
bool isDeleted;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
String query = $"SELECT is_deleted FROM vehicle where id = {id}";
using (NpgsqlCommand cmd = new NpgsqlCommand(query, connection))
{
temp = cmd.ExecuteScalar();
}
}
}
catch(Exception ex)
{
Utils.WriteLine("isUnitDeleted: " + ex.ToString(), ConsoleColor.Red);
}
if (temp is bool)
return isDeleted = (bool)temp;
else
return true;
}
public List<UnitGpsPos> GET_HistoryPositions(int sc_id, Int32 p_start, Int32 p_stop)
{
List<UnitGpsPos> ret = new List<UnitGpsPos>();
Double Stop = 0, Start = 0;
if ((p_start == 0) && (p_stop == 0)) p_stop = 2100000000;
Start = sc_id * 10000000000 + p_start;
Stop = sc_id * 10000000000 + p_stop;
try
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = getConnectionString();
connection.Open();
String query = String.Format($"SELECT lat, lng, speed, timeGMT, address FROM messages WHERE scevtime>{Start} AND scevtime<{Stop} ORDER BY timeGMT");
using (NpgsqlCommand cmd = new NpgsqlCommand(query, connection))
{
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UnitGpsPos pos = new UnitGpsPos();
pos.IMEI = "NA";
pos.lat = Convert.ToDouble(reader["lat"]).ToString();
pos.lng = Convert.ToDouble(reader["lng"]).ToString();
pos.speed = Convert.ToInt32(reader["speed"]);
pos.timeGMT = Convert.ToInt32(reader["timeGMT"]);
pos.adr = reader.IsDBNull(4) ? " " : reader["address"].ToString();
ret.Add(pos);
}
reader.Close();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"GET_HistoryPositions : {ex.ToString()}", ConsoleColor.Yellow);
}
return ret;
}
}
public enum vehResponse
{
done,
alreadyInDB,
SQLerror,
vehNontInDB
}
public class ContactLinx
{
private int id;
/// <summary>
/// Radio ID for radio, user id for dispatcher, etc.
/// </summary>
public int Id
{
get { return id; }
set { id = value; }
}
private int sipid;
public int SipId
{
get { return sipid; }
set { sipid = value; }
}
private string ip;
public string IP
{
get { return ip; }
set { ip = value; }
}
private string sippwd;
public string Sippwd
{
get { return sippwd; }
set { sippwd = value; }
}
private int imageID;
public int ImageID
{
get { return imageID; }
set { imageID = value; }
}
private string name;
/// <summary>
/// Friendly name of radio unit, sipid or....
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
private ContactType type;
public ContactType Type
{
get { return type; }
set { type = value; }
}
private int intType;
public int IntType
{
get { return intType; }
set { intType = value; }
}
private int dispatcherBackup;
public int DispatcherBackup
{
get { return dispatcherBackup; }
set { dispatcherBackup = value; }
}
private string gWandRadioGW;
/// <summary>
/// GwId + "." + RadioGwID sau "-1.-1"
/// </summary>
public string GWandRadioGW
{
get { return gWandRadioGW; }
set { gWandRadioGW = value; }
}
private GatewayType gw_type;
public GatewayType GWtype
{
get { return gw_type; }
set { gw_type = value; }
}
}
public class MobileVehicles
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string sipLogin;
public string SipLogin
{
get { return sipLogin; }
set { sipLogin = value; }
}
private string unitName;
public string UnitName
{
get { return unitName; }
set { unitName = value; }
}
private string imei;
public string IMEI
{
get { return imei; }
set { imei = 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 company;
public string Company
{
get { return company; }
set { company = value; }
}
private string os;
public string OS
{
get { return os; }
set { os = value; }
}
private string phoneType;
public string PhoneType
{
get { return phoneType; }
set { phoneType = value; }
}
private string sipPswd;
public string SipPswd
{
get { return sipPswd; }
set { sipPswd = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
private bool canUpdate;
public bool CanUpdate
{
get { return canUpdate; }
set { canUpdate = value; }
}
private bool has_gps;
public bool HasGPS
{
get { return has_gps; }
set { has_gps = value; }
}
private bool has_voice;
public bool HasVoice
{
get { return has_voice; }
set { has_voice = value; }
}
private bool has_text;
public bool HasText
{
get { return has_text; }
set { has_text = value; }
}
private bool has_ticketing;
public bool HasTicketing
{
get { return has_ticketing; }
set { has_ticketing = value; }
}
private bool is_lone_worker;
public bool IsLoneWorker
{
get { return is_lone_worker; }
set { is_lone_worker = value; }
}
private int lone_worker_interval;
public int LoneWorkerInterval
{
get { return lone_worker_interval; }
set { lone_worker_interval = value; }
}
private bool has_man_down;
public bool HasManDown
{
get { return has_man_down; }
set { has_man_down = value; }
}
private bool has_emergency;
public bool HasEmergency
{
get { return has_emergency; }
set { has_emergency = value; }
}
public MobileVehicles()
{
lone_worker_interval = 1;
}
public Dictionary<string, bool> ToggleStateDictionary;
public bool AddToHashTableThreeState(string key, bool IsIndeterminate)
{
bool ret = false;
if (!ToggleStateDictionary.ContainsKey(key))
{
ToggleStateDictionary.Add(key, IsIndeterminate);
ret = true;
}
return ret;
}
}
public class Vehicles
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private int di;
public int Di
{
get { return di; }
set { di = value; }
}
private Int64 intImei;
public Int64 IntImei
{
get { return intImei; }
set { intImei = value; }
}
private string imei;
public string Imei
{
get { return imei; }
set { imei = value; }
}
private string serialNumber;
public string SerialNumber
{
get { return serialNumber; }
set { serialNumber = value; }
}
private string vehName;
public string VehName
{
get { return vehName; }
set { vehName = value; }
}
private string userName;
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string phone;
public string Phone
{
get { return phone; }
set { phone = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
private int gpsInterval;
public int GpsInterval
{
get { return gpsInterval; }
set { gpsInterval = value; }
}
private int arsInterval;
public int ArsInterval
{
get { return arsInterval; }
set { arsInterval = value; }
}
private string groupName;
public string GroupName
{
get { return groupName; }
set { groupName = value; }
}
private int isStolen;
public int IsStolen
{
get { return isStolen; }
set { isStolen = value; }
}
private int imgID;
public int ImgID
{
get { return imgID; }
set { imgID = value; }
}
private int enableStatus;
public int EnableStatus
{
get { return enableStatus; }
set { enableStatus = value; }
}
private int sc_id;
public int Sc_id
{
get { return sc_id; }
set { sc_id = value; }
}
private int gps_poor;
public int Gps_poor
{
get { return gps_poor; }
set { gps_poor = value; }
}
private int gps_off;
public int Gps_off
{
get { return gps_off; }
set { gps_off = value; }
}
private int made_off;
public int Made_off
{
get { return made_off; }
set { made_off = value; }
}
private int gw_id;
public int Gw_id
{
get { return gw_id; }
set { gw_id = value; }
}
private int radio_gw_id;
public int Radio_gw_id
{
get { return radio_gw_id; }
set { radio_gw_id = value; }
}
private int type;
public int Type
{
get { return type; }
set { type = value; }
}
private bool active;
public bool Active
{
get { return active; }
set { active = value; }
}
public Vehicles(int id, string imei, string serialNumber, string name, string user, int DI, int gpsInterval, string groupName, int imgID, int _isStolen, int gps_poor, int gps_off, int made_off, int _arsInterval = 0)
{
this.id = id;
this.imei = imei;
this.serialNumber = serialNumber;
this.vehName = name;
this.userName = user;
this.di = DI;
this.gpsInterval = gpsInterval;
this.groupName = groupName;
this.imgID = imgID;
this.isStolen = _isStolen;
this.arsInterval = _arsInterval;
this.gps_poor = gps_poor;
this.gps_off = gps_off;
this.made_off = made_off;
this.sc_id = 0;
}
public Vehicles(int id, string imei, string serialNumber, string name, string user, int DI, int gpsInterval, string groupName, int imgID, int _isStolen, int _sc_id, int gps_poor, int gps_off, int made_off, int _arsInterval = 0)
{
this.id = id;
this.imei = imei;
this.serialNumber = serialNumber;
this.vehName = name;
this.userName = user;
this.di = DI;
this.gpsInterval = gpsInterval;
this.groupName = groupName;
this.imgID = imgID;
this.isStolen = _isStolen;
this.arsInterval = _arsInterval;
this.gps_poor = gps_poor;
this.gps_off = gps_off;
this.made_off = made_off;
this.sc_id = _sc_id;
}
public Vehicles()
{
// TODO: Complete member initialization
}
}
public class VehicleNameComparer : IComparer
{
public VehicleNameComparer() : base() { }
int IComparer.Compare(object x, object y)
{
Vehicles X = x as Vehicles;
Vehicles Y = y as Vehicles;
return String.Compare(X.VehName, Y.VehName);
}
}
public class UnitSysPosition
{
private int gw_id;
public int Gw_id
{
get { return gw_id; }
set { gw_id = value; }
}
private int r_gw_id;
public int R_gw_id
{
get { return r_gw_id; }
set { r_gw_id = value; }
}
public UnitSysPosition(int gwid, int rgwid)
{
gw_id = gwid;
r_gw_id = rgwid;
}
}
public class Car
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string fileName;
public string desc;
public Int32 idx;
public string listFilePath;
public string iconPattern;
private string displayedName;
public string DisplayedName
{
get { return displayedName; }
set { displayedName = value; }
}
}
public class SUID_AND_IMEI
{
private int sc_id;
public int Sc_id
{
get { return sc_id; }
set { sc_id = value; }
}
private string imei;
public string Imei
{
get { return imei; }
set { imei = value; }
}
public SUID_AND_IMEI(int scid, string imei)
{
this.sc_id = scid;
this.imei = imei;
}
}
public class Scid_and_Status
{
private int sc_id;
public int Sc_id
{
get { return sc_id; }
set { sc_id = value; }
}
private int status;
public int Status
{
get { return status; }
set { status = value; }
}
public Scid_and_Status(int scid, int status)
{
this.sc_id = scid;
this.status = status;
}
}
public class ARSstatus
{
private int status;
public int Status
{
get { return status; }
set { status = value; }
}
private string imei;
public string Imei
{
get { return imei; }
set { imei = value; }
}
private DateTime timegmt;
public DateTime Timegmt
{
get { return timegmt; }
set { timegmt = value; }
}
private int arsInterval;//seconds
public int ArsInterval
{
get { return arsInterval; }
set { arsInterval = value; }
}
}
public class UnitGpsPos
{
public string IMEI;
public string lat;
public string lng;
public int speed;
public int status;
public int timeGMT;
public string adr;
public UnitGpsPos()
{
}
}
}