using System; using System.Collections.Generic; using System.Collections; using System.Data; using System.IO; using System.Drawing; using Npgsql; using System.Threading; using SafeMobileLib; using ESRI.ArcGIS.Display; using SafeMobileLib.DBmanagers; using System.Drawing.Imaging; namespace Safedispatch_4_0 { public class SMdb_access : IDisposable { Hashtable m_msg_list; //private ConvertDT convDT; private NpgsqlDataReader drSafe; private String Retur; private ArrayList retSafeSMposition; private ArrayList retSafeStatusAndDI; private ArrayList retSafeSMSrecv; private int sc_idSafe; private String RFIDSafe; private String PassNameSafe = "no name"; private String VehNameSafe = "no name"; private Double mindistSafe; private Double latTmpSafe, lngTmpSafe, newMinSafe; private String addrTmpSafe; public SMdb_access() { m_msg_list = new Hashtable(); retSafeSMposition = new ArrayList(); retSafeStatusAndDI = new ArrayList(); retSafeSMSrecv = new ArrayList(); //convDT = new ConvertDT(); } public void Dispose() { System.GC.SuppressFinalize(this); } public ArrayList get_lines() { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT * from addrline", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) ret.Add(new Lines(dr.GetDouble(0), dr.GetDouble(1), dr.GetDouble(2), dr.GetDouble(3), dr.GetString(4))); } conn.Close(); } return ret; } public ArrayList get_points() { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT * from addrpoint", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) ret.Add(new Points(dr.GetDouble(0), dr.GetDouble(1), dr.GetString(2), dr.GetString(3), dr.GetString(4), dr.GetString(5), dr.GetString(6))); } conn.Close(); } return ret; } public ArrayList get_lastPos3() { retSafeSMposition.Clear(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("SELECT lastpos.imei, lastpos.timeGMT, lastpos.lat, lastpos.lng, lastpos.di, lastpos.dox, lastpos.speed, lastpos.address, lastpos.status, lastpos.altitude, veh.name FROM lastpos INNER JOIN subscriber ON (lastpos.imei = subscriber.imei) INNER JOIN subscriber_history as sh ON (sh.sc_id = subscriber.sc_id) INNER JOIN vehicle as veh on (veh.id = sh.veh_id) inner join vehicle_user as vh on(vh.veh_id=veh.id) Where vh.user_id={0} Group by lastpos.imei, lastpos.timeGMT, lastpos.lat, lastpos.lng, lastpos.di, lastpos.dox, lastpos.speed, lastpos.address, lastpos.status, lastpos.altitude, veh.name ORDER BY veh.name", MainForm2.userIDX), conn)) { drSafe = cmd.ExecuteReader(); while (drSafe.Read()) { var obj = new SMposition { m_imei = drSafe.GetString(0), m_time = drSafe.GetInt32(1), m_lat = drSafe.GetDouble(2), m_lng = drSafe.GetDouble(3), m_di = (Byte)drSafe.GetInt32(4), m_do = (Byte)drSafe.GetInt32(5), m_speed = (Byte)drSafe.GetInt32(6), m_address = drSafe.GetString(7), m_motostat = (Byte)drSafe.GetInt32(8), m_alt = (drSafe.IsDBNull(9) ? 0 : drSafe.GetDouble(9)), m_vehName = drSafe.GetString(10) }; retSafeSMposition.Add(obj); } drSafe.Close(); } conn.Close(); } return retSafeSMposition; } public void oneConnectionHASH() { Hashtable ret = new Hashtable(); String s; Hashtable GroupList = new Hashtable(); Hashtable GroupCPSList = new Hashtable(); ArrayList arr = new ArrayList(); int OldGrpId = 0; string OldGroupNAme = ""; ZoneClass oldZone =null; Boolean first = true; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (var cmd = new NpgsqlCommand()) { cmd.Connection = conn; cmd.CommandText = "SELECT rfid,name,sc_id from passenger ORDER by name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var obj = new PassengerClass { RFID = dr.GetString(0), Name = dr.GetString(1), sc_id = dr.GetInt32(2) }; s = dr.GetString(0); try { ret.Add(s, obj); } catch (Exception ex) { SM.Debug("Fail to add RFID Name in hash RFID:" + s + ex.ToString()); } } } } MainForm2.PassHash = ret; try { cmd.CommandText = string.Format("UPDATE place set useridx ={0} where useridx=0", MainForm2.userIDX); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format("UPDATE zonename set useridx ={0} where useridx=0", MainForm2.userIDX); cmd.ExecuteNonQuery(); } catch (Exception ex) { SM.Debug("Error on update users IDX for place and zone with value 0 :" + ex.ToString()); } cmd.CommandText = "SELECT zn.idx,zn.name,znpnt.lat,znpnt.lng,znpnt.idx,zn.color,zn.useridx,zn.alarmtype,zn.sentmsg,zn.msgbody,zn.unitids,zn.sentemail,zn.email,zn.subj,zn.body,zn.sentmsg2,zn.msgbody2,zn.speed, zn.callout, zn.callout_severity" + " FROM zonename as zn" + " LEFT JOIN zonepoints as znpnt ON (zn.idx = znpnt.zone_id) " //+ " Group by zn.idx,zn.name,znpnt.lat,znpnt.lng,znpnt.idx,zn.color,zn.useridx,zn.alarmtype,zn.sentmsg,zn.msgbody,zn.unitids,zn.sentemail,zn.email,zn.subj,zn.body,zn.sentmsg2,zn.msgbody2,zn.speed, zn.callout, zn.callout_severity " + " ORDER by zn.name,znpnt.idx"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { if (OldGrpId != dr.GetInt32(0)) { if (first) first = false; else { ZoneClass g = new ZoneClass(oldZone, OldGrpId, arr); try { GroupList.Add(OldGrpId, g); } catch (Exception ex) { SM.Debug("Unable to add Group" + ex.ToString()); } } OldGrpId = dr.GetInt32(0); oldZone = new ZoneClass(dr.GetString(1), dr.GetInt32(5), dr.GetInt32(6), dr.GetInt32(7), dr.GetBoolean(8), dr.GetString(9), dr.GetString(10), dr.GetBoolean(11), dr.GetString(12), dr.GetString(13), dr.GetString(14), dr.GetBoolean(15), dr.GetString(16), dr.GetInt32(17), dr.GetBoolean(18), dr.GetInt16(19)); arr = new ArrayList(); } if (!dr.IsDBNull(2)) arr.Add(new PointonZone(dr.GetDouble(2), dr.GetDouble(3), dr.GetInt32(4))); } if (OldGrpId != 0) { ZoneClass g1 = new ZoneClass(oldZone, OldGrpId, arr); GroupList.Add(OldGrpId, g1); } } } MainForm2.ZoneIDHash = GroupList; ret = new Hashtable(); ArrayList tmp = new ArrayList(); cmd.CommandText = "select name,idx,useridx from place ORDER BY name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) tmp.Add(new VehandID(dr.GetString(0), dr.GetInt32(1), dr.GetInt32(2).ToString())); } } foreach (VehandID obj in tmp) { try { ret.Add(obj.sc_id, obj.Name); if (!MainForm2.LandIDuserIDX.ContainsKey(obj.sc_id)) MainForm2.LandIDuserIDX.Add(obj.sc_id, obj.Imei); } catch (Exception ex) { SM.Debug("Fail to add VECHICLE Name in hash vehnames:" + obj.sc_id + ex.ToString()); } } MainForm2.LandIDHash = ret; MainForm2.userIDHash.Clear(); MainForm2.passUserHash.Clear(); cmd.CommandText = "SELECT userid , login , password from users where user_type<>1 order by login"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { try { MainForm2.userIDHash.Add(dr.GetInt32(0), dr.GetString(1)); MainForm2.passUserHash.Add(dr.GetInt32(0), dr.GetString(2)); } catch (Exception ex) { SM.Debug("Unable to add user in hash table error:" + ex.ToString()); } } } } ret = new Hashtable(); cmd.CommandText = "SELECT name, id, pattern, displayed_name from car ORDER by name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Car obj = new Car(); obj.name = dr.GetString(0); obj.idx = dr.GetInt32(1); obj.iconPattern = dr.GetString(2); obj.displayedName = dr.GetString(3); try { ret.Add(obj.idx, obj); } catch (Exception ex) { SM.Debug("Unable to add car in hash table name:" + obj.name + " idx:" + obj.idx + " error:" + ex.ToString()); } } } } // check if resource directory exists if (!Directory.Exists("resource")) { Directory.CreateDirectory("resource"); } // check if resource directory exists if (!Directory.Exists("resource/cars")) { Directory.CreateDirectory("resource/cars"); } // for every car in the DB foreach (Car obj in ret.Values) { String fileNamePattern = Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern; // check if the image exists on the local hard disk if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png") && !obj.iconPattern.StartsWith("custom_")) { obj.fileName = System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; obj.listFilePath = System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + (Safedispatch_4_0.MainForm2.iconThemeType == SafeMobileLib.IconTheme.CLASSIC ? "" : "list_") + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; obj.googleAddresPath = "cars/" + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; } else { // the car icon doesn't exists Utils.WriteLine("Fetching icon for unit " + obj.displayedName + " [" + obj.idx + "]", ConsoleColor.Yellow); obj.fileName = System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; obj.listFilePath = System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + (Safedispatch_4_0.MainForm2.iconThemeType == SafeMobileLib.IconTheme.CLASSIC ? "" : "list_") + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; obj.googleAddresPath = "cars/" + Safedispatch_4_0.MainForm2.iconThemeType + "_" + obj.iconPattern + ".png"; DBiconsManager DBIcons = new DBiconsManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB); byte[] iconBytes = null; // get the icon from the database if exists or replace it with a default one if ((iconBytes = DBIcons.Get_Unit_Image(obj.idx)) == null) { // get unknown image from the resources System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); using (Stream resFilestream = a.GetManifestResourceStream("Dispatcher.Resources.classic_unknown.png")) { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { while (MainForm2.isRunning) { int read = resFilestream.Read(buffer, 0, buffer.Length); if (read <= 0) { // reached the end of the resource file iconBytes = ms.ToArray(); break; } // add read buffer into the memory stream ms.Write(buffer, 0, read); } } } } try { // save the image received from the database to a png file Bitmap bmp = new Bitmap(new MemoryStream(iconBytes)); bmp.Save(System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + fileNamePattern + ".png", ImageFormat.Png); Utils.WriteLine("Done Writing file to folder" + fileNamePattern, ConsoleColor.Red); // save image for the list if the theme type is not classic if (MainForm2.iconThemeType == SafeMobileLib.IconTheme.PIN) bmp.Save(System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + "list_" + fileNamePattern + ".png", ImageFormat.Png); Utils.WriteLine("Done Writing file to folder: " + fileNamePattern, ConsoleColor.DarkGray); } catch (Exception ex) { SM.Debug("Error write car icon to folder: " + ex.ToString() + "\n" + fileNamePattern); } } #region ARCGIS if (MainForm2.MapType == MapTYPE.ArcGis) { try { ESRI.ArcGIS.Display.IPictureMarkerSymbol bitmapPictureMarkerSymbolCls = new ESRI.ArcGIS.Display.PictureMarkerSymbolClass(); Image ArcgisImage = Image.FromFile(obj.fileName); ArcgisImage.Save(System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + fileNamePattern + ".bmp", ImageFormat.Bmp); bitmapPictureMarkerSymbolCls.CreateMarkerSymbolFromFile (ESRI.ArcGIS.Display.esriIPictureType.esriIPictureBitmap, System.Windows.Forms.Application.StartupPath + @"\resource\cars\" + fileNamePattern + ".bmp"); bitmapPictureMarkerSymbolCls.Angle = 0;//Minicar RgbColor rgbColor = new ESRI.ArcGIS.Display.RgbColor(); rgbColor.Red = 255; rgbColor.Green = 255; rgbColor.Blue = 255; bitmapPictureMarkerSymbolCls.BitmapTransparencyColor = rgbColor; bitmapPictureMarkerSymbolCls.Size = 24; bitmapPictureMarkerSymbolCls.XOffset = -12; bitmapPictureMarkerSymbolCls.YOffset = -12; obj.GISsymb = bitmapPictureMarkerSymbolCls; } catch (Exception ex) { SM.Debug("Error load cars for ARCGIS" + ex.ToString() + "\n" + obj.name); obj.GISsymb = null; } } #endregion } MainForm2.carlist = ret; GroupList = new Hashtable(); GroupCPSList = new Hashtable(); MainForm2.htGroupsKeyNAmeValueID = new Hashtable(); arr = new ArrayList(); ArrayList arrImei = new ArrayList(); OldGrpId = 0; OldGroupNAme = ""; Int32 OldGrpCpsId = 0; first = true; /*new NpgsqlCommand("SELECT grp.id,grp.name,v_grp.sc_id,grp.cps_id" + " FROM groups as grp" + " LEFT JOIN vehicle_group as v_grp ON (grp.id = v_grp.grp_ip) " + " Group by grp.id, grp.name, v_grp.sc_id,grp.cps_id ORDER by grp.name", conn))*/ cmd.CommandText = "SELECT grp.id,grp.name,v_grp.sc_id,grp.cps_id,sbs.imei, v.name" + " FROM groups as grp" + " LEFT JOIN vehicle_group as v_grp ON (grp.id = v_grp.grp_ip) " + " INNER JOIN subscriber as sbs ON (sbs.sc_id = v_grp.sc_id) " + " JOIN vehicle as v ON (v.id = v_grp.sc_id) " + " INNER JOIN vehicle_user vu on vu.veh_id = v.id" + " WHERE grp.type = " + (int)SafeMobileLib.GroupType.CATEGORY.value + " and vu.user_id = " + MainForm2.userIDX //+ " Group by grp.id, grp.name, v_grp.sc_id,grp.cps_id,sbs.imei,v.name " + " ORDER by grp.name, v.name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { if (OldGrpId != dr.GetInt32(0)) { if (first) first = false; else { GroupClass g = new GroupClass(OldGroupNAme, OldGrpId, OldGrpCpsId, arr, arrImei); //GroupList.Add(OldGrpId, g); try { GroupList.Add(OldGrpId, g); if (GroupCPSList[OldGrpCpsId] == null) GroupCPSList.Add((Int32)OldGrpCpsId, OldGroupNAme); } catch (Exception ex) { SM.Debug("Unable to add Group" + ex.ToString()); } MainForm2.htGroupsKeyNAmeValueID.Add(OldGroupNAme, OldGrpId); } OldGroupNAme = dr.GetString(1); OldGrpId = dr.GetInt32(0); OldGrpCpsId = dr.GetInt32(3); arr = new ArrayList(); arrImei = new ArrayList(); } try { if (!dr.IsDBNull(2)) { Int32 grpId = dr.GetInt32(2); if (MainForm2.GrpIdforScId.ContainsKey(grpId)) MainForm2.GrpIdforScId.Remove(grpId); MainForm2.GrpIdforScId.Add(grpId, new GroupClass(OldGroupNAme, OldGrpId, OldGrpCpsId)); } } catch (Exception ex) { SM.Debug("Unable to put sc_id in a group" + ex.ToString()); } if (!dr.IsDBNull(2)) { arr.Add(dr.GetInt32(2)); arrImei.Add(dr.GetString(4)); } } if (OldGrpId != 0) { GroupClass g1 = new GroupClass(OldGroupNAme, OldGrpId, OldGrpCpsId, arr, arrImei); GroupList.Add(OldGrpId, g1); if (GroupCPSList[OldGrpCpsId] == null) GroupCPSList.Add((Int32)OldGrpCpsId, OldGroupNAme); MainForm2.htGroupsKeyNAmeValueID.Add(OldGroupNAme, OldGrpId); } } } cmd.CommandText = "SELECT g.id,g.name,g.cps_id,g.type,g.r_gw_id, sm.sip_id" + " FROM groups g" + " JOIN sip_manager sm ON sm.id = g.id " + " WHERE g.type <> " + (int)SafeMobileLib.GroupType.CATEGORY.value + " and sm.type = " + (int)ContactType.GROUP; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Group grp = new Group(dr.GetInt32(0), dr.GetString(1), dr.GetInt32(2), dr.GetInt32(3), dr.GetInt32(4)); grp.SipID = dr.GetInt32(5); MainForm2.TalkGroups.Add(dr.GetInt32(0), grp); if (MainForm2.radioType == RADIOTYPE.EXCERA) { if(!MainForm2.GroupsAndRadioGW.ContainsKey(dr.GetInt32(2) + "." + dr.GetInt32(4))) MainForm2.GroupsAndRadioGW.Add(dr.GetInt32(2) + "." + dr.GetInt32(4), grp); } else { if (!MainForm2.GroupsAndRadioGW.ContainsKey(dr.GetInt32(0) + "." + dr.GetInt32(4))) MainForm2.GroupsAndRadioGW.Add(dr.GetInt32(2) + "." + dr.GetInt32(4), grp); } } } } MainForm2.GroupHash = GroupList; MainForm2.GroupCPSIDOnlyHash = GroupCPSList; try { MainForm2.GroupCPSIDOnlyHash = new Hashtable(); cmd.CommandText = "SELECT grp.name,grp.cps_id FROM groups as grp ORDER by grp.name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { if (MainForm2.GroupCPSIDOnlyHash[dr.GetInt32(1)] == null) MainForm2.GroupCPSIDOnlyHash.Add(dr.GetInt32(1), dr.GetString(0)); } } } } catch (Exception ex) { SM.Debug("Error on loading GroupHashOnly:" + ex.ToString()); } #region grups without categories try { MainForm2.GroupCPSIDOnlyHashWithoutCategory = new Dictionary(); cmd.CommandText = "SELECT grp.name,grp.cps_id, rg.\"ID\", rg.\"GW_ID\",rg.gw_type, sip.sip_id FROM groups as grp " + " LEFT JOIN radio_gw rg ON rg.\"ID\" = grp.r_gw_id" + " JOIN user_radio ur ON rg.\"ID\" = ur.radio_id" + " JOIN users u ON u.userid = ur.user_id" + " LEFT JOIN sip_manager sip on sip.id = grp.id " + " WHERE grp.type <> " + (int)SafeMobileLib.GroupType.CATEGORY.value + " AND sip.type = "+ (int)ContactType.GROUP + " AND u.userid = "+ MainForm2.userIDX + " ORDER by grp.name"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Group grp = new Group() { Name = dr.GetString(0), Id = dr.GetInt32(1), Gw_and_radioID = (dr.IsDBNull(2) || dr.IsDBNull(3)) ? "-1.-1" : dr.GetInt32(3) + "." + dr.GetInt32(2), Type = dr.IsDBNull(4) ? 0 : dr.GetInt32(4), SipID = dr.IsDBNull(5) ? 0 : dr.GetInt32(5) }; grp.SipID = MainForm2.radioType == RADIOTYPE.EXCERA ? grp.Id : grp.SipID; string key = grp.Id + grp.Gw_and_radioID; if (!MainForm2.GroupCPSIDOnlyHashWithoutCategory.ContainsKey(key)) //MainForm2.GroupCPSIDOnlyHashWithoutCategory.Add(dr.GetInt32(1), dr.GetString(0)); MainForm2.GroupCPSIDOnlyHashWithoutCategory.Add(key, grp); } } } } catch (Exception ex) { SM.Debug("Error on loading GroupHashOnly:" + ex.ToString()); } #endregion grups without categories tmp = new ArrayList(); cmd.CommandText = "select sms from defineSMS order by sms"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) //ret.Add(new Zone_type(dr.GetString(0), dr.GetInt32(1), 0)); tmp.Add(dr.GetString(0)); } } MainForm2.DefineSMSList = tmp; tmp = new ArrayList(); cmd.CommandText = "select \"ID\",\"GW_ID\",\"IP\" from radio_gw order by \"GW_ID\""; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) tmp.Add(new GatewayIDandIP(dr.GetInt32(0), dr.GetInt32(1), dr.GetString(2))); } } MainForm2.RadioListIP = tmp; tmp = new ArrayList(); cmd.CommandText = "SELECT sc_id,emsound,empopup,geosound,geopopup,speedsound,speedpopup,telemsound,telempopup FROM subscriber_alarm"; { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) tmp.Add(new SoundandPopup(dr.GetInt32(0), dr.GetBoolean(1), dr.GetBoolean(2), dr.GetBoolean(3), dr.GetBoolean(4), dr.GetBoolean(5), dr.GetBoolean(6), dr.GetBoolean(7), dr.GetBoolean(8))); } } MainForm2.AlarmforUnitList = tmp; cmd.CommandText = "select count(*) from user_radio"; MainForm2.cnt_User_Radio_assign = Convert.ToInt32(cmd.ExecuteScalar()); } conn.Close(); } //return ret; } public void AssignGatewayToUsers() { ArrayList listofUserID = new ArrayList(); ArrayList listofgateWays = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT userid from users where user_type=0", conn)) { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { listofUserID.Add(dr.GetInt32(0)); } } } using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT \"ID\" from radio_gw where voice_enabled=1", conn)) { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { listofgateWays.Add(dr.GetInt32(0)); } } } foreach (Int32 objUserID in listofUserID) foreach (Int32 objGateWaysID in listofgateWays) { try { using (var cmdx = new NpgsqlCommand("INSERT INTO user_radio VALUES(" + objGateWaysID + "," + objUserID + ")", conn)) { cmdx.ExecuteNonQuery(); Thread.Sleep(10); } } catch (Exception ee) { Console.WriteLine(ee.Message + " " + ee.StackTrace + " " + ee.Source); } } conn.Close(); } } public Hashtable get_all_RFID() { Hashtable ret = new Hashtable(); String s; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT rfid,name,sc_id from passenger ORDER by name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { var obj = new PassengerClass { RFID = dr.GetString(0), Name = dr.GetString(1), sc_id = dr.GetInt32(2) }; s = dr.GetString(0); try { ret.Add(s, obj); } catch (Exception ex) { SM.Debug("Fail to add RFID Name in hash RFID:" + s + ex.ToString()); } } dr.Close(); } conn.Close(); } return ret; } public ArrayList get_HistoryPositions2(string p_vehicle, Int32 p_start, Int32 p_stop) { ArrayList ret = new ArrayList(); Double Stop=0, Start=0; if ((p_start == 0) && (p_stop == 0)) p_stop = 2100000000; if (MainForm2.vehicleHT[p_vehicle] != null) { Start = (MainForm2.vehicleHT[p_vehicle] as Vehicle).sc_id * 10000000000 + p_start; Stop = (MainForm2.vehicleHT[p_vehicle] as Vehicle).sc_id * 10000000000 + p_stop; } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = ""; //if (MainForm2.HistSpeedLimit != 0) { Int32 limit = MainForm2.HistSpeedLimit; Int32 upperLimit = MainForm2.HistUpperSpeedLimit; if (MainForm2.isInMile) { limit = (Int32)(limit * 1.609344); upperLimit = (Int32)(upperLimit * 1.609344); } query = "SELECT lat,lng,speed,di,dox,timeGMT,heading,address,evnt_id,scevtime " + " FROM messages WHERE scevtime>" + Start + " and scevtime< " + Stop + (MainForm2.HistSpeedLimit != 0 ? " and speed >= " + limit : " ") + (MainForm2.HistUpperSpeedLimit != 0 ? " and speed <= " + upperLimit : " ") + " ORDER BY timeGMT"; } //else // query = String.Format("select lat,lng,speed,di,dox,timeGMT,heading,address,evnt_id,scevtime from messages where scevtime>{0} and scevtime<{1} ORDER BY timeGMT", Start, Stop); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { int cnt = 0; SM.Debug("#### History SQL: " + cmd.CommandText); using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { //if (((parent != null) && (parent.closeTabThread)) || ((parentMap != null) && (parentMap.closeTabThread)) || ((parentInfo != null) && (parentInfo.closeTabThread))) //if ((parent != null) && (parent.closeTabThread)) // break; cnt++; var pos = new SMposition { m_lat = (double)dr.GetDouble(0), m_lng = (double)dr.GetDouble(1), m_speed = (byte)dr.GetInt32(2), m_di = (byte)dr.GetInt16(3), m_do = (byte)dr.GetInt16(4), m_time = dr.GetInt32(5), m_vehName = p_vehicle, m_heading = 0, m_address = dr.IsDBNull(7) ? "" : dr.GetString(7), m_evnt_id = dr.GetInt32(8), m_scevMSSQL = dr.GetDouble(9) }; if ((pos.m_lat == 0) && (pos.m_lng == 0)) pos.m_address = "NO GPS FIX"; ret.Add(pos); } } } conn.Close(); } /*System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test3.txt"); Int32 cntx = 0; foreach (SMposition obj in ret) { file.WriteLine("#" + obj.m_lat + "#" + obj.m_lng + "#" + obj.m_speed + "#" + obj.m_address + "#"); cntx++; Console.WriteLine("Steps cnt:" + cntx); } file.Close();*/ //file.WriteLine(lines); /*String MyConStringGaby = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};Pooling=false;Timeout=60;CommandTimeout=0;", "10.120.1.114", "5432", "postgres", "wizdemo26", "safedispatchdb"); using (NpgsqlConnection conn2 = new NpgsqlConnection(MyConStringGaby)) { conn2.Open(); //NpgsqlCommand cmd = new NpgsqlCommand(); //cmd.Connection = conn2; Int32 cnt = 0; foreach (SMposition obj in ret) { file.WriteLine("#" + obj.m_lat + "#" + obj.m_lng + "#" + obj.m_speed + "#" + obj.m_address + "#"); cnt++; Console.WriteLine("Steps cnt:"+cnt); } conn2.Close(); } file.Close();*/ return ret; } public void Update_Speed_Limit(string key, int value) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE \"userSettings\" SET value='" + value + "' WHERE user_id=" + MainForm2.userIDX.ToString() +" AND key='" + key + "'", conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public ArrayList get_HistoryfillAddr() { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = "select lat,lng,address from messages where address<>''"; using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { int cnt = 0; using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { cnt++; var pos = new SMposition { m_lat = (double)dr.GetDouble(0), m_lng = (double)dr.GetDouble(1), m_address = (dr.IsDBNull(2) ? "" : dr.GetString(2)) }; ret.Add(pos); } } } conn.Close(); } return ret; } public Int32 get_Count_addr() { Int32 ret = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = "select count(address) from address"; using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) ret = Convert.ToInt32(cmd.ExecuteScalar()); conn.Close(); } return ret; } public Int32 get_Count_User_to_radio() { Int32 ret = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = "select count(*) from user_radio"; using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) ret = Convert.ToInt32(cmd.ExecuteScalar()); conn.Close(); } return ret; } public ArrayList get_HistoryTelem(Int32 sc_id, Int32 p_start, Int32 p_stop) { ArrayList ret = new ArrayList(); 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; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = String.Format("select lat,lng,timeGMT,address from messages where scevtime>{0} and scevtime<{1}", Start, Stop); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { int cnt = 0; using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { cnt++; var pos = new SMposition { m_lat = (double)dr.GetDouble(0), m_lng = (double)dr.GetDouble(1), m_time = dr.GetInt32(2), m_address = dr.IsDBNull(3) ? "" : dr.GetString(3), }; ret.Add(pos); } } } conn.Close(); } return ret; } public ArrayList get_HistorySpeed(Int32 sc_id, Int32 p_start, Int32 p_stop,Int32 exactTime) { ArrayList ret = new ArrayList(); Double Stop = 0, Start = 0,exact=0; if ((p_start == 0) && (p_stop == 0)) p_stop = 2100000000; Start = sc_id * 10000000000 + p_start; Stop = sc_id * 10000000000 + p_stop; exact = sc_id * 10000000000 + exactTime; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = String.Format("select lat,lng,timeGMT,address from messages where scevtime={0}", exact); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { int cnt = 0; using (NpgsqlDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { cnt++; var pos = new SMposition { m_lat = (double)dr.GetDouble(0), m_lng = (double)dr.GetDouble(1), m_time = dr.GetInt32(2), m_address = dr.IsDBNull(3) ? "" : dr.GetString(3), }; ret.Add(pos); return ret; } } } query = String.Format("select lat,lng,timeGMT,address from messages where scevtime>{0} and scevtime<{1}", Start, Stop); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { int cnt = 0; using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { cnt++; var pos = new SMposition { m_lat = (double)dr.GetDouble(0), m_lng = (double)dr.GetDouble(1), m_time = dr.GetInt32(2), m_address = dr.IsDBNull(3) ? "" : dr.GetString(3), }; ret.Add(pos); } } } conn.Close(); } return ret; } public ArrayList get_StudentPositions(string p_vehicle, UInt32 p_start, UInt32 p_stop) { ArrayList ret = new ArrayList(); Double Stop=0, Start=0; if ((p_start == 0) && (p_stop == 0)) p_stop = 2100000000; if (MainForm2.vehicleHT[p_vehicle] != null) { Start = (MainForm2.vehicleHT[p_vehicle] as Vehicle).sc_id * 10000000000 + p_start; Stop = (MainForm2.vehicleHT[p_vehicle] as Vehicle).sc_id * 10000000000 + p_stop; } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("select sc_id,lat,lng,timeGMT,rfid from messages where scevtime>{0} and scevtime<{1} and rfid>''", Start,Stop), conn)) { int cnt = 0; using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { cnt++; var pos = new SMposition { m_posID = dr.GetInt32(0), m_lat = (double)dr.GetDouble(1), m_lng = (double)dr.GetDouble(2), m_time = dr.GetInt32(3), m_imei = cnt.ToString(), m_address = dr.GetString(4), m_vehName = p_vehicle }; ret.Add(pos); } } } conn.Close(); } return ret; } public ArrayList get_vehicles_and_ID(out Hashtable VehIDHash, out Hashtable VehIMEIHash, out ArrayList arVehSCID) { VehIDHash = new Hashtable(); VehIMEIHash = new Hashtable(); arVehSCID = new ArrayList(); ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); string cmdSQL = String.Format("SELECT veh.name,veh.time_route,veh.driver_id,sub.sc_id,sub.imei,veh.id, veh.is_stolen, veh.\"GPS_reporting_interval\", gr.\"name\", gr.id, " + " sa.emergency, sa.zone, sa.loneworker, sa.speed, sa.email, sa.landmark, veh.type, sip.sip_id, sgw.gateway_id, sgw.radio_gw_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 sip_manager as sip on sip.id = sub.sc_id and sip.type = "+ (int)ContactType.UNIT+ " INNER JOIN vehicle_user AS vh ON (vh.veh_id=veh.id) " + "LEFT JOIN subs_gateway as sgw ON (sgw.sc_id = sub.sc_id) " + "LEFT JOIN groups AS gr ON " + "(gr.id = (SELECT grp_ip FROM vehicle_group vg join groups g on vg.grp_ip = g.id WHERE sc_id = sub.sc_id and g.type = " + (int)SafeMobileLib.GroupType.CATEGORY.value + " )) " + "LEFT JOIN subscriber_alarm AS sa ON (sh.sc_id = sa.sc_id) " + "WHERE vh.user_id={0} and veh.active = true " + //"GROUP BY veh.name,sub.sc_id,sub.imei,veh.id,veh.time_route,veh.driver_id,veh.is_stolen,veh.\"GPS_reporting_interval\", gr.\"name\", gr.id, " + //" sa.emergency, sa.zone, sa.loneworker, sa.speed, sa.email, sa.landmark, veh.type, sip.sip_id, sgw.gateway_id, sgw.radio_gw_id " + "ORDER BY veh.name", MainForm2.userIDX); Utils.WriteLine(cmdSQL); using (NpgsqlCommand cmd = new NpgsqlCommand(cmdSQL, conn)) //using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("SELECT veh.name,veh.time_route,veh.driver_id,sub.sc_id,sub.imei,veh.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) inner join vehicle_user as vh on(vh.veh_id=veh.id) Where vh.user_id={0} Group by veh.name,sub.sc_id,sub.imei,veh.id,veh.time_route,veh.driver_id ORDER BY veh.name", MainForm2.userIDX), conn)) { using (NpgsqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { string veh_name = dr["name"] != DBNull.Value ? dr["name"].ToString() : ""; int sc_id = dr["sc_id"] != DBNull.Value ? int.Parse(dr["sc_id"].ToString()) : 0; string imei = dr["imei"] != DBNull.Value ? dr["imei"].ToString() : ""; int veh_id = dr["id"] != DBNull.Value ? int.Parse(dr["id"].ToString()) : 0; int driver_id = dr["driver_id"] != DBNull.Value ? int.Parse(dr["driver_id"].ToString()) : 0; int isStolen = dr["is_stolen"] != DBNull.Value ? int.Parse(dr["is_stolen"].ToString()) : 0; int time_route = dr["time_route"] != DBNull.Value ? int.Parse(dr["time_route"].ToString()) : 0; int gps_reporting_interval = dr["GPS_reporting_interval"] != DBNull.Value ? int.Parse(dr["GPS_reporting_interval"].ToString()) : 0; int canMakeSipCalls = dr["type"] != DBNull.Value ? int.Parse(dr["type"].ToString()) : 0; int sip_id = dr["sip_id"] != DBNull.Value ? int.Parse(dr["sip_id"].ToString()) : -1; VehandID veh = new VehandID(veh_name, sc_id, imei, time_route, driver_id, veh_id, gps_reporting_interval, false, (isStolen == 1) ? true : false); veh.groupName = dr.IsDBNull(8) ? "" : dr.GetString(8); veh.groupID = dr.IsDBNull(9) ? 0 : dr.GetInt32(9); veh.GwandRadioID = ((dr["gateway_id"] != DBNull.Value) ? dr["gateway_id"].ToString() : "0") + "." + ((dr["radio_gw_id"] != DBNull.Value) ? dr["radio_gw_id"].ToString() : "0"); veh.hasEmergencyAlert = (dr["emergency"] != DBNull.Value) ? dr["emergency"].ToString().Equals("1") : false; veh.hasZoneAlert = (dr["zone"] != DBNull.Value) ? dr["zone"].ToString().Equals("1") : false; veh.hasLoneWorkerAlert = (dr["loneworker"] != DBNull.Value) ? dr["loneworker"].ToString().Equals("1") : false; veh.hasSpeedAlert = (dr["speed"] != DBNull.Value) ? dr["speed"].ToString().Equals("1") : false; veh.hasEmailAlert = (dr["email"] != DBNull.Value) ? dr["email"].ToString().Equals("1") : false; veh.hasLandmarkAlert = (dr["landmark"] != DBNull.Value) ? dr["landmark"].ToString().Equals("1") : false; veh.hasTelemetryAlert = true; veh.canMakeSipCalls = (canMakeSipCalls == 1) ? true : false; veh.sipID = sip_id; ret.Add(veh); VehIDHash.Add(veh.sc_id, veh.Name); VehIMEIHash.Add(veh.Imei, veh.Name); arVehSCID.Add(new VehandID(veh.Name, veh.sc_id, null)); } } } conn.Close(); } return ret; } public ArrayList get_all_Alarm_Pop_Sound() { ArrayList ret = new ArrayList(); NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT sc_id,emsound,empopup,geosound,geopopup,speedsound,speedpopup,telemsound,telempopup, " + " emergency, zone, loneworker, speed, email, landmark " + " FROM subscriber_alarm", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { bool hasEmergencyAlert = dr.GetString(dr.GetOrdinal("emergency")).Equals("1"); bool hasZoneAlert = dr.GetString(dr.GetOrdinal("zone")).Equals("1"); bool hasLoneWorkerAlert = dr.GetString(dr.GetOrdinal("loneworker")).Equals("1"); bool hasSpeedAlert = dr.GetString(dr.GetOrdinal("speed")).Equals("1"); bool hasEmailAlert = dr.GetString(dr.GetOrdinal("email")).Equals("1"); bool hasLandmarkAlert = dr.GetString(dr.GetOrdinal("landmark")).Equals("1"); ret.Add( new SoundandPopup() { sc_id = dr.GetInt32(0), EMsound = (hasEmergencyAlert ? dr.GetBoolean(1) : false), EMpopup = (hasEmergencyAlert ? dr.GetBoolean(2) : false ), GEOsound = (hasZoneAlert ? dr.GetBoolean(3) : false), GEOpopup = (hasZoneAlert ? dr.GetBoolean(4) : false), SPEEDsound = (hasSpeedAlert ? dr.GetBoolean(5) : false), SPEEDpopup = (hasSpeedAlert ? dr.GetBoolean(6) : false), TELEMsound = (true ? dr.GetBoolean(7) : false), TELEMpopup = (true ? dr.GetBoolean(8) : false), } ); } dr.Close(); } conn.Close(); } return ret; } public ArrayList get_land_and_ID() { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("select name,idx,useridx from place ORDER BY name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) ret.Add(new VehandID(dr.GetString(0), dr.GetInt32(1), dr.GetInt32(2).ToString())); } conn.Close(); } return ret; } /// /// Get All Landmarks as defined in the DB. /// /// public List GetAllLandmarks() { List landmarks = new List(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT p.name, p.note, p.lat, p.lng, p.idx, p.type_id, p.address, p.useridx, " + " pt.type_name, p.icon_size, pt.icon_name, p.color, p.callout, p.callout_severity" + " FROM place AS p " + " INNER JOIN placetype AS pt ON (pt.type_id = p.type_id)" + " ORDER BY name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { landmarks.Add( new LandmarkUI() { Name = dr.GetString(0), Description = dr.GetString(1), Latitude = dr.GetDouble(2), Longitude = dr.GetDouble(3), Idx = dr.GetInt32(4), TypeIdx = dr.GetInt32(5), Address = dr.GetString(6), UserIdx = dr.GetInt32(7), Size = dr.IsDBNull(9) ? Safedispatch_4_0.LandmarkUI.IconSize.MEDIUM : Safedispatch_4_0.LandmarkUI.IconSize.GetIconSize(dr.GetString(9)), IconName = dr.IsDBNull(10) ? "" : dr.GetString(10), Color = dr.IsDBNull(11) ? System.Drawing.ColorTranslator.FromHtml("#000000") : System.Drawing.ColorTranslator.FromHtml(dr.GetString(11)), Callout = (dr.IsDBNull(12) ? false : dr.GetBoolean(12)), CalloutSeverity = (dr.IsDBNull(13) ? 3 : dr.GetInt16(13)) }); } dr.Close(); } conn.Close(); } return landmarks; } /// /// Get All Landmarks Types as defined in the DB. /// /// public Dictionary GetAllLandmarkTypes() { Dictionary landmarkTypes = new Dictionary(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { int crt = 0; conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT type_id, type_name, icon_name" + " FROM placetype" + " ORDER BY type_name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { landmarkTypes.Add(dr.GetInt32(0), new LandmarkType() { CrtIdx = crt++, Idx = dr.GetInt32(0), TypeName = dr.GetString(1), IconName = dr.IsDBNull(2) ? "" : dr.GetString(2) }); } dr.Close(); } conn.Close(); } return landmarkTypes; } /// /// Get All Geofences as defined in the DB. /// /// List containing all Geofences public List GetAllGeofences() { List geofences = new List(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(" SELECT Z.name, Z.idx, Z.color, Z.useridx, Z.alarmtype, " + " Z.sentmsg, Z.msgbody, Z.unitids, Z.sentemail, Z.email, Z.subj, Z.body, Z.imeilist, Z.sentmsg2, " + " Z.msgbody2, Z.speed, Z.fill_color, Z.fill_opacity, Z.border_color, Z.border_width, Z.border_opacity, " + " Z.callout, Z.callout_severity," + " ZP.points " + " FROM zonename AS Z " + " INNER JOIN (SELECT array_agg(idx || '#' || lat || '#' || lng) as points, zone_id " + " FROM zonepoints " + " GROUP BY zone_id) AS ZP ON (ZP.zone_id = Z.idx) " + " ORDER BY name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { List unitsIdsList = new List(); List unitsImeisList = new List(); String unitsIds = (dr.IsDBNull(7) ? "" : dr.GetString(7)); String unitsImeis = (dr.IsDBNull(12) ? "" : dr.GetString(12)); // split units ids String[] unitsIdsArray = unitsIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach(String id in unitsIdsArray) { int crt_id = 0; // add id only if valid if (Int32.TryParse(id, out crt_id)) unitsIdsList.Add(crt_id); } // split units imeis String[] unitsImeisArray = unitsImeis.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (String imei in unitsImeisArray) { int crt_imei = 0; // add imei only if valid if (Int32.TryParse(imei, out crt_imei)) unitsImeisList.Add(crt_imei); } List pointsList = new List(); // get all points for this geofence String[] geofencePoints = (dr.IsDBNull(21) ? new String[] {} : (dr["points"] as String[])); // remove { and } from returning string //geofencePoints = geofencePoints.Replace('{',' ').Replace('}',' ').Trim(); // parse each point foreach (String str in geofencePoints) { // split current point by its delimiters string[] split = str.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries); // get the values from the string Int32 pointId = 0; double lat = 0; double lng = 0; Int32.TryParse(split[0], out pointId); //Double.TryParse(split[1], out lat); //Double.TryParse(split[2], out lng); MainForm2.SafeConvertStringToDouble(split[1], split[2], out lat, out lng); // create the new geofence point GeofencePoint gp = new GeofencePoint() { Idx = pointId, Latitude = lat, Longitude = lng, GeofeceId = dr.GetInt32(1) }; // add the geofence point to the list pointsList.Add(gp); } // get values from current row and add them to a new geofence UI object geofences.Add( new GeofenceUI() { Name = dr.GetString(0), Idx = dr.GetInt32(1), UserIdx = dr.GetInt32(3), AlertTypee = (dr.IsDBNull(4) ? GeofenceUI.AlertType.IN : (GeofenceUI.AlertType)dr.GetInt32(4)), SendUnitMessage = (dr.IsDBNull(13) ? false : dr.GetBoolean(13)), UnitMessage = (dr.IsDBNull(14) ? "" : dr.GetString(14)), UnitsIds = unitsIdsList, SendEmail = (dr.IsDBNull(8) ? false : dr.GetBoolean(8)), EmailAddress = (dr.IsDBNull(9) ? "" : dr.GetString(9)), EmailSubject = (dr.IsDBNull(10) ? "" : dr.GetString(10)), EmailBody = (dr.IsDBNull(11) ? "" : dr.GetString(11)), UnitsImeis = unitsImeisList, SendUnitsMessage = (dr.IsDBNull(5) ? false : dr.GetBoolean(5)), UnitsMessage = (dr.IsDBNull(6) ? "" : dr.GetString(6)), SpeedLimit = dr.GetInt32(15), FillColor = (dr.IsDBNull(16) ? System.Drawing.ColorTranslator.FromHtml("#000000") : System.Drawing.ColorTranslator.FromHtml(dr.GetString(16))), FillOpacity = (dr.IsDBNull(17) ? 0.7 : dr.GetDouble(17)), BorderColor = (dr.IsDBNull(18) ? System.Drawing.ColorTranslator.FromHtml("#000000") : System.Drawing.ColorTranslator.FromHtml(dr.GetString(18))), BorderWidth = (dr.IsDBNull(19) ? 4 : dr.GetInt32(19)), BorderOpacity = (dr.IsDBNull(20) ? 0.7 : dr.GetDouble(20)), Callout = (dr.IsDBNull(21) ? false : dr.GetBoolean(21)), CalloutSeverity = (dr.IsDBNull(22) ? 3 : dr.GetInt16(22)), points = pointsList }); } dr.Close(); } conn.Close(); } return geofences; } public void get_land_and_ID_Hash() { MainForm2.LandIDHash = new Hashtable(); MainForm2.LandIDuserIDX = new Hashtable(); ArrayList tmp = get_land_and_ID(); foreach (VehandID obj in tmp) { try { MainForm2.LandIDHash.Add(obj.sc_id, obj.Name); MainForm2.LandIDuserIDX.Add(obj.sc_id, obj.Imei); } catch (Exception ex) { SM.Debug("Fail to add VECHICLE Name in hash vehnames:" + obj.sc_id + ex.ToString()); } } } public ArrayList get_all_GatewaywithIDandIP() { ArrayList ret = new ArrayList(); NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("select \"ID\",\"GW_ID\",\"IP\" from radio_gw", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) ret.Add(new GatewayIDandIP(dr.GetInt32(0), dr.GetInt32(1), dr.GetString(2))); } conn.Close(); } return ret; } public ArrayList get_all_DefSMS() { ArrayList ret = new ArrayList(); NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("select sms from defineSMS order by sms", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) //ret.Add(new Zone_type(dr.GetString(0), dr.GetInt32(1), 0)); ret.Add(dr.GetString(0)); } conn.Close(); } return ret; } public Boolean test_user(int userID, String pass) { NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select login from users where userid='{0}' and password ='{1}'", userID,pass), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) return true; } conn.Close(); } return false; } public void Clean_older_info(String timelimit) { NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM messages where timeGMT <{0}",timelimit), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void update_car_color(String name, Int32 col) { NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE vehicle SET time_route={0} WHERE name='{1}'", col, name), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void update_vehicle_icon(Int32 idx, Int32 driver_id) { NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE vehicle SET driver_id={0} WHERE id={1}",driver_id, idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public Place test_place_exist(String nameParam, String idxmod) { Place ret = null; Char c = (char)39; String name = nameParam; if (name != null) name = name.Replace(c, '`'); NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT p.name , p.note , p.lat , p.lng , p.address, t.type_name, p.callout, p.callout_severity from place p, placetype t where p.type_id=t.type_id and p.name = '{0}' and p.idx<>{1}",name,idxmod), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { ret = new Place { name = dr.GetString(0), desc = dr.GetString(1), lat = dr.GetDouble(2), lng = dr.GetDouble(3), address = dr.GetString(4), type = dr.GetString(5), callout = dr.GetBoolean(6), callout_severity=dr.GetInt16(7) }; } dr.Close(); } conn.Close(); } return ret; } public String Get_DB_version() { String name = ""; NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT version,idx from updatelist where idx IN (select max(idx) from updatelist)", conn)) name = (String)cmd.ExecuteScalar(); conn.Close(); } return name; } public void Insert_Place_GIS(String p_name, String p_desc, Double lat, Double lng, String p_id,String Address,Int32 useridx) { Char c = (char)39; String name = p_name; if (name != null) name = name.Replace(c, '`'); String descris = p_desc; if (descris != null) descris = descris.Replace(c, '`'); String addr = Address; if (addr != null) { addr = addr.Replace(c, '`'); addr = addr.Replace(',', ' '); } NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString); { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO place (name,note,lat,lng,type_id,address,useridx) VALUES('{0}','{1}',@lat,@lng,{2},'{3}',{4})",name,descris,p_id,addr,useridx); cmd.Parameters.Add("@lat", NpgsqlTypes.NpgsqlDbType.Double).Value = lat; cmd.Parameters.Add("@lng", NpgsqlTypes.NpgsqlDbType.Double).Value = lng; cmd.Prepare(); cmd.ExecuteNonQuery(); conn.Close(); } } public void Insert_Place(String p_name, String p_desc, Double lat, Double lng, String p_id, String Address, Int32 useridx, Color color, LandmarkUI.IconSize iconSize, Boolean callout, int callout_severity) { Char c = (char)39; String name = p_name; if (name != null) name = name.Replace(c, '`'); String descris = p_desc; if (descris != null) descris = descris.Replace(c, '`'); String addr = Address; if (addr != null) { addr = addr.Replace(c, '`'); addr = addr.Replace(',', ' '); } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { // get the hex colors for the desired color String hexColor = "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO place (name,note,lat,lng,type_id,address,useridx, color, icon_size, callout, callout_severity) " + " VALUES('{0}','{1}',@lat,@lng,{2},'{3}',{4}, '{5}', '{6}', {7}, {8})", name, descris, p_id, addr, useridx, hexColor, iconSize.ToDBString(), callout, callout_severity); cmd.Parameters.Add("@lat", NpgsqlTypes.NpgsqlDbType.Double).Value = lat; cmd.Parameters.Add("@lng", NpgsqlTypes.NpgsqlDbType.Double).Value = lng; cmd.Prepare(); cmd.ExecuteNonQuery(); conn.Close(); } } public Int32 Get_Last_Place_Insert() { Int32 returnValue = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT max(idx) from place", conn)) returnValue = (Int32)cmd.ExecuteScalar(); conn.Close(); } return returnValue; } public void Insert_Address(String p_addr, Double lat, Double lng) { Char c = (char)39; String addr = p_addr; if (addr != null) { addr = addr.Replace(c, '`'); addr = addr.Replace(',', ' '); } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO address (lat,lng,address,type) VALUES(@lat,@lng,'{0}',1)", addr); cmd.Parameters.Add("@lat", NpgsqlTypes.NpgsqlDbType.Double).Value = lat; cmd.Parameters.Add("@lng", NpgsqlTypes.NpgsqlDbType.Double).Value = lng; cmd.Prepare(); cmd.ExecuteNonQuery(); conn.Close(); } } public ReportDefinition Insert_Report(Int32 startdate, Int32 stopdate,String unit_ids,Int32 geo_id,Int32 type,Int32 idle, Int32 repID,String email,Boolean LatLng, String TicketStatus, String TicketDateType, String days, String reportType, Boolean is_activated, Int32 id) { unit_ids = unit_ids.Replace("\"","").Replace("'",""); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("UPDATE reports SET startdate={0}, stopdate={1}, unit_ids='{2}', geofence_id={3}, " + "type_stat={4}, idletime={5}, report_id={6}, email='{7}', latlng={8}, userid={9}, ticket_status='{10}', " + "ticket_date_type='{11}', type='{12}', day='{13}', is_activated='{14}' WHERE idx = {15} AND unit_ids='{2}'; ", startdate, stopdate, unit_ids, geo_id, type, idle, repID, email, LatLng, MainForm2.userIDX, TicketStatus, TicketDateType, reportType, days, is_activated, id) + Environment.NewLine + string.Format("INSERT INTO reports (startdate,stopdate,unit_ids,geofence_id,type_stat," + "idletime,report_id,email,latlng,userid, ticket_status, ticket_date_type, type, day, is_activated) " + //"VALUES({0},{1},'{2}',{3},{4},{5},{6},'{7}',{8},{9},'{10}','{11}', '{12}', '{13}', 'TRUE')", " SELECT {0},{1},'{2}',{3},{4},{5},{6},'{7}',{8},{9},'{10}','{11}', '{12}', '{13}', 't'" + " WHERE NOT EXISTS (SELECT 1 FROM reports WHERE report_id=" + repID + " AND unit_ids='{2}' and userid={9}) RETURNING idx ", startdate, stopdate, unit_ids, geo_id, type, idle, repID, email, LatLng, MainForm2.userIDX, TicketStatus, TicketDateType, reportType, days); //cmd.ExecuteNonQuery(); //conn.Close(); // execute and get index if inserted NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { id = dr.GetInt32(0); } dr.Close(); conn.Close(); return new ReportDefinition() { StartDate = startdate, EndDate = stopdate, UnitIds = unit_ids, GeofenceId = geo_id, TypeStat = type, ReportId = repID, Email = email, IdleTime = idle, Idx = id, LatLng = LatLng, UserId = MainForm2.userIDX, TicketStatus = TicketStatus, TicketDate = TicketDateType, ReportType = reportType, Day = days, IsActive = true, }; } } /// /// Get All Report Definitions as defined in the DB. /// /// public Dictionary GetReportsForUser(Int64 userId) { Dictionary reportsDefinitions = new Dictionary(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand( "SELECT startdate, stopdate, unit_ids, geofence_id, type_stat, report_id, " + "email, idletime, idx, latlng, userid, ticket_status, ticket_date_type, " + "\"type\", \"day\", is_activated " + "FROM reports " + "WHERE userid = " + userId + " " + "ORDER BY report_id ASC", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string unitIds = dr.IsDBNull(2) ? "" : dr.GetString(2); int reportId = dr.IsDBNull(5) ? 0 : dr.GetInt32(5); string key = reportId + "-" + unitIds; if (!reportsDefinitions.ContainsKey(key)) reportsDefinitions.Add(key, new ReportDefinition() { StartDate = dr.GetInt32(0), EndDate = dr.GetInt32(1), UnitIds = unitIds, GeofenceId = dr.IsDBNull(3) ? 0 : dr.GetInt32(3), TypeStat = dr.IsDBNull(4) ? 0 : dr.GetInt32(4), ReportId = dr.IsDBNull(5) ? 0 : dr.GetInt32(5), Email = dr.IsDBNull(6) ? "" : dr.GetString(6), IdleTime = dr.IsDBNull(7) ? 0 : dr.GetInt32(7), Idx = dr.GetInt32(8), LatLng = dr.IsDBNull(9) ? false : dr.GetBoolean(9), UserId = dr.IsDBNull(10) ? 0 : dr.GetInt32(10), TicketStatus = dr.IsDBNull(11) ? "" : dr.GetString(11), TicketDate = dr.IsDBNull(12) ? "" : dr.GetString(12), ReportType = dr.IsDBNull(13) ? "" : dr.GetString(13), Day = dr.IsDBNull(14) ? "" : dr.GetString(14), IsActive = dr.IsDBNull(15) ? false : dr.GetBoolean(15), }); } dr.Close(); } conn.Close(); } return reportsDefinitions; } public void EnableDisableReport(Int64 id, Int64 userId, Boolean isActive) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("UPDATE reports SET is_activated='{0}' " + " WHERE idx = {1} AND userid = {2} ",isActive , id, userId); cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_all_old_alarms(String idx_new,String idx_old) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("UPDATE geozoneinout SET zone_id={0} where zone_id={1}", idx_new,idx_old); cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_all_old_Reports(String idx_new, String idx_old,Boolean Geofence) { Int32 type = 1; if (!Geofence) type = 4; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("UPDATE reports SET geofence_id={0} where geofence_id={1} and type_stat={2}", idx_new, idx_old,type); cmd.ExecuteNonQuery(); conn.Close(); } } public void Insert_Address_with_one_connection(String p_addr, Double lat, Double lng) { Char c = (char)39; String addr = p_addr; if (addr != null) { addr = addr.Replace(c, '`'); addr = addr.Replace(',', ' '); } Int32 nrofErrors =0; while (nrofErrors<2) { try { NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = connAddress; cmd.CommandText = string.Format("INSERT INTO address (lat,lng,address,type) VALUES(@lat,@lng,'{0}',1)", addr); cmd.Parameters.Add("@lat", NpgsqlTypes.NpgsqlDbType.Double).Value = lat; cmd.Parameters.Add("@lng", NpgsqlTypes.NpgsqlDbType.Double).Value = lng; cmd.Prepare(); cmd.ExecuteNonQuery(); nrofErrors=3; } catch (Exception ex) { SM.Debug("Error on get address: "+ex.ToString()); nrofErrors++; CloseConnectionForAddress(); Thread.Sleep(100); InitConnectionForAddress(); } } } public void UpdateInsertAddressHash(String p_addr, Double lat, Double lng) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("UPDATE address SET address='{0}' WHERE lat = {1} AND lng = {2}; ", p_addr, lat, lng) + Environment.NewLine + string.Format("INSERT INTO address (lat,lng,address,type) " + " SELECT {0},{1}, '{2}', {3}" + " WHERE NOT EXISTS (SELECT 1 FROM address WHERE lat=" + lat + " AND lng=" + lng +" )", lat, lng, p_addr, 1); // execute and get index if inserted NpgsqlDataReader dr = cmd.ExecuteReader(); conn.Close(); } } private NpgsqlConnection connX = null; public void INIT() { connX = new NpgsqlConnection(MainForm2.MyConString); connX.Open(); } public void CLOSE() { connX.Close(); } public void Insert_Address_fast(String p_addr, Double lat, Double lng) { Char c = (char)39; String addr = p_addr; if (addr != null) { addr = addr.Replace(c, '`'); addr = addr.Replace(',', ' '); } NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = connX; cmd.CommandText = string.Format("INSERT INTO address (lat,lng,address,type) VALUES(@lat,@lng,'{0}',1)", addr); cmd.Parameters.Add("@lat", NpgsqlTypes.NpgsqlDbType.Double).Value = lat; cmd.Parameters.Add("@lng", NpgsqlTypes.NpgsqlDbType.Double).Value = lng; cmd.Prepare(); cmd.ExecuteNonQuery(); } public void Update_address_with_one_connection(String p_imei, Int32 p_sc_id, Int32 p_timeGMT, String p_address, Double LAT, Double LNG) { Char c = (char)39; String name = p_address; if (name != null) name = name.Replace(c, '`'); Int32 nrofErrors =0; Int64 intLAT = 0, intLNG = 0; intLAT = (Int64)(LAT * 10000); intLNG = (Int64)(LNG * 10000); while (nrofErrors<2) { try { Double scev_id; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE lastpos set address ='{0}' where imei='{1}' and round(lat*10000)={2} and round(lng*10000)={3}", name, p_imei,intLAT,intLNG), connAddress)) cmd.ExecuteNonQuery(); scev_id = p_sc_id * 10000000000 + p_timeGMT; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE messages set address ='{0}' where scevtime={1}", name, scev_id), connAddress)) cmd.ExecuteNonQuery(); nrofErrors=3; } catch (Exception ex) { SM.Debug("Error on get address: "+ex.ToString()); nrofErrors++; CloseConnectionForAddress(); Thread.Sleep(100); InitConnectionForAddress(); } } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); Double scev_id; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE lastpos set address ='{0}' where imei='{1}' and round(lat*10000)={2} and round(lng*10000)={3}", name, p_imei,intLAT,intLNG), conn)) cmd.ExecuteNonQuery(); scev_id = p_sc_id * 10000000000 + p_timeGMT; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE messages set address ='{0}' where scevtime={1}", name, scev_id), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_address_speed(Int32 p_sc_id, Int32 p_timeGMT, String p_address, Double p_lat, Double p_lng) { Char c = (char)39; String name = p_address; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); Double scev_id; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE speedalarm set address='{2}', lat={3}, lng={4} where sc_id={0} and timegmt={1}", p_sc_id, p_timeGMT, name, p_lat, p_lng), conn)) cmd.ExecuteNonQuery(); scev_id = p_sc_id * 10000000000 + p_timeGMT; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE messages set address ='{0}' where scevtime={1}", name, scev_id), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_address_SMS_Location(Int32 p_sc_id, Int32 p_timeGMT, String p_address, Double p_lat, Double p_lng) { Char c = (char)39; String name = p_address; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); Double scev_id; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE sms set address='{2}', lat={3}, lng={4} where sc_id_sour={0} and timegmt={1}", p_sc_id, p_timeGMT, name, p_lat, p_lng), conn)) cmd.ExecuteNonQuery(); scev_id = p_sc_id * 10000000000 + p_timeGMT; conn.Close(); } } public void Update_address_telem(Int32 p_sc_id, Int32 p_timeGMT, String p_address, Double p_lat, Double p_lng) { Char c = (char)39; String name = p_address; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("UPDATE telemetry_history set address='{2}', lat={3}, lng={4} where sc_id={0} and timegmt={1}", p_sc_id, p_timeGMT,name, p_lat, p_lng), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_address_emergency(Int32 p_sc_id, Int32 p_timeGMT, String p_address, Double p_lat, Double p_lng) { Char c = (char)39; String name = p_address.Substring(0,45); if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("UPDATE emergalarm set address='{2}', lat={3}, lng={4} where sc_id={0} and timegmt={1}", p_sc_id, p_timeGMT, name, p_lat, p_lng), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_address_hist(String scevMYSQL, Double scevMSSQL, String p_address) { Char c = (char)39; String name = p_address; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE messages set address ='{0}' where scevtime={1}", name, scevMSSQL), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public String Insert_Zone(String p_name, Int32 color, ArrayList Points, Int32 useridx, Int32 Alarmtype, Boolean sentmsg, String MsgBody, String unitids, Boolean sentemail, String email, String subj, String body, String imeilist, Boolean sentmsg2, String MsgBody2,Int32 Speed) { String name = p_name; String idx = "0"; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO zonename (name,color,useridx,alarmtype,sentmsg,msgbody,unitids," + "sentemail,email,subj,body,imeilist,sentmsg2,msgbody2,speed) VALUES('{0}',{1},{2},{3},{4},'{5}','{6}',{7},'{8}','{9}','{10}','{11}',{12},'{13}',{14})", name, color, useridx, Alarmtype, sentmsg, MsgBody, unitids, sentemail, email, subj, body, imeilist,sentmsg2,MsgBody2,Speed); cmd.ExecuteNonQuery(); Thread.Sleep(200); cmd = new NpgsqlCommand("SELECT max(idx) from zonename", conn); idx = ((Int32)cmd.ExecuteScalar()).ToString(); foreach (PointonZone obj in Points) { cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO zonepoints (lat,lng,zone_id) VALUES(@lat1,@lng1,{0})", idx); cmd.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = obj.lat; cmd.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = obj.lng; cmd.Prepare(); cmd.ExecuteNonQuery(); } conn.Close(); } return idx; } public Int32 InsertGeofence(String name, Color fillColor, Decimal fillOpacity, Color borderColor, Decimal borderWidth, Decimal borderOpacity, List points, GeofenceUI.AlertType alertType, Int32 speed, String unitMessage, String unitsMessage, String unitsIds, String imeiList,String emailAddress, String emailSubject, String emailBody, Boolean callout, int callout_severity, Int32 userIdx) { /* SELECT Z.name, Z.idx, Z.color, Z.useridx, Z.alarmtype, " + " Z.sentmsg, Z.msgbody, Z.unitids, Z.sentemail, Z.email, Z.subj, Z.body, Z.imeilist, Z.sentmsg2, " + " Z.msgbody2, Z.speed, Z.fill_color, Z.fill_opacity, Z.border_color, Z.border_width, Z.border_opacity, " + " ZP.points */ Int32 idx = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { // get the hex colors for the desired color String hexFillColor = "#" + fillColor.R.ToString("X2") + fillColor.G.ToString("X2") + fillColor.B.ToString("X2"); String hexBorderColor = "#" + borderColor.R.ToString("X2") + borderColor.G.ToString("X2") + borderColor.B.ToString("X2"); conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO zonename (name,color,useridx,alarmtype,sentmsg,msgbody,unitids,sentemail,email,subj,body,imeilist,sentmsg2,msgbody2," + " speed, fill_color, fill_opacity, border_color, border_width, border_opacity, callout, callout_severity) " + " VALUES('{0}',{1},{2},{3},{4},'{5}','{6}',{7},'{8}','{9}','{10}','{11}',{12},'{13}',{14}, " + "'{15}', {16}, '{17}', {18}, {19}, {20}, {21})", name, 0, userIdx, (int)alertType, unitsMessage.Length > 0 ? true : false, unitsMessage, unitsIds, emailAddress.Length > 0 ? true : false, emailAddress, emailSubject, emailBody, imeiList, unitMessage.Length > 0 ? true : false, unitMessage, speed, hexFillColor, fillOpacity.ToString().Replace(',', '.'), hexBorderColor, borderWidth, borderOpacity.ToString().Replace(',', '.'), callout, callout_severity); cmd.ExecuteNonQuery(); Thread.Sleep(200); cmd = new NpgsqlCommand("SELECT max(idx) from zonename", conn); idx = (Int32)cmd.ExecuteScalar(); foreach (PointonZone obj in points) { cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = string.Format("INSERT INTO zonepoints (lat,lng,zone_id) VALUES(@lat1,@lng1,{0})", idx); cmd.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = obj.lat; cmd.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = obj.lng; cmd.Prepare(); cmd.ExecuteNonQuery(); } conn.Close(); } return idx; } public Boolean Insert_Define_SMS(String p_SMS) { Boolean ret = false; Char c = (char)39; String name = p_SMS; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); object temp = null; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT count(sms) FROM definesms where sms='{0}'", name), conn)) temp = cmd.ExecuteScalar(); if (temp.ToString() == "0") { using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("INSERT INTO defineSMS (sms) VALUES('{0}')", name), conn)) cmd.ExecuteNonQuery(); ret = true; } else { ret = false; } conn.Close(); } return ret; } public void Modify_Define_SMS(String p_SMS, String p_idx) { Char c = (char)39; String name = p_SMS; if (name != null) name = name.Replace(c, '`'); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE defineSMS SET sms ='{0}' where idx={1}", name, p_idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public ArrayList get_all_places(String glwhere) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT p.name, p.note, p.lat, p.lng, p.address, t.type_name, p.useridx, p.callout, p.callout_severity from place p, placetype t where p.type_id=t.type_id {0}", glwhere), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { var tmp = new Place { name = dr.GetString(0), desc = dr.GetString(1), lat = dr.GetDouble(2), lng = dr.GetDouble(3), address = dr.GetString(4), type = dr.GetString(5), useridx = dr.GetInt32(6), callout = dr.GetBoolean(7), callout_severity = dr.GetInt16(8) }; ret.Add(tmp); } dr.Close(); } conn.Close(); } return ret; } public ArrayList get_all_places_GIS(String glwhere) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT p.name, p.note, p.lat, p.lng, p.address, t.type_name, p.useridx, p.icon_size, color from place p, placetype t where p.type_id=t.type_id {0}", glwhere), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { var tmp = new Place { name = dr.GetString(0), desc = dr.GetString(1), lat = dr.GetDouble(2), lng = dr.GetDouble(3), address = dr.GetString(4), type = dr.GetString(5), useridx = dr.GetInt32(6), iconSize = dr.GetValue(7).ToString(), color = dr.GetValue(8).ToString() }; ret.Add(tmp); } dr.Close(); } conn.Close(); } return ret; } public Hashtable get_all_place_type_picture() { Hashtable ret = new Hashtable(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT type_name, type_id from placetype ORDER by type_name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Place obj = new Place(); obj.type = dr.GetString(0); obj.idx = dr.GetInt32(1); obj.pic = ""; try { ret.Add(obj.type, obj); } catch (Exception ex) { SM.Debug("Error add place type"+ex.ToString()); } } dr.Close(); } conn.Close(); } // check if resource directory exists if (!Directory.Exists("resource")) { Directory.CreateDirectory("resource"); } // check if places directory exists if (!Directory.Exists("resource/places")) { Directory.CreateDirectory("resource/places"); } foreach (Place obj in ret.Values) { String placeFileNamePattern = obj.type; // check if the image exists on the local hard disk if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + @"\resource\places\" + obj.type + ".png")) { obj.pic = System.Windows.Forms.Application.StartupPath + @"\resource\places\" + obj.type + ".png"; } else { // the car icon doesn't exists Utils.WriteLine("Fetching icon for place " + obj.Type); obj.pic = System.Windows.Forms.Application.StartupPath + @"\resource\places\" + obj.type + ".png"; DBiconsManager DBIcons = new DBiconsManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB); byte[] iconBytes = null; // get the icon from the database if exists or replace it with a default one if ((iconBytes = DBIcons.Get_Place_Image(obj.idx)) == null) { // get unknown image from the resources System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); using (Stream resFilestream = a.GetManifestResourceStream("Dispatcher.Resources.default.png")) { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { while (MainForm2.isRunning) { int read = resFilestream.Read(buffer, 0, buffer.Length); if (read <= 0) { // reached the end of the resource file iconBytes = ms.ToArray(); break; } // add read buffer into the memory stream ms.Write(buffer, 0, read); } } } } try { // save the image received from the database to a png file Bitmap bmp = new Bitmap(new MemoryStream(iconBytes)); bmp.Save(System.Windows.Forms.Application.StartupPath + @"\resource\places\" + placeFileNamePattern + ".png", ImageFormat.Png); Utils.WriteLine("Done Writing place file to folder -> " + placeFileNamePattern, ConsoleColor.DarkGray); } catch (Exception ex) { SM.Debug("Error write car icon to folder: " + ex.ToString() + "\n" + placeFileNamePattern); } } } return ret; } public Hashtable get_all_place_type_picture_GIS() { Hashtable ret = new Hashtable(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT type_name, p.type_id, p.icon_size, color, icon_name from placetype pt "+ " JOIN place p on p.type_id = pt.type_id "+ " ORDER by type_name ", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Place obj = new Place(); obj.type = dr.GetString(0); obj.idx = dr.GetInt32(1); obj.pic = ""; obj.iconSize = dr.GetValue(2).ToString(); obj.color = dr.GetValue(3).ToString(); obj.iconName = dr.GetValue(4).ToString(); try { if (!ret.Contains(obj.type + obj.color + obj.iconSize)) ret.Add(obj.type + obj.color + obj.iconSize, obj); } catch (Exception ex) { SM.Debug("Error add place type" + ex.ToString()); } } dr.Close(); } conn.Close(); } // check if resource directory exists if (!Directory.Exists("resource")) { Directory.CreateDirectory("resource"); } // check if resource directory exists if (!Directory.Exists("resource/landmarks")) { Directory.CreateDirectory("resource/landmarks"); } #region new arcgis foreach (Place obj in ret.Values) { //foreach place from db look up in landmarks directory in order to pass to arcgis control Color color = Color.Black; color = System.Drawing.ColorTranslator.FromHtml(obj.color); String hexColor = color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); int width = 36; int heigth = 48; int size = 48; if (obj.iconSize == "") obj.iconSize = "medium"; if (obj.iconSize.Substring(0,1) == LandmarkUI.IconSize.MEDIUM.ToString()) { width = 27; heigth = 36; size = 32; } else if (obj.iconSize.Substring(0,1) == LandmarkUI.IconSize.SMALL.ToString()) { width = 20; heigth = 26; size = 24; } // generate the name and the path of the desired icon string iconNameAndPath = System.Windows.Forms.Application.StartupPath + @"\resource\landmarks\" + obj.iconName.Replace(".png", "") + "_" + hexColor + "_" + obj.iconSize.Substring(0, 1) + ".png"; obj.pic = iconNameAndPath.Replace(".png", ".bmp"); // check if the icon exists on the hdd if (System.IO.File.Exists(iconNameAndPath)) { // we are ok, and the icon doesn't need to be recreated } else { float r = (float)((1.0 / 256) * color.R);// / 256; float g = (float)((1.0 / 256) * color.G);// / 256; float b = (float)((1.0 / 256) * color.B);// / 256; // create the landmark icon using (Bitmap landmarkPin = new Bitmap(System.Windows.Forms.Application.StartupPath + @"\resource\landmarks\_pin_02.png")) { Bitmap bitmap = new Bitmap(landmarkPin.Width, landmarkPin.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); ImageAttributes imageAttributes = new ImageAttributes(); // create a color matrix in order to change the color float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // Red scaling [multiply] new float[] {0, 1, 0, 0, 0}, // Green scaling [multiply] new float[] {0, 0, 1, 0, 0}, // Blue scaling [multiply] new float[] {r, g, b, 1, 0}, // this will add values to R,G,B,A new float[] {0, 0, 0, 0, 1}}; // three translations of 0.2 ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // Create a Graphics object using (Graphics gr = Graphics.FromImage(bitmap)) { // Draw image with no affects gr.DrawImage(landmarkPin, 0, 0, landmarkPin.Width, landmarkPin.Height); // Draw image with ImageAttributes gr.DrawImage(landmarkPin, new Rectangle(0, 0, landmarkPin.Width, landmarkPin.Height), 0, 0, landmarkPin.Width, landmarkPin.Height, GraphicsUnit.Pixel, imageAttributes); // add landmark type icon String safemobileDirPath = System.Windows.Forms.Application.StartupPath; string iconPath = safemobileDirPath + @"\resource\landmarks\" + obj.iconName; using (Image img = Utils.ScaleImage(Bitmap.FromFile(iconPath), 44, 44)) { gr.DrawImage(img, 19, 18); } Image resizedImage = Utils.ScaleImage(bitmap, width, heigth); resizedImage.Save(iconNameAndPath); //bitmap.Save(iconNameAndPath); // Dispose bitmap.Dispose(); resizedImage.Dispose(); } } } try { ESRI.ArcGIS.Display.IPictureMarkerSymbol bitmapPictureMarkerSymbolCls = new ESRI.ArcGIS.Display.PictureMarkerSymbolClass(); Image ArcgisImage = Image.FromFile(iconNameAndPath); ArcgisImage.Save(iconNameAndPath.Replace(".png", ".bmp"), ImageFormat.Bmp); //var ArcgisImage = new Bitmap(iconNameAndPath); //ArcgisImage.MakeTransparent(Color.Black); //ArcgisImage.Save(iconNameAndPath.Replace(".png", ".bmp")); ArcgisImage.Dispose(); bitmapPictureMarkerSymbolCls.CreateMarkerSymbolFromFile (ESRI.ArcGIS.Display.esriIPictureType.esriIPictureBitmap, iconNameAndPath.Replace(".png", ".bmp")); bitmapPictureMarkerSymbolCls.Angle = 0;//Minicar RgbColor rgbColor = new ESRI.ArcGIS.Display.RgbColor(); rgbColor.Red = 255; rgbColor.Green = 255; rgbColor.Blue = 255; bitmapPictureMarkerSymbolCls.BitmapTransparencyColor = rgbColor; bitmapPictureMarkerSymbolCls.Size = size; bitmapPictureMarkerSymbolCls.XOffset = -12; bitmapPictureMarkerSymbolCls.YOffset = -12; obj.GISsymb = bitmapPictureMarkerSymbolCls; } catch (Exception ex) { SM.Debug("Error load cars for ARCGIS" + ex.ToString() + "\n" + obj.name); obj.GISsymb = null; } } #endregion return ret; } public ArrayList get_position_for_report(Int32 timeMIN, Int32 timeMAX, Int32 sc_id) { ArrayList ret = new ArrayList(); Double scevtimemin = 0, scevtimemax = 0; scevtimemin = sc_id * 10000000000 + timeMIN; scevtimemax = sc_id * 10000000000 + timeMAX; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("SELECT timeGMT , address , lat , lng , di , speed FROM messages WHERE scevtime >{0} and scevtime <{1} ORDER by scevtime", scevtimemin, scevtimemax), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if ((dr.GetDouble(2)!=0)&&(dr.GetDouble(3)!=0)) ret.Add(new PositionData(dr.GetDouble(2), dr.GetDouble(3), "", dr.GetInt32(0), car_state_e.CAR_RUNNING, dr.GetInt32(5))); } dr.Close(); } conn.Close(); } return ret; } public Hashtable get_all_zone() { Hashtable GroupList = new Hashtable(); ArrayList arr = new ArrayList(); int OldGrpId = 0; Int32 SpeedValue = 0; ZoneClass oldZone = null; Boolean first = true; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT zn.idx,zn.name,znpnt.lat,znpnt.lng,znpnt.idx,zn.color,zn.useridx,zn.alarmtype,zn.sentmsg,zn.msgbody,zn.unitids,zn.sentemail,zn.email,zn.subj,zn.body,zn.sentmsg2,zn.msgbody2,zn.speed, zn.callout, zn.callout_severity" + " FROM zonename as zn" + " LEFT JOIN zonepoints as znpnt ON (zn.idx = znpnt.zone_id) " + " ORDER by zn.name,znpnt.idx", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if (OldGrpId != dr.GetInt32(0)) { if (first) first = false; else { ZoneClass g = new ZoneClass(oldZone, OldGrpId,arr); try { GroupList.Add(OldGrpId, g); } catch (Exception ex) { SM.Debug("Unable to add Group" + ex.ToString()); } } OldGrpId = dr.GetInt32(0); SpeedValue = dr.GetInt32(17); if (MainForm2.isInMile) SpeedValue = (Int32)Math.Round(SpeedValue * 0.621371); oldZone = new ZoneClass(dr.GetString(1), dr.GetInt32(5), dr.GetInt32(6), dr.GetInt32(7), dr.GetBoolean(8), dr.GetString(9), dr.GetString(10), dr.GetBoolean(11), dr.GetString(12), dr.GetString(13), dr.GetString(14), dr.GetBoolean(15), dr.GetString(16),SpeedValue,dr.GetBoolean(18), dr.GetInt16(19)); arr = new ArrayList(); } if (!dr.IsDBNull(2)) arr.Add(new PointonZone(dr.GetDouble(2),dr.GetDouble(3),dr.GetInt32(4))); } dr.Close(); if (OldGrpId != 0) { ZoneClass g1 = new ZoneClass(oldZone, OldGrpId, arr); GroupList.Add(OldGrpId, g1); } } conn.Close(); } return GroupList; } //public DataTable get_place_table(string command) //{ // DataTable table = new DataTable(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(command, conn); // table.Locale = System.Globalization.CultureInfo.InvariantCulture; // dataAdapter.Fill(table); // } // return table; //} //public void get_log_view_all(String glwhere) //{ // String tmpname=""; // String TimeVal = ""; // string Stat = ""; // MainForm2.ONOFFList = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select imei,timeGMT,status FROM logmototurbo {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(); // while (dr.Read()) // { // if (MainForm2.VehIMEIHash[dr.GetString(0)] != null) tmpname = (MainForm2.VehIMEIHash[dr.GetString(0)] as String); // else tmpname = ""; // if (tmpname != "") // { // TimeVal = convDT.GetRegionalFormat(dr.GetInt32(1), MainForm2.is24hours, MainForm2.DayFirst); // switch (dr.GetInt32(2)) // { // case 0: Stat = "OFF"; // break; // case 1: Stat = "ON"; // break; // case 9: Stat = "MADE OFF"; // break; // case 10: Stat = "MADE ON"; // break; // } // var tmp = new ONOFFData // { // Name = tmpname, // Time = TimeVal, // Status = Stat // }; // MainForm2.ONOFFList.Add(tmp); // } // } // dr.Close(); // } // } //} //public void get_EMERG(String glwhere) //{ // MainForm2.ONOFFList = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select timeGMT,sc_id,address,lat,lng FROM emergalarm {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(); // while (dr.Read()) // { // var tmp = new ONOFFData // { // Name = (MainForm2.VehIDHash[dr.GetInt32(1)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(1)] : "", // // Time = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0), !MainForm2.is24hours), // // Status = convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).Date.ToShortDateString(), // Time = (MainForm2.is24hours) ? convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).ToString("MM/dd/yyyy HH:mm:ss") : convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).ToString("MM/dd/yyyy hh:mm:ss tt"), // Status = dr.GetString(2), // sc_id = dr.GetInt32(1), // lat = dr.GetDouble(3), // lng = dr.GetDouble(4), // timeGMT = dr.GetInt32(0) // }; // if (tmp.Name!="") // MainForm2.ONOFFList.Add(tmp); // } // dr.Close(); // } // } //} //public void get_Speeding(String glwhere) //{ // MainForm2.SpeedingList = new List(); // Int32 count50000 = 0; // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select timeGMT,sc_id,speed,address,lat,lng FROM speedalarm {0} ORDER BY timeGMT desc", glwhere), conn)) // { // int count = 0; // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // count50000++; // var tmp = new SpeedData // { // Name = (MainForm2.VehIDHash[dr.GetInt32(1)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(1)] : "", // Speed = (MainForm2.isInMile) ? ((int)(dr.GetInt32(2) * 0.621371192)).ToString() : dr.GetInt32(2).ToString(), // Time = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0), !MainForm2.is24hours), // Data = convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).Date.ToShortDateString(), // Address = dr.GetString(3), // sc_id = dr.GetInt32(1), // timeGMT = dr.GetInt32(0), // lat = (dr.IsDBNull(4) ? 0 : dr.GetDouble(4)), // lng = (dr.IsDBNull(5) ? 0 : dr.GetDouble(5)) // }; // if (tmp.Name != "") // MainForm2.SpeedingList.Add(tmp); // if (count50000 > 50000) break; // } // } // } //} //public void get_SMS_Location(String glwhere) //{ // MainForm2.SMSLocList = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select timeGMT,sc_id_sour,mess,address,lat,lng FROM sms {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // var tmp = new SMS_Location // { // Name = (MainForm2.VehIDHash[dr.GetInt32(1)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(1)] : "", // Text_mess = dr.GetString(2), // Time = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0), !MainForm2.is24hours), // Data = convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).Date.ToShortDateString(), // Address = dr.GetString(3), // sc_id = dr.GetInt32(1), // timeGMT = dr.GetInt32(0), // lat = dr.GetDouble(4), // lng = dr.GetDouble(5) // }; // if (tmp.Name != "") // MainForm2.SMSLocList.Add(tmp); // } // } // } //} //public void get_History(String glwhere,Boolean compAddress,Boolean forceLATLNG) //{ // MainForm2.HistDataReport = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT timeGMT,address,speed,lat,lng,scevtime, sc_id, W.name, W.driver_id FROM messages " + // " INNER JOIN vehicle W on sc_id = W.id {0} ORDER BY timeGMT DESC", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // String Address = ""; // if (!forceLATLNG) // { // if (!dr.IsDBNull(1)) Address = dr.GetString(1); // if ((dr.GetDouble(3) == 0) || (dr.GetDouble(4) == 0)) Address = "NO GPS FIX"; // else if ((Address == "") || (Address == " ")) // { // if (compAddress) // { // MainForm2.cntaddr++; // ReportsControl.IdReportHS[MainForm2.cntaddr.ToString()] = "no address"; // ReportsControl.AddrGISQueue.Enqueue(new AddrAndID(MainForm2.cntaddr, dr.GetDouble(3), dr.GetDouble(4))); // Address = MainForm2.cntaddr.ToString(); // } // else Address = "LAT:" + Math.Round(dr.GetDouble(3), 5).ToString() + " , LNG:" + Math.Round(dr.GetDouble(4), 5).ToString(); // } // } // else Address = "LAT:" + Math.Round(dr.GetDouble(3), 5).ToString() + " , LNG:" + Math.Round(dr.GetDouble(4), 5).ToString(); // //Address = dr.GetInt32(0).ToString() + " " + "LAT:" + Math.Round(dr.GetDouble(3), 5).ToString() + " , LNG:" + Math.Round(dr.GetDouble(4), 5).ToString(); ; // var tmp = new StopData // { // Location = Address, // Duration = (MainForm2.isInMile) ? ((int)(dr.GetInt32(2) * 0.621371192)).ToString() : dr.GetInt32(2).ToString(), // //Time = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0),!MainForm2.is24hours), // Time = convDT.TimeOfDayHHMMSSLocal(dr.GetInt32(0), !MainForm2.is24hours), // Data = convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).Date.ToShortDateString(), // unit_sc_id = dr.GetInt32(6), // unit_name = dr.GetString(7), // unique_id = dr.GetDouble(5) // }; // MainForm2.HistDataReport.Add(tmp); // } // } // } //} //public void get_ALLAlarm(String glwhere) //{ // String tmpglwhere = glwhere; // String TimeVal = ""; // MainForm2.HistDataReport = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // //get all energ alarm // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT sc_id, timeGMT FROM emergalarm {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // TimeVal = convDT.GetRegionalFormat(dr.GetInt32(1), MainForm2.is24hours, MainForm2.DayFirst); // var tmp = new StopData // { // Location = TimeVal, // Duration = "", // Time = "Emergency", // Data = (MainForm2.VehIDHash[dr.GetInt32(0)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(0)] : "", // timeGMT = dr.GetInt32(1) // }; // if (tmp.Data!="") // MainForm2.HistDataReport.Add(tmp); // } // } // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select sc_id,zone_id,action,timeGMT,type FROM geozoneinout {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // String descStr = ""; // if ((uint)dr.GetInt32(2) == 1) descStr = "OUT "; // else descStr = "IN "; // if (dr.GetInt32(4) == 1) // { // if (MainForm2.ZoneIDHash[dr.GetInt32(1)] != null) // descStr = descStr + ((ZoneClass)MainForm2.ZoneIDHash[dr.GetInt32(1)]).Name; // } // else // { // if (MainForm2.LandIDHash[dr.GetInt32(1)] != null) // descStr = descStr + ((String)MainForm2.LandIDHash[dr.GetInt32(1)]); // } // TimeVal = convDT.GetRegionalFormat(dr.GetInt32(3), MainForm2.is24hours, MainForm2.DayFirst); // var tmp = new StopData // { // Location = TimeVal, // Duration = descStr, // Time = "Geo-Fence", // Data = (MainForm2.VehIDHash[dr.GetInt32(0)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(0)] : "", // timeGMT = dr.GetInt32(3) // }; // if (tmp.Data != "") // MainForm2.HistDataReport.Add(tmp); // } // } // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select timeGMT,sc_id,speed FROM speedalarm {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // TimeVal = convDT.GetRegionalFormat(dr.GetInt32(0), MainForm2.is24hours, MainForm2.DayFirst); // var tmp = new StopData // { // Location = TimeVal, // Duration = (MainForm2.isInMile) ? ((int)(dr.GetInt32(2) * 0.621371192)).ToString() + " " + MainForm2.milesh : dr.GetInt32(2).ToString() + " " + MainForm2.kmh, // Time = "Speeding", // Data = (MainForm2.VehIDHash[dr.GetInt32(1)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(1)] : "", // timeGMT = dr.GetInt32(0) // }; // if (tmp.Data != "") // MainForm2.HistDataReport.Add(tmp); // } // } // if (tmpglwhere != "") tmpglwhere = tmpglwhere + " and alarm =1"; // else tmpglwhere = " where alarm = 1"; // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select sc_id,timeGMT,telemetry_id FROM telemetry_history {0} ORDER BY timeGMT desc", tmpglwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // String actionName = ""; // if (MainForm2.VehIDHash[dr.GetInt32(0)] != null) // { // foreach (TelemetryObj obj in ((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIDHash[dr.GetInt32(0)]]).telemList) // if (obj.Id == dr.GetInt32(2)) { actionName = obj.Name; break; } // } // TimeVal = convDT.GetRegionalFormat(dr.GetInt32(1), MainForm2.is24hours, MainForm2.DayFirst); // var tmp = new StopData // { // Location = TimeVal, // Duration = actionName, // Time = "Telemetry", // Data = (MainForm2.VehIDHash[dr.GetInt32(0)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(0)] : "", // timeGMT = dr.GetInt32(1) // }; // if (tmp.Data != "") // MainForm2.HistDataReport.Add(tmp); // } // } // } // MainForm2.HistDataReport.Sort(delegate(StopData li1, StopData li2) // { // -1 is for descending order // return (-1) * (li1.timeGMT.CompareTo(li2.timeGMT)); // }); //} //public void get_TelemHist_alarm_event(String glwhere) //{ // MainForm2.SpeedingList = new List(); // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select timegmt,sc_id,telemetry_id,address,lat,lng FROM telemetry_history {0} ORDER BY timeGMT desc", glwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // String actionName = ""; // if (MainForm2.VehIDHash[dr.GetInt32(1)] != null) // { // foreach (TelemetryObj obj in ((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIDHash[dr.GetInt32(1)]]).telemList) // if (obj.Id == dr.GetInt32(2)) // { // actionName = obj.Name; // break; // } // } // var tmp = new SpeedData // { // Name = (MainForm2.VehIDHash[dr.GetInt32(1)] != null) ? (String)MainForm2.VehIDHash[dr.GetInt32(1)] : "", // Speed = actionName, // //Time = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0),!MainForm2.is24hours), // Time = convDT.TimeOfDayHHMMSSLocal(dr.GetInt32(0),false), // Data = convDT.GetDTLocalFromSeconds(dr.GetInt32(0)).Date.ToShortDateString(), // Address = dr.GetString(3), // sc_id = dr.GetInt32(1), // timeGMT = dr.GetInt32(0), // lat = dr.GetDouble(4), // lng = dr.GetDouble(5) // }; // if (tmp.Name != "") // MainForm2.SpeedingList.Add(tmp); // } // } // } //} //public void get_LANDANDZONE(String glwhere, rep_type typ) //{ // MainForm2.LandList = new List(); // String newglwhere = glwhere; // String ToAdd = " type=2 "; // if (typ == rep_type.GEOFENC) ToAdd = " type=1 "; // if (newglwhere.Length > 1) // newglwhere = newglwhere + " and " + ToAdd; // else newglwhere = " where " + ToAdd; // using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) // { // conn.Open(); // using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("select sc_id,zone_id,action,timeGMT FROM geozoneinout {0} ORDER BY timeGMT desc", newglwhere), conn)) // { // NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // while (dr.Read()) // { // LandData tmp = new LandData(); // if (MainForm2.VehIDHash[dr.GetInt32(0)] != null) // tmp.Name = (String)MainForm2.VehIDHash[dr.GetInt32(0)]; // else tmp.Name = ""; // if ((uint)dr.GetInt32(2) == 1) tmp.LandType = "OUT"; // else tmp.LandType = "IN"; // //tmp.Time = convDT.GetDTLocalFromSeconds(dr.GetInt32(3)).ToString(); // tmp.Time = convDT.GetRegionalFormat(dr.GetInt32(3), MainForm2.is24hours, MainForm2.DayFirst); // tmp.LandName = convDT.TimeOfDayHHMMLocal(dr.GetInt32(0)); // if (typ == rep_type.GEOFENC) // { // if (MainForm2.ZoneIDHash[dr.GetInt32(1)] != null) // tmp.LandName = ((ZoneClass)MainForm2.ZoneIDHash[dr.GetInt32(1)]).Name; // } // else // { // SM.Debug("LandID"+dr.GetInt32(1)); // if (MainForm2.LandIDHash[dr.GetInt32(1)] != null) // tmp.LandName = (String)MainForm2.LandIDHash[dr.GetInt32(1)]; // } // if (tmp.Name!="") // MainForm2.LandList.Add(tmp); // } // } // } //} public ArrayList get_SMS(String glwhere, Boolean inbox) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = string.Format("select mess,timeGMT,sc_id_dest,status,email,idx, color, sched_timegmt FROM sms {0} ORDER BY timeGMT desc", glwhere); if (inbox) query = string.Format("select mess,timeGMT,sc_id_sour,status,email,idx, color FROM sms {0} ORDER BY timeGMT desc", glwhere); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { SMSfromDB sms = new SMSfromDB(dr.GetInt32(2), dr.GetInt32(1), dr.GetString(0), dr.GetInt32(3), dr.GetInt32(5), dr.GetString(4)); sms.color = (dr.IsDBNull(6) ? System.Drawing.ColorTranslator.FromHtml("#FFFFFF") : System.Drawing.ColorTranslator.FromHtml(dr.GetString(6))); // set scheduled time for those who are scheduled if (!inbox && !dr.IsDBNull(7) && dr.GetInt32(7) > 0) sms.date = dr.GetInt32(7); ret.Add(sms); } dr.Close(); } conn.Close(); } return ret; } public ArrayList get_SMS_with_limit(String glwhere, Boolean inbox, Int32 page_number) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); String query = string.Format("select mess,timeGMT,sc_id_dest,status,email,idx FROM sms {0} ORDER BY timeGMT desc LIMIT 2000 OFFSET {1}", glwhere, page_number * 2000); if (inbox) query = string.Format("select mess,timeGMT,sc_id_sour,status,email,idx FROM sms {0} ORDER BY timeGMT desc LIMIT 2000 OFFSET {1}", glwhere,page_number*2000); using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { SMSfromDB sms = new SMSfromDB(dr.GetInt32(2), dr.GetInt32(1), dr.GetString(0), dr.GetInt32(3), dr.GetInt32(5), dr.GetString(4)); ret.Add(sms); } dr.Close(); } conn.Close(); } return ret; } public ArrayList get_Deleted_SMS() { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("select mess,timeGMT,sc_id_sour,sc_id_dest, status,email,idx FROM sms Where deleted=1 ORDER BY timeGMT desc", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { SMSfromDB sms = new SMSfromDB(dr.GetInt32(2),dr.GetInt32(3), dr.GetInt32(1), dr.GetString(0), dr.GetInt32(4), dr.GetInt32(6), dr.GetString(5)); ret.Add(sms); } dr.Close(); } conn.Close(); } return ret; } public void Delete_Place(String p_idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM place where idx={0}", p_idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_Zone(String p_idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM zonename where idx={0}", p_idx), conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM zonepoints where zone_id={0}", p_idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_Zone_Alarm(String p_idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM geozoneinout where idx={0} and type=1", p_idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_Zone_Reports(String p_idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM reports where geofence_id={0} and type_stat=1", p_idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_Define_SMS(String sms) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE FROM defineSMS where sms='{0}'",sms), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_new_RFID() { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=6", conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_GEOVIEW(Boolean isZone) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); if (isZone) { using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE geozoneinout SET preview=1 where type=1", conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=2", conn)) cmd.ExecuteNonQuery(); } else { using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE geozoneinout SET preview=1 where type=2", conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=3", conn)) cmd.ExecuteNonQuery(); } conn.Close(); } } public void Update_SPEED() { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE speedalarm SET preview=1", conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=4", conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_EMERG() { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd =new NpgsqlCommand("UPDATE emergalarm SET preview=1", conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=5", conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_SMS_Alarm() { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE emergalarm SET preview=1", conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand("UPDATE alarm SET sc_id=0 where type=1", conn)) cmd.ExecuteNonQuery(); conn.Close(); } } private NpgsqlConnection connAddress = null; public void InitConnectionForAddress() { try { connAddress = new NpgsqlConnection(MainForm2.MyConString); connAddress.Open(); } catch (Exception ex) { SM.Debug("Error on Init Address connection"+ex.ToString()); } } public void CloseConnectionForAddress() { try { connAddress.Close(); } catch (Exception ex) { SM.Debug("Error on close Address connection"+ex.ToString()); } } public String get_address_one_connection(Double LAT,Double LNG) { String ret = ""; Int32 nrofErrors =0; while (nrofErrors<2) { try { NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = connAddress; cmd.CommandText = "SELECT address from address where LAT=@lat1 and LNG=@lng1"; cmd.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = LAT; cmd.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = LNG; cmd.Prepare(); NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { ret = dr.GetString(0); } try { dr.Close(); } catch (Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); } nrofErrors=3; } catch (Exception ex) { SM.Debug("Error on get address ok: "+ex.ToString()); nrofErrors++; CloseConnectionForAddress(); Thread.Sleep(100); InitConnectionForAddress(); } } return ret; } public String get_address(Double LAT,Double LNG) { String ret = ""; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = conn; cmd.CommandText = "SELECT address from address where LAT=@lat1 and LNG=@lng1"; cmd.Parameters.Add("@lat1", NpgsqlTypes.NpgsqlDbType.Double).Value = LAT; cmd.Parameters.Add("@lng1", NpgsqlTypes.NpgsqlDbType.Double).Value = LNG; cmd.Prepare(); NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { ret = dr.GetString(0); } dr.Close(); conn.Close(); } return ret; } public ArrayList get_place(Int32 id) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT name, note, lat, lng, address, type_id,useridx from place where idx={0} order by name", id.ToString()), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { ret.Add(dr.GetString(0)); ret.Add(dr.GetString(1)); ret.Add(dr.GetDouble(2)); ret.Add(dr.GetDouble(3)); ret.Add(dr.GetString(4)); ret.Add(dr.GetInt32(5)); ret.Add(dr.GetInt32(6)); } dr.Close(); } conn.Close(); } return ret; } public void UPDATE_TIME(String timeGMT, String timeGMT2) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE messages SET di=128 where timeGMT>{0} and timeGMT<{1}", timeGMT, timeGMT2), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public String GetAddress(Double lat, Double lng) { Retur = ""; mindistSafe = 180 + 90; //max lat+lng addrTmpSafe = ""; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT address,lat,lng from address where lat>{0} and lat<{1} and lng>{2} and lng<{3} and type=2", (double)(lat - 0.5), (double)(lat + 0.5), (double)(lng - 0.5), (double)(lng + 0.5)), conn)) { drSafe = cmd.ExecuteReader(); while (drSafe.Read()) { addrTmpSafe = drSafe.GetString(0); latTmpSafe = drSafe.GetDouble(1); lngTmpSafe = drSafe.GetDouble(2); newMinSafe = System.Math.Abs(latTmpSafe - lat) + System.Math.Abs(lngTmpSafe - lng); if (newMinSafe < mindistSafe) { Retur = addrTmpSafe; mindistSafe = newMinSafe; } } drSafe.Close(); } conn.Close(); } if (Retur.CompareTo("") == 0) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT address,lat,lng from address where lat>{0} and lat<{1} and lng>{2} and lng<{3} and (type=1 or type=3)", (double)(lat - 0.0007), (double)(lat + 0.0007), (double)(lng - 0.0007), (double)(lng + 0.0007)), conn)) { drSafe = cmd.ExecuteReader(); while (drSafe.Read()) { addrTmpSafe = drSafe.GetString(0); latTmpSafe = drSafe.GetDouble(1); lngTmpSafe = drSafe.GetDouble(2); newMinSafe = System.Math.Abs(latTmpSafe - lat) + System.Math.Abs(lngTmpSafe - lng); if (newMinSafe < mindistSafe) { Retur = addrTmpSafe; mindistSafe = newMinSafe; } } drSafe.Close(); } conn.Close(); } } if (Retur.CompareTo("") == 0) Retur = "no address"; return Retur; } /* public void GetAddressList(Double minlat, Double minlng, Double maxlat, Double maxlng, out ArrayList Street, out ArrayList Place, AxMappointControlx mapControl, Telerik.WinControls.UI.RadProgressBar ProgBar, HistoryTab parent, HistoryTabMap parentMap, HistoryTabInfo parentInfo) { ArrayList ret = new ArrayList(); ArrayList ret2 = new ArrayList(); int cont = -1; Locationx LocTmp; Street = null; Place = null; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT address,lat,lng from address where lat>{0} and lat<{1} and lng>{2} and lng<{3} and type=2", (double)(minlat - 0.0005), (double)(maxlat + 0.0005), (double)(minlng - 0.0005), (double)(maxlng + 0.0005)), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { if (((parent != null) && (parent.closeTabThread)) || ((parentMap != null) && (parentMap.closeTabThread)) || ((parentInfo != null) && (parentInfo.closeTabThread))) break; cont++; var obj = new PositionData { address = dr.GetString(0), lat = dr.GetDouble(1), lng = dr.GetDouble(2) }; ret.Add(obj); if ((cont % 1000) == 0) System.Threading.Thread.Sleep(10); if (mapControl != null) { if ((cont % 30000) == 0) ProgBar.ProgressBarElement.PerformStepValue1(); if (cont == 5000) LocTmp = mapControl.ActiveMap.GetLocation(0, 0, 10); if ((cont % 70000) == 0) LocTmp = mapControl.ActiveMap.GetLocation(0, 0, 10); } } } } using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT address,lat,lng from address where lat>{0} and lat<{1} and lng>{2} and lng<{3} and (type=1 or type=3)", (double)(minlat - 0.5), (double)(maxlat + 0.5), (double)(minlng - 0.5), (double)(maxlng + 0.5)), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { if (((parent != null) && (parent.closeTabThread)) || ((parentMap != null) && (parentMap.closeTabThread)) || ((parentInfo != null) && (parentInfo.closeTabThread))) break; PositionData obj = new PositionData(); obj.address = dr.GetString(0); obj.lat = dr.GetDouble(1); obj.lng = dr.GetDouble(2); ret2.Add(obj); } } } Street = ret; Place = ret2; }*/ public void get_Alarms() { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT type,sc_id,timeGMT,mess from alarm where sc_id!=0 ORDER BY type", conn)) { drSafe = cmd.ExecuteReader(); while (drSafe.Read()) { switch (drSafe.GetInt32(0)) { /*SMS*/ case 1: if (!MainForm2.NewMess) { MainForm2.sc_id_Mess = drSafe.GetInt32(1); MainForm2.Mess_Alarm = drSafe.GetString(3) + " " + MainForm2.newSMSTime + drSafe.GetInt32(2).GetDTLocalFromSeconds().ToString(); MainForm2.NewMess = true; } break; /*ZONE*/ case 2: if (!MainForm2.NewZone) { MainForm2.sc_id_Geo = drSafe.GetInt32(1); MainForm2.Zone_Alarm = ((Convert.ToInt32(drSafe.GetString(3)) == 2) ? " IN " : " OUT ") + MainForm2.ZoneIDHash[drSafe.GetInt32(2)]; MainForm2.NewZone = true; } break; /*LAND*/ case 3: if (!MainForm2.NewLand) { MainForm2.sc_id_Geo = drSafe.GetInt32(1); MainForm2.Land_Alarm = ((Convert.ToInt32(drSafe.GetString(3)) == 2) ? " IN " : " OUT ") + MainForm2.LandIDHash[drSafe.GetInt32(2)]; MainForm2.NewLand = true; } break; /*SPEED*/ case 4: if (!MainForm2.NewSpeed) { MainForm2.sc_id_Speed = drSafe.GetInt32(1); if (MainForm2.isInMile) MainForm2.Speed_unit = (int)Math.Round(drSafe.GetInt32(2) * 0.621371192); else MainForm2.Speed_unit = drSafe.GetInt32(2); MainForm2.NewSpeed = true; } break; /*EMERG*/ case 5: if (!MainForm2.NewEMERG) MainForm2.sc_id_EMERG = drSafe.GetInt32(1); MainForm2.NewEMERG = true; break; /*RFID*/ case 6: if (MainForm2.PassAlarm == "") { sc_idSafe = drSafe.GetInt32(1); RFIDSafe = drSafe.GetString(3); PassNameSafe = RFIDSafe; if (MainForm2.VehIDHash[(int)sc_idSafe] != null) VehNameSafe = (String)MainForm2.VehIDHash[(int)sc_idSafe]; if (MainForm2.PassHash[RFIDSafe] != null) PassNameSafe = ((PassengerClass)MainForm2.PassHash[RFIDSafe]).Name; MainForm2.PassAlarm = PassNameSafe + " in " + VehNameSafe; } break; } } drSafe.Close(); } conn.Close(); } } public Int32 Get_user_ID(string userLog) { Int32 tmp = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT userID from users where login='{0}'",userLog), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) tmp = dr.GetInt32(0); dr.Close(); } conn.Close(); } return tmp; } /// /// Get all dispatchers names along with their ids and create a dictionary /// that will have the key based on the id and value the string /// /// Dictionary containing all dispatchers names public Dictionary GetDispatchersNames() { Dictionary dispatchers = new Dictionary(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("SELECT userID, login from users"), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { // add the dispatcher name into the hash dispatchers.Add(dr.GetInt32(0), dr.GetString(1)); } dr.Close(); } conn.Close(); } return dispatchers; } public Hashtable Select_groups() { Hashtable GroupList = new Hashtable(); MainForm2.htGroupsKeyNAmeValueID = new Hashtable(); ArrayList arr = new ArrayList(); ArrayList arrImei = new ArrayList(); int OldGrpId = 0; string OldGroupNAme = ""; Int32 OldGrpCpsId = 0; Boolean first = true; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); /* new NpgsqlCommand("SELECT grp.id,grp.name,v_grp.sc_id,grp.cps_id" + " FROM groups as grp" + " LEFT JOIN vehicle_group as v_grp ON (grp.id = v_grp.grp_ip) " + " Group by grp.id, grp.name, v_grp.sc_id,grp.cps_id ORDER by grp.name", conn))*/ using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT grp.id,grp.name,v_grp.sc_id,grp.cps_id,sbs.imei" + " FROM groups as grp" + " LEFT JOIN vehicle_group as v_grp ON (grp.id = v_grp.grp_ip) " + " INNER JOIN subscriber as sbs ON (sbs.sc_id = v_grp.sc_id) " + " INNER JOIN vehicle as v ON (v.id = v_grp.sc_id) " //+ " Group by grp.id, grp.name, v_grp.sc_id,grp.cps_id,sbs.imei " + " ORDER by grp.name, v.name", conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if (OldGrpId != dr.GetInt32(0)) { if (first) first = false; else { GroupClass g = new GroupClass(OldGroupNAme,OldGrpId,OldGrpCpsId,arr,arrImei); //GroupList.Add(OldGrpId, g); try { GroupList.Add(OldGrpId, g); } catch (Exception ex) { SM.Debug("Unable to add Group" + ex.ToString()); } MainForm2.htGroupsKeyNAmeValueID.Add(OldGroupNAme, OldGrpId); } OldGroupNAme = dr.GetString(1); OldGrpId = dr.GetInt32(0); OldGrpCpsId = dr.GetInt32(3); arr = new ArrayList(); arrImei = new ArrayList(); } try{ if (!dr.IsDBNull(2)) MainForm2.GrpIdforScId.Add(dr.GetInt32(2), new GroupClass(OldGroupNAme, OldGrpId,OldGrpCpsId)); }catch(Exception ex){ SM.Debug("Unable to put sc_id in a group"+ex.ToString());} if (!dr.IsDBNull(2)) { arr.Add(dr.GetInt32(2)); arrImei.Add(dr.GetString(4)); } } dr.Close(); if (OldGrpId != 0) { GroupClass g1 = new GroupClass(OldGroupNAme,OldGrpId,OldGrpCpsId,arr,arrImei); GroupList.Add(OldGrpId, g1); MainForm2.htGroupsKeyNAmeValueID.Add(OldGroupNAme, OldGrpId); } } conn.Close(); } return GroupList; } public Boolean CheckUserStatus(Int32 UserIdx, string MyConString) { Boolean ret = false; using (NpgsqlConnection conn = new NpgsqlConnection(MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT ison FROM users where userid="+UserIdx, conn)) { Int32 temp = Convert.ToInt32((object)cmd.ExecuteScalar()); if (temp == 1) ret = true; } conn.Close(); } return ret; } public ArrayList GetSoundCards(Int32 ID) { ArrayList ret = new ArrayList(); using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("SELECT dev_name FROM soundcards where user_id={0} and rad_disp_id={1} ORDER by type", MainForm2.userIDX, ID), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { ret.Add(dr.GetString(0)); } dr.Close(); } conn.Close(); } return ret; } public void SetUserState(Int32 UserIdx,Boolean state) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); Int32 Intstate = 0; if (state) Intstate = 1; using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("update users set ison={0} where userid={1}", Intstate,UserIdx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void SaveSoundCardinDB(Int32 ID, String OUTName, String INName,String KeyName) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("DELETE from soundcards where user_id='{0}' and rad_disp_id={1}", MainForm2.userIDX, ID), conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("INSERT INTO soundcards (user_id,rad_disp_id,type,dev_name) VALUES({0},{1},{2},'{3}')", MainForm2.userIDX, ID, 0,OUTName), conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("INSERT INTO soundcards (user_id,rad_disp_id,type,dev_name) VALUES({0},{1},{2},'{3}')", MainForm2.userIDX, ID, 1, INName), conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("INSERT INTO soundcards (user_id,rad_disp_id,type,dev_name) VALUES({0},{1},{2},'{3}')", MainForm2.userIDX, ID, 2, KeyName), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void AddGroupElement(int sc_id, int groupID) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("Delete from vehicle_group where sc_id={0}", sc_id), conn)) cmd.ExecuteNonQuery(); using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("INSERT INTO vehicle_group (sc_id,grp_ip) VALUES ({0},{1})", sc_id, groupID), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } /* public Int32 Get_sd_id(Int32 hid) { Int32 sd_id=0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT sd_id FROM sd_list where hid="+hid.ToString(), conn)) { NpgsqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { sd_id = dr.GetInt32(0); } } if (sd_id == 0) { using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("insert into sd_list (hid) VALUES({0})", hid), conn)) cmd.ExecuteNonQuery(); } name = (String)cmd.ExecuteScalar(); } return sd_id; }*/ public void RemoveGroupElement(int sc_id) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("Delete from vehicle_group where sc_id={0}", sc_id), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Send_cmd_to_val(Boolean TypeDO, String IMEI, String command) { Int32 typcmd = 0; // POLL command if (TypeDO) typcmd = 1; //DO set command using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand( string.Format("INSERT INTO sendtoval (type,imei,cmd,status) VALUES({0},'{1}','{2}',0)", typcmd, IMEI,command), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Update_SMS(Int32 status, Int32 idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE sms SET status={0} where idx={1}",status,idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void UnDelete_SMS(Int32 idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE sms SET deleted=0 where idx={0}", idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_SMS(Int32 idx) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("UPDATE sms SET deleted=1 where idx={0}", idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public void Delete_SMS_from_trash(int[] smsIDX_list) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); for (int i = 0; i < smsIDX_list.Length; i++) { using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format("Delete from sms where idx={0}", smsIDX_list[i]), conn)) cmd.ExecuteNonQuery(); } conn.Close(); } } public void ChangeSMSColor(Int32 idx, Color color) { using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { String hex = "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("UPDATE sms SET color='{0}' where idx={1}", hex, idx), conn)) cmd.ExecuteNonQuery(); conn.Close(); } } public Int32 GetNumberOfUnreadMessages(Int64 userID) { Int32 ret = 0; using (NpgsqlConnection conn = new NpgsqlConnection(MainForm2.MyConString)) { conn.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand("SELECT count(*) FROM sms " + "WHERE deleted = 0 AND mess not like 'Linx%.%' AND status = 3 AND " + " sc_id_sour IN (SELECT veh_id FROM vehicle_user WHERE user_id = " + userID + ") ", conn)) { ret = Convert.ToInt32((object)cmd.ExecuteScalar()); } conn.Close(); } return ret; } } }