SafeDispatch/Safedispatch_4_0/maptab/LiveTab.cs
2024-02-22 18:43:59 +02:00

4775 lines
208 KiB
C#

//#define jurgen
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Linq;
using MapGoogle;
using Telerik.WinControls.UI;
using Telerik.WinControls;
using Telerik.WinControls.UI.Docking;
using SafeMobileLib;
using Telerik.WinControls.Data;
using Dispatcher;
using Dispatcher.maptab.UIClasses;
using Safedispatch_4_0.Radio;
using Dispatcher.maptab;
using SafeMobileLib.Attributes;
using Dispatcher.Helpers;
using System.Device.Location;
using System.Threading.Tasks;
using System.Windows.Input;
using Telerik.WinControls.Enumerations;
using System.Timers;
namespace Safedispatch_4_0
{
/// <summary>
/// This class implements the live tab.</summary>
/// <remarks>
/// The live tab contains two areas, left and right. On the left side
/// the vehicle selection is made, and on the right side information
/// is displayed according to the criteria from the left</remarks>
public partial class LiveTab : UserControl
{
/// <summary>
/// The class constructor. </summary>
///
private MapHandler mapHandler;
private DBalarmManager dbalm;
public bool KillTimerActive = false;
private String latname = "";
private String lngname = "";
private String altname = "";
private String zonename = "";
private String milesh, kmh, msg2, s18;
public Boolean docLoad = false;
private Int32 loadcnt = 0;
public Int32 nrNavigatecnt = 0;
public String updatecomand = "";
public String getADDRcomand;
public String deleteDsetcomand = "";
public Boolean setdatasetBool = false;
public volatile Boolean TableViewDataComplete = true;
public volatile Boolean TableViewSortComplete = true;
public volatile Boolean TableViewFinish = true;
public volatile Boolean StreetViewOpened = false;
public Boolean isFilterLoaded = false;
public bool mapLoaded = false;
public bool parseLiveGridEvents = true;
public delegate void ProcessResponseFromMapInvokeCallBack(String url);
private bool isFirstTime = true;
private Thread threadForPeriodicThings;
private DateTime lastMapRestart = DateTime.Now;
public System.Timers.Timer changeCheckboxState = new System.Timers.Timer();
public LiveTab(MainForm2 parentParam, String tabNameParam)
{
parent = parentParam;
tabName = tabNameParam;
this.Name = tabName;
try
{
InitializeComponent();
}
catch (Exception ex)
{
SM.Debug("Error on Generate Live tab:" + ex.ToString());
if (ex.ToString().Contains("0x800736B1"))
{
ErrWithLink tmp = new ErrWithLink();
tmp.ShowDialog();
}
}
// create the toolTip that will be displayed when the user sets a pattern
// over the hint pictureBox
toolTipHelp = new ToolTip();
toolTipHelp.ToolTipTitle = "Live";
toolTipHelp.AutoPopDelay = 0;
toolTipHelp.InitialDelay = 0;
toolTipHelp.ReshowDelay = 0;
toolTipHelp.IsBalloon = false;
toolTipHelp.ShowAlways = true;
LiveGridColumn ctc = new LiveGridColumn("live");
ctc.AllowResize = true;
ctc.AllowGroup = true;
ctc.Name = "live";
ctc.FieldName = "live";
ctc.HeaderText = "live";
//ctc.AutoSizeMode = BestFitColumnMode.AllCells;
ctc.HeaderTextAlignment = ContentAlignment.MiddleLeft;
ctc.SortOrder = RadSortOrder.Ascending;
this.gridVehicles.TableElement.GroupIndent = 15;
this.gridVehicles.TableElement.RowHeight = 55;
this.gridVehicles.TableElement.AutoSizeMode = RadAutoSizeMode.Auto;
this.gridVehicles.AutoSizeRows = true;
//this.gridVehicles.TableElement.RowHeight = 55;
this.gridVehicles.Columns.Add(ctc);
this.gridVehicles.Columns.Move(ctc.Index, 0);
this.gridVehicles.GridViewElement.DrawBorder = false;
this.gridVehicles.GridViewElement.GroupPanelElement.DrawBorder = false;
LiveAddressGridColumn positionCell = new LiveAddressGridColumn("history");
positionCell.AllowResize = true;
positionCell.Name = "history";
positionCell.FieldName = "history";
//positionCell.MinWidth = 249;
//positionCell.MaxWidth = 249;
//positionCell.Width = 249;
positionCell.HeaderText = "history";
positionCell.AutoSizeMode = BestFitColumnMode.AllCells;
positionCell.HeaderTextAlignment = ContentAlignment.MiddleLeft;
positionCell.SortOrder = RadSortOrder.Ascending;
this.tableVehiclesList.TableElement.RowHeight = 75;
this.tableVehiclesList.Columns.Add(positionCell);
this.tableVehiclesList.Columns.Move(positionCell.Index, 0);
this.tableVehiclesList.GridViewElement.DrawBorder = false;
this.tableVehiclesList.GridViewElement.GroupPanelElement.DrawBorder = false;
// set the group comparer in order to display the custom groups in
// desired order
CustomGroupComparer gc = new CustomGroupComparer();
this.gridVehicles.MasterTemplate.GroupComparer = gc;
// change the icons for grouping and add them to the hashtable
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_group"))
MainForm2.imagesDictionary.Add("l_filter_group",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_user_n, MainForm2.ButtonColor));
// return the desired image
pbGroup.Image = MainForm2.imagesDictionary["l_filter_group"];
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_time"))
MainForm2.imagesDictionary.Add("l_filter_time",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_history_b, MainForm2.ButtonColor));
// return the desired image
pbGroupTime.Image = MainForm2.imagesDictionary["l_filter_time"];
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_status"))
MainForm2.imagesDictionary.Add("l_filter_status",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_bullet_bl, MainForm2.ButtonColor));
// return the desired image
pbGroupStatusType.Image = MainForm2.imagesDictionary["l_filter_status"];
pbFilter_Click(pbGroup, null);
#region THEMING
rlUnits.ForeColor = MainForm2.LabelColor;
rbDisplay.ButtonElement.ButtonFillElement.BackColor = MainForm2.ButtonColor;
pbFilter.Image = Utils.ChangeColor(global::Dispatcher.Properties.Resources.i_search, MainForm2.ButtonColor);
#endregion
#region LANGUAGE
string s1 = MainForm2.returnLNGString("displayButton"),
s2 = MainForm2.returnLNGString("cbselAll").ToUpper(),
s3 = MainForm2.returnLNGString("selectionExpando"),
s4 = MainForm2.returnLNGString("tabPage1"),
s5 = MainForm2.returnLNGString("tabPage2"),
s6 = MainForm2.returnLNGString("htableVehiclesListColumns1"),
s7 = MainForm2.returnLNGString("htableVehiclesListColumns1"),
s8 = MainForm2.returnLNGString("alarmsListColumns1"),
s9 = MainForm2.returnLNGString("tableVehiclesListColumns2"),
s10 = MainForm2.returnLNGString("tablevehiclesListColumns3"),
s11 = MainForm2.returnLNGString("tableVehiclesListColumns4"),
s12 = MainForm2.returnLNGString("lbGroup"),
s13 = MainForm2.returnLNGString("btGetAddress"),
s15 = MainForm2.returnLNGString("SMScomp"),
s16 = MainForm2.returnLNGString("DI"),
s17 = MainForm2.returnLNGString("DO"),
s19 = MainForm2.returnLNGString("quickhist"),
s20 = MainForm2.returnLNGString("snd"),
s21 = MainForm2.returnLNGString("changeDO"),
s22 = MainForm2.returnLNGString("radcheck");
s18 = MainForm2.returnLNGString("allunits");
langProgStat = MainForm2.returnLNGString("txProgStatLive");
latname = MainForm2.returnLNGString("colum2");
lngname = MainForm2.returnLNGString("colum3");
altname = MainForm2.returnLNGString("altname");
zonename = MainForm2.returnLNGString("zone");
msg2 = MainForm2.returnLNGString("toomany");
ckShowLand.Text = MainForm2.returnLNGString("prevland");
ckShowZone.Text = MainForm2.returnLNGString("prevzone");
txProgStatus.Text = MainForm2.returnLNGString("waitfor");
kmh = MainForm2.returnLNGString("kmh");
milesh = MainForm2.returnLNGString("milesh");
rbDisplay.Text = s1;
sel_desel.Text = s2;
windowUnits.Text = s3;
toolWindow2.Text = s4;
rlUnits.Text = MainForm2.returnLNGString("GrpUnits");
windowPositions.Text = MainForm2.returnLNGString("positions");
gridVehicles.Columns["unitName"].HeaderText = s6;
gridVehicles.Columns["status"].HeaderText = MainForm2.returnLNGString("SMSStatus");
tableVehiclesList.Columns["VehName"].HeaderText = s7;
tableVehiclesList.Columns["datetime"].HeaderText = s8;
tableVehiclesList.Columns["address"].HeaderText = s9;
if (MainForm2.isInMile) tableVehiclesList.Columns["speed"].HeaderText = s10 + " (" + milesh + ")";
else tableVehiclesList.Columns["speed"].HeaderText = s10 + " (" + kmh + ")";
tableVehiclesList.Columns["head"].HeaderText = s11;
tableVehiclesList.Columns["di"].HeaderText = s16;
tableVehiclesList.Columns["do"].HeaderText = s17;
sendSMSToolStripMenuItem1.Text = s15;
sendSMSToolStripMenuItem.Text = s15;
basicHistoryToolStripMenuItem.Text = s19;
sendPOLLToolStripMenuItem.Text = s20;
changeDOStatusToolStripMenuItem.Text = s21;
tableVehiclesList.Columns["lat"].HeaderText = latname;
tableVehiclesList.Columns["lng"].HeaderText = lngname;
tableVehiclesList.Columns["zone"].HeaderText = "";
tableVehiclesList.Columns["Altitude"].HeaderText = altname;
searchTextBox.NullText = MainForm2.returnLNGString("Typetosearchunit");
rcbAutoRefresh.Text = MainForm2.returnLNGString("enableAutoRefresh");
tableVehiclesList.Refresh();
rcbMarkersLables.Text = MainForm2.returnLNGString("showMarkersLabels");
ckShowZone.Text = MainForm2.returnLNGString("showGeofences");
ckShowLand.Text = MainForm2.returnLNGString("showLandmarks");
lbReportingInterval.Text = MainForm2.returnLNGString("maxNumberOfDisplayedUnits");
#endregion
/*
// set disabled images for time and status group
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_time_g"))
MainForm2.imagesDictionary.Add("l_filter_time_g", Utils.MakeGrayscale3(global::Dispatcher.Properties.Resources.l_history_b, 0.5f));
// return the desired image
pbGroupTime.Image = MainForm2.imagesDictionary["l_filter_time_g"];
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_status_g"))
MainForm2.imagesDictionary.Add("l_filter_status_g", Utils.MakeGrayscale3(global::Dispatcher.Properties.Resources.l_bullet_bl, 0.5f));
// return the desired image
pbGroupStatusType.Image = MainForm2.imagesDictionary["l_filter_status_g"];
*/
/*
Font f = new Font("Segae UI", 11f, FontStyle.Regular);
gridVehicles.TableElement.RowHeight = 32;
gridVehicles.Font = f;
//vehiclesList.*/
threadForPeriodicThings = new Thread(delegate ()
{
int count = 0;
while (MainForm2.isRunning)
{
Thread.Sleep(100);
// check if a minute had passed
if (count++ > 60 * 10)
{
count = 0;
this.Invoke((MethodInvoker)delegate ()
{
// refresh the grid each minute
RefreshUnitTimerExpired();
});
// check at each minute if the map needs to be restarted due to long running
if (MainForm2.cfg.MapRestart && (DateTime.Now - lastMapRestart).Minutes >= MainForm2.cfg.MapRestartMinutes)
{
this.Invoke((MethodInvoker)delegate ()
{
Utils.WriteLine($"Map Handler will restart because last restart was @ {lastMapRestart.ToString()}", ConsoleColor.Yellow);
lastMapRestart = DateTime.Now;
mapHandler?.RestartMap();
});
}
}
}
});
threadForPeriodicThings.Start();
// show landmarks and geofences is needed
foreach (Control x in this.windowUnits.Controls)
{
if (x is PictureBox)
{
string key = this.Name + "_" + "PictureBox_Filter";
if (MainForm2.HashVal.Contains(key) && ((PictureBox)x).Name == MainForm2.HashVal[key].ToString())
pbFilter_Click(((PictureBox)x), null);
}
}
VisualSettings.loadUserVisualSettings(tabName, this.windowUnits, MainForm2.HashVal);
isFilterLoaded = true;
if (MainForm2.HashVal.ContainsKey("showMarkersLables"))
MainForm2.Displaywithname = Convert.ToBoolean(MainForm2.HashVal["showMarkersLables"]);
String safemobileDirPath = System.Windows.Forms.Application.StartupPath.Replace('\\', '/').Replace(" ", "%20");
safemobileDirPath = safemobileDirPath.Replace("#", "%23");
String mapUrl = "file:///" + safemobileDirPath + "/resource/" + MainForm2.MapHtmlName;
LatLngZoom centerPosition = new LatLngZoom() { Lat = MainForm2.LatStart, Lng = MainForm2.LngStart, ZoomLevel = MainForm2.ZoomStart };
mapHandler = new MapHandler(mapUrl)
{
MapHashName = tabName,
HasLabels = rcbMarkersLables.Checked,
IsMetric = !MainForm2.isInMile,
ConsoleVisible = MainForm2.MapDebugConsole,
IconTheme = MainForm2.iconThemeType,
IconType = MainForm2.iconType,
CenterPosition = centerPosition,
HideTimeInactiveUnits = MainForm2.HideInactiveUnitsCheck,
HideNonEmergUnits = MainForm2.emergOnlyCheck,
InactiveTimeoutMinutes = MainForm2.Livelastmin,
IsNeverReportedWarning = false,
MaxDisplayedNrOfUnits = 2000
};
mapHandler.Dock = DockStyle.Fill;
// register for event
ckShowZone.ToggleStateChanged += ckShowZone_ToggleStateChanged;
ckShowLand.ToggleStateChanged += ckShowLand_ToggleStateChanged;
#region MAP HANDLERS
mapHandler.OnMapLoaded += delegate ()
{
docLoad = true;
// set
if (isFirstTime)
{
List<Vehicle> vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
foreach (Vehicle veh in vehicles)
{
try
{
String imei = veh.IMEI;
bool isDisplayed = VisualSettings.IsDisplayedInLiveTab(veh.sipID, tabName);
if (!MainForm2.VehIMEIHash.ContainsKey(imei))
continue;
((MapElement)((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[imei + ""]]).MapsHT[tabName]).itemCheck = isDisplayed;
// check and create emergency icon if in emergency
if (veh.is_emergency)
IconHelper.CheckCreateEmergencyIcon(veh.IconID);
if (isDisplayed)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[imei + ""]]).MapsHT[tabName]).ActivatePushPin();
}
else
((MapElement)((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[imei + ""]]).MapsHT[tabName]).DeactivatePushpin();
(((Vehicle)MainForm2.vehicleHT[(String)MainForm2.VehIMEIHash[imei + ""]])).is_displayed = isDisplayed;
}
catch (Exception ex)
{
Utils.WriteLine("Exception ex: " + ex.ToString(), ConsoleColor.Red);
}
}
isFirstTime = false;
}
// detect which units needs to be added on the map from last session
List<Vehicle> toDisplayVehicles = new List<Vehicle>();
List<Vehicle> htList = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
IEnumerable<IGrouping<int, Vehicle>> query = htList.GroupBy(d => d.group.Id, d => d);
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
{
String groupName = group.FirstOrDefault(d => d.sipID > 0).group.Name;
int groupUnits = group.ToList().Count;
int groupDisplayedUnits = group.Count(d => ((MapElement)d.MapsHT[tabName]).itemCheck);
// see if all the units are checked and raise the event for updating the group checked event
if (groupUnits == groupDisplayedUnits)
{
// Print the key value of the IGrouping.
Utils.WriteLine($"{groupName} has {groupUnits} units [{groupDisplayedUnits} displayed]");
for (int i = 0; i < gridVehicles.Groups.Count; i++)
{
if (gridVehicles.Groups[i].Key.Equals(groupName))
{
// update the grid units on left map
IEnumerable<DataforVehList> resLiveGrid = ListforVehList.Select(d => d).Where(d => (group.Select(w => w.IMEI)).Contains(d.RadioId));
foreach (DataforVehList ve in resLiveGrid)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
}
if (groupsHeadersByString.ContainsKey(groupName))
groupsHeadersByString[groupName].checkbox.Checked = true;
mapHandler.AddGroup(groupName, group.ToList(), false);
//groupsHeadersByString[groupName].checkbox.PerformClick();
//GridViewInfo v = gridVehicles.Groups[i].GroupRow.ViewInfo.CurrentRow.ViewInfo; // as CustomGroupHeaderCell;
// GridGroupContentCellElement
//GroupCheckBox_StateChanged(mapHandler, new GRPEventArgs(i, true));
}
}
}
else if (groupUnits - groupDisplayedUnits > 0)
toDisplayVehicles.AddRange(group.Select(d => d).Where(d => ((MapElement)d.MapsHT[tabName]).itemCheck).ToList());
}
// display the units that are checked and not a part of a group
mapHandler.AddVehicles(toDisplayVehicles, true);
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Select(d => d).Where(d => (toDisplayVehicles.Select(w => w.IMEI)).Contains(d.RadioId));
foreach (DataforVehList ve in result)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
}
// flag that the map had finished loading
mapLoaded = true;
this.Invoke((MethodInvoker)delegate ()
{
if (WaitWindow != null)
WaitWindow.Close();
// show or hide geofences
if (ckShowZone.Checked)
ckShowZone_ToggleStateChanged(ckShowZone, new StateChangedEventArgs(ckShowLand.Checked
? Telerik.WinControls.Enumerations.ToggleState.On : Telerik.WinControls.Enumerations.ToggleState.Off));
// !!!!!!!!!!!!!!!!! THIS MUST BE THE LAST METHOD IN THE LOADED EVENT !!!!!!!!!!!!!!!!
// show or hide landmarks
if (ckShowLand.Checked)
ckShowLand_ToggleStateChanged(ckShowZone, new StateChangedEventArgs(ckShowZone.Checked
? Telerik.WinControls.Enumerations.ToggleState.On : Telerik.WinControls.Enumerations.ToggleState.Off));
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
// update the group header
onGroupDisplayedUnitsChangedHandler(group.FirstOrDefault(d => d.sipID > 0).group.Name);
});
};
mapHandler.OnNearestRequest += delegate (int x, int y, double lat, double lng)
{
OnNearestMapRequest(x, y, lat, lng);
};
mapHandler.OnUnitDisplayReq += delegate (String unitName)
{
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Where(d => d.UnitName.Equals(unitName));
foreach (DataforVehList ve in result)
{
if (!ve.OnMap)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).ActivatePushPin();
VisualSettings.SetDisplayedInLiveTab(ve.SipId, true, tabName);
List<Vehicle> vehs = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(d => d.busName.Equals(unitName)).ToList();
if (vehs.Count > 0)
mapHandler.AddVehicles(new List<Vehicle>() { vehs[0] }, false);
}
}
};
mapHandler.OnNeverReportedWarning += delegate (int numberOfUnits)
{
this.Invoke((MethodInvoker)delegate ()
{
//displayNeverReportedWarning(numberOfUnits);
});
};
mapHandler.OnInactiveUnitsWarning += delegate (int numberOfUnits)
{
this.Invoke((MethodInvoker)delegate ()
{
//displayInactiveMinutesWarning(numberOfUnits);
});
};
mapHandler.OnGeofencesDisplayed += delegate (int geofencesCount)
{
this.Invoke((MethodInvoker)delegate ()
{
parent.DisplayToast(MainForm2.returnLNGString("geofenceDisplayed"),
"<html><b>" + geofencesCount + " " + MainForm2.returnLNGString("geofences") + " </b> " + MainForm2.returnLNGString("mapdisp") + " </html>");
});
};
mapHandler.OnLandmarksDisplayed += delegate (int landmarksCount)
{
this.Invoke((MethodInvoker)delegate ()
{
parent.DisplayToast(MainForm2.returnLNGString("landDisp"),
string.Format(MainForm2.returnLNGString("landHTML"), landmarksCount));
});
};
mapHandler.OnMapDead += delegate ()
{
this.Invoke((MethodInvoker)delegate ()
{
// parent.DisplayToast("MAP DEAD !!!!!!!!!!!", "It's dead JIM");
// restart the map
//mapHandler.RestartMap();
});
};
mapHandler.OnMapProgressChanged += delegate (int currentStep, int totalSteps, String message)
{
this.Invoke((MethodInvoker)delegate ()
{
try
{
mapLoadingPanel.Visible = !message.Equals("done");
mapLoadingBar.Maximum = totalSteps;
mapLoadingBar.Value1 = message.Equals("done") ? totalSteps : currentStep;
mapLoadingBar.Text = currentStep + " out of " + totalSteps;
mapLoadingMessage.Text = message;
}
catch (Exception ex)
{
Utils.WriteLine("Exception " + ex.ToString(), ConsoleColor.Red);
}
});
};
mapHandler.OnTextMessageRequest += delegate (String unitName, String message)
{
string imei = ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI;
((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
string GatewayAndRadioID = ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID;
// store if the text message was trimmed or not
bool isTrimmed = false;
// check if the message is larger than the maximum number of characters accepted
// by the radio system
int gwType = (int)GatewayType.Unknown;
if (MainForm2.radioGwHT[GatewayAndRadioID] != null)
{
gwType = ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type;
}
if (message.Length > SmsUtils.GetMaxNumberOfCharacters(gwType))
{
isTrimmed = true;
message = message.Substring(0, SmsUtils.GetMaxNumberOfCharacters(gwType));
}
int sc_id = ((Vehicle)MainForm2.vehicleHT[unitName]).sc_id;
int sched_time = (int)DateTime.Now.ToUniversalTime().DateTo70Format();
//((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
////String Totrans = "#142#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "." + imei + "#" + textMessage + "#" + sched_time + "#";
//String Totrans = "#142#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "." + imei + "#" + textMessage + "#" + sched_time + "#" + MainForm2.userIDX + "#";
//parent.DisplayToast(MainForm2.returnLNGString("txtMsgTo") + " " + unitName,
// (isTrimmed ? (MainForm2.returnLNGString("trimmed") + " ") : "") +
// string.Format(MainForm2.returnLNGString("MsHTML"), textMessage));
//parent.Send_UDP_cmd(Totrans, 0, 0);
parent.SendSmsOnMBus(message, sc_id, sched_time);
};
mapHandler.OnPTTButtonPressChanged += delegate (String unitName, bool isPressed)
{
string imei = ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI;
bool canMakeSipCalls = ((Vehicle)MainForm2.vehicleHT[unitName]).canMakeSipCalls;
int sipID = ((Vehicle)MainForm2.vehicleHT[unitName]).sipID;
if (MainForm2.VoiceTabStarted)
{
if (isPressed)
{
parent.RadioTabControl.sendPTT(
new Subscriber()
{
DispatcherName = unitName,
SubscriberType = SubscriberType.SUBSCRIBER,
ImageKey = "i_classic_bus_02",
IconFilePath = IconHelper.GetIconPathForUnit(unitName),
Sc_id = 0,
Imei = imei,
Gw_and_radioID = parent.RadioTabControl.Valid_GwID_and_RadioID,
IP = String.Format("224.10.{0}", parent.RadioTabControl.Valid_GwID_and_RadioID),
Favorite = false,
canMakeSipCalls = canMakeSipCalls,
SipID = sipID
}, true
);
}
else
{
parent.RadioTabControl.StopPTT(
new Subscriber()
{
DispatcherName = unitName,
SubscriberType = SubscriberType.SUBSCRIBER,
ImageKey = "i_classic_bus_02",
IconFilePath = IconHelper.GetIconPathForUnit(unitName),
Sc_id = 0,
Imei = imei,
Gw_and_radioID = parent.RadioTabControl.Valid_GwID_and_RadioID,
IP = String.Format("224.10.{0}", parent.RadioTabControl.Valid_GwID_and_RadioID),
Favorite = false,
canMakeSipCalls = canMakeSipCalls,
SipID = sipID
}
);
}
}
else
{
// Initializez vocea
parent.CheckTabs(track_type.RADIO, parent.GetTabNewRadio);
parent_OnCallStatusChanged(unitName, false, false);
}
};
mapHandler.OnStreetViewStateChanged += delegate (bool isOpened)
{
StreetViewOpened = isOpened;
};
#endregion
mapGoogles = new CefSharpChromiumWebBrowser(mapUrl);
LiveMapPanel.Controls.Add(mapHandler);
if (MainForm2.NOAddress)
tableVehiclesList.Columns["address"].IsVisible = false;
//mapGoogles.AllowFileAccessFromFileURLs = true;
try
{
if (MainForm2.is24hours)
{
if (MainForm2.DayFirst)
((GridViewDateTimeColumn)tableVehiclesList.Columns["datetime"]).FormatString = "{0:dd/MM/yyyy HH:mm:ss}";
else
((GridViewDateTimeColumn)tableVehiclesList.Columns["datetime"]).FormatString = "{0:MM/dd/yyyy HH:mm:ss}";
}
else
{
if (MainForm2.DayFirst)
((GridViewDateTimeColumn)tableVehiclesList.Columns["datetime"]).FormatString = "{0:dd/MM/yyyy hh:mm:ss tt}";
else
((GridViewDateTimeColumn)tableVehiclesList.Columns["datetime"]).FormatString = "{0:MM/dd/yyyy hh:mm:ss tt}";
}
}
catch (Exception ex)
{
SM.Debug("Error on gridview DateFormat:" + ex.ToString());
}
//this.SelectionLive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(219)))), ((int)(((byte)(255)))));
LiveWaitingBar.ThemeClassName = "Telerik.WinControls.UI.RadWaitingBar";
LiveWaitingBar.ThemeName = "Telerik";
LiveWaitingBar.Visible = false;
txProgStatus.Visible = false;
LivePanel.Visible = false;
Console.WriteLine("Panel visibil false 2");
this.DrawMap();
SM.Debug("Start timer");
TimerLoad3Sec.Enabled = true;
TimerLoad3Sec.Start();
SM.Debug("Da e pornit timer");
populateVehiclesList(vehicleListNames);
//ChangeIcons(vehicleListNames);
GetPositionForPlace = false;
GetPositionForStart = false;
GetPositionForZones = false;
if (MainForm2.MotoTURBO)
{
sendPOLLToolStripMenuItem.Visibility = Telerik.WinControls.ElementVisibility.Hidden;
changeDOStatusToolStripMenuItem.Visibility = Telerik.WinControls.ElementVisibility.Hidden;
}
else sendSMSToolStripMenuItem1.Visibility = Telerik.WinControls.ElementVisibility.Hidden;
windowUnits.ToolCaptionButtons = Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.AutoHide | Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.SystemMenu;
//toolWindow1.ToolCaptionButtons = Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.SystemMenu;
windowUnits.DocumentButtons &= ~Telerik.WinControls.UI.Docking.DocumentStripButtons.Close;
windowUnits.AllowedDockState = AllowedDockState.Docked | AllowedDockState.AutoHide;
toolWindow2.ToolCaptionButtons = Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.AutoHide | Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.SystemMenu;
toolWindow2.DocumentButtons &= ~Telerik.WinControls.UI.Docking.DocumentStripButtons.Close;
//toolWindow3.ToolCaptionButtons = Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.AutoHide | Telerik.WinControls.UI.Docking.ToolStripCaptionButtons.SystemMenu;
//toolWindow3.DocumentButtons &= ~Telerik.WinControls.UI.Docking.DocumentStripButtons.Close;
//toolWindow3.AllowedDockState = AllowedDockState.Docked | AllowedDockState.AutoHide;
ContextMenuService menuService = this.radDock1.GetService<ContextMenuService>();
menuService.ContextMenuDisplaying += menuService_ContextMenuDisplaying;
//this disables the context menu
menuService.AllowActiveWindowListContextMenu = false;
menuService.AllowDocumentContextMenu = false;
menuService.AllowToolContextMenu = false;
switch (MainForm2.radioType)
{
case RADIOTYPE.HYT:
radDock1.BackColor = MainForm2.HyteraColor;
LivePanel.BackColor = MainForm2.HyteraColor;
//radSplitContainer1.BackColor = MainForm2.HyteraColor;
documentTabStrip1.BackColor = MainForm2.HyteraColor;
break;
case RADIOTYPE.HARRIS:
radDock1.BackColor = MainForm2.HarrisColor;
LivePanel.BackColor = MainForm2.HarrisColor;
//radSplitContainer1.BackColor = MainForm2.HarrisColor;
documentTabStrip1.BackColor = MainForm2.HarrisColor;
break;
case RADIOTYPE.ATLAS:
radDock1.BackColor = MainForm2.HarrisColor;
LivePanel.BackColor = MainForm2.HarrisColor;
//radSplitContainer1.BackColor = MainForm2.HarrisColor;
documentTabStrip1.BackColor = MainForm2.HarrisColor;
break;
case RADIOTYPE.SIMOCO:
//we don't need this
break;
case RADIOTYPE.EXCERA:
//we don't need this
break;
}
dbalm = new DBalarmManager(MainForm2.cfg.DB_IP, MainForm2.cfg.DB_schema, MainForm2.cfg.DB_user, MainForm2.cfg.DB_passwd, MainForm2.cfg.DB_port);
//vehiclesList.TableElement.RowHeight = 32;
#if jurgen
((GridViewCheckBoxColumn)vehiclesList.Columns[3]).ReadOnly = true;
#endif
//RadMessageBox.Show("Please wait for map loading... \n This window will disapper after 10 seconds", "Wait for loading", MessageBoxButtons.OK);
rddlGroupingType.Items.Clear();
//RadListDataItem item = new RadListDataItem(MainForm2.returnLNGString("")) { Tag = "categories" };
rddlGroupingType.Items.Add(new RadListDataItem(MainForm2.returnLNGString("liveGroupingCategories")) { Tag = "categories" });
if (MainForm2.HasVoice)
rddlGroupingType.Items.Add(new RadListDataItem(MainForm2.returnLNGString("liveGroupingRadioGateway")) { Tag = "radiogateway" });
String currentGroupingType = VisualSettings.GetGroupingTypeInLiveTab(tabName);
bool found = false;
foreach (RadListDataItem item in rddlGroupingType.Items)
{
if (currentGroupingType == null)
{
item.Selected = true;
VisualSettings.SetGroupingTypeInLiveTab(item.Tag + "", tabName);
break;
}
else if (item.Tag.ToString().Equals(currentGroupingType))
{
item.Selected = true;
found = true;
}
}
rddlGroupingType.SelectedIndexChanged += GroupingType_SelectedIndexChanged;
if (!found)
rddlGroupingType.SelectedIndex = 0;
GroupLiveGrid(rddlGroupingType.SelectedItem.Tag.ToString().Equals("categories") ? GroupType.GROUPNAME : GroupType.RADIOGATEWAY, false);
chkWebsocketConnected.Visible = false;
if (MainForm2.hasDBAccess)
{
chkWebsocketConnected.Visible = true;
OnWebSocketStatusChanged(ToggleState.Indeterminate);
changeCheckboxState.Elapsed += new ElapsedEventHandler(ChangeCheckboxState);
changeCheckboxState.Interval = 10000;
changeCheckboxState.Enabled = true;
}
}
private void GroupingType_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
// skip the case when the position is out of bounds
if (!(e.Position >= 0 && e.Position < rddlGroupingType.Items.Count))
return;
RadListDataItem selectedItem = rddlGroupingType.Items[e.Position];
GroupLiveGrid(selectedItem.Tag.ToString().Equals("categories") ? GroupType.GROUPNAME : GroupType.RADIOGATEWAY, false);
VisualSettings.SetGroupingTypeInLiveTab(selectedItem.Tag + "", tabName);
}
public void updateGwAndRagioGatewayForSubscriber(String radioID, String gwId, String radioGwId)
{
//Utils.WriteLine("updateGwAndRagioGatewayForSubscriber " + radioID, ConsoleColor.DarkMagenta);
gridVehicles.BeginEdit();
foreach (DataforVehList item in ListforVehList)
{
if (item == null)
continue;
if (item.RadioId.Equals(radioID))
{
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (gwId + "." + radioGwId).Equals(d.Gw_id + "." + d.Id));
item.RadioGateway = rg != null ? rg.Name : MainForm2.returnLNGString("Unassigned");
item.NrOfUpdates++;
}
}
gridVehicles.EndEdit();
}
private void rlUnits_Click(object sender, EventArgs e)
{
if (mapHandler == null)
return;
;// OnNearestMapRequest(6, 8, 44.4335723, 26.1119778);
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
mapHandler.ConsoleVisible = !mapHandler.ConsoleVisible;
}
private void OnNearestMapRequest(int x, int y, double lat, double lng)
{
int numberOfNearestResponse = 10;
List<Vehicle> allVehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
var coord = new GeoCoordinate(lat, lng);
// get nearest vehicles coordinates
var nearestCoordinatesForUnitsWithGpsOn = (allVehicles.Where(d => d.actual_status == Status_for_tab.GPS_ON))
.Select(w => new GeoCoordinate(w.LAT, w.LNG, w.sipID))
.OrderBy(w => w.GetDistanceTo(coord)).Take(numberOfNearestResponse).ToList();
// get more units if the required number is not filled by those with gps on
if(nearestCoordinatesForUnitsWithGpsOn.Count < numberOfNearestResponse)
{
var nearestCoordinatesForUnitsWithGpsNotOn = (allVehicles.Where(d => d.actual_status != Status_for_tab.GPS_ON))
.Select(w => new GeoCoordinate(w.LAT, w.LNG, w.sipID))
.OrderBy(w => w.GetDistanceTo(coord)).Take(numberOfNearestResponse).ToList();
// add number of units from those with GPS not on so it will provide with the required number
nearestCoordinatesForUnitsWithGpsOn.AddRange(nearestCoordinatesForUnitsWithGpsNotOn
.Take(numberOfNearestResponse - nearestCoordinatesForUnitsWithGpsOn.Count));
}
// get only the sip Ids for the nearest vehicles by coordinates (ordered by distance)
var nearestCoordinatesSipIds = nearestCoordinatesForUnitsWithGpsOn.Select(d => d.Altitude).ToList();
// get the vehicles associated with those sip Ids
var nearestVehicles = allVehicles.Where(w => (nearestCoordinatesForUnitsWithGpsOn.Select(d => d.Altitude).Contains(w.sipID)))
.OrderBy(w => (nearestCoordinatesSipIds.IndexOf(w.sipID))).ToList();
//TODO get transparent icons for those that are not displayed
foreach(Vehicle veh in nearestVehicles)
{
if (!((MapElement)veh.MapsHT[tabName]).itemCheck)
IconHelper.CheckCreateTransparentIcon(veh.IconID);
}
// #######################################
// #######################################
// send response to the map
mapHandler.NearestUnitResponse(x, y, lat, lng, nearestVehicles);
}
private void onGroupDisplayedUnitsChangedHandler(String groupName)
{
List<Vehicle> groupVehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(groupName)).ToList();
// count the number of displayed units
int displayVehiclesCount = groupVehicles.Select(d => d).Where(d => ((MapElement)d.MapsHT[tabName]).itemCheck).Count();
// change the header name
ChangeGroupHeaderDisplayedUnits(groupName, displayVehiclesCount, groupVehicles.Count);
// display abote the live grid the number of displayed units
UpdateUnitsDisplayedNumberLabel();
}
private void ChangeGroupHeaderDisplayedUnits(String groupName, int displayedNumberInGroup, int totalNumberInGroup)
{
for(int i=0; i < gridVehicles.Groups.Count; i++)
{
if (gridVehicles.Groups[i].Key.Equals(groupName))
{
gridVehicles.Groups[i].Header = groupName + " [" + displayedNumberInGroup + MainForm2.returnLNGString("of") + totalNumberInGroup + "]";
gridVehicles.Groups[i].GroupRow.HeaderText = gridVehicles.Groups[i].Header;
/*
vehiclesList_GroupSummaryEvaluate(gridVehicles, new GroupSummaryEvaluationEventArgs(gridVehicles.Groups[i], gridVehicles.Groups[i],
gridVehicles.Groups[i].Header, null, null, null));
*/
}
}
/*
for (int contor = 0; contor < gridVehicles.ChildRows.Count; contor++)
{
GridViewGroupRowInfo row = gridVehicles.ChildRows[contor] as GridViewGroupRowInfo;
if (row != null && row.Group.Key.Equals(groupName))
{
row.Group.Header = groupName + " [" + displayedNumberInGroup + " of " + totalNumberInGroup + "]";
}
}*/
}
private String getGroupHeaderCount(String groupName)
{
List<Vehicle> groupVehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(groupName)).ToList();
// count the number of displayed units
int displayVehiclesCount = groupVehicles.Select(d => d).Where(d => !((MapElement)d.MapsHT[tabName]).itemCheck).Count();
return " [" + displayVehiclesCount + " of " + groupVehicles.Count + "]";
}
private void displayInactiveMinutesWarning(int numberOfUnits)
{
parent.DisplayToast(MainForm2.returnLNGString("inactiveMinutes"),
String.Format(MainForm2.returnLNGString("HTMLinactiveMinutesUnits"), numberOfUnits, MainForm2.Livelastmin));
}
private void displayNeverReportedWarning(int numberOfUnits)
{
parent.DisplayToast(MainForm2.returnLNGString("noGPS"),
String.Format(MainForm2.returnLNGString("HTMLNoGPSMap"), numberOfUnits));
}
private int getNumberOfDisplayedUsers()
{
return (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(d => ((MapElement)d.MapsHT[tabName]).itemCheck).Count();
}
private void UpdateUnitsDisplayedNumberLabel()
{
rlUnits.Text = String.Format(MainForm2.returnLNGString("unitsDisplayed"), getNumberOfDisplayedUsers());
}
private void menuService_ContextMenuDisplaying(object sender, ContextMenuDisplayingEventArgs e)
{
try
{
if (e.MenuType == ContextMenuType.DockWindow &&
e.DockWindow.DockTabStrip is DocumentTabStrip)
{
for (int i = 0; i < e.MenuItems.Count; i++)
{
RadMenuItemBase menuItem = e.MenuItems[i];
if (menuItem.Name == "CloseWindow" ||
menuItem.Name == "CloseAllButThis" ||
menuItem.Name == "CloseAll" ||
menuItem.Name == "Floating" ||
menuItem.Name == "Docked" ||
menuItem.Name == "Hidden" ||
menuItem is RadMenuSeparatorItem)
{
menuItem.Visibility = Telerik.WinControls.ElementVisibility.Collapsed;
}
}
}
}
catch (Exception ex)
{
SM.Debug("ExLive1:" + ex.ToString());
}
}
/// <summary>
/// Handler for when a GPS Position was received for a particular unit
/// </summary>
/// <param name="unitName">Unit name for which the GPS position was received</param>
/// <param name="isFirstPositionForUnit">Flag if this is the first position for that unit</param>
public void onGPSPositionReceivedHandler(String unitName, bool isFirstPositionForUnit)
{
try
{
//Utils.WriteLine("Sending GPS to the mapHandler for " + unitName);
mapHandler.GPSUpdate((Vehicle)MainForm2.vehicleHT[unitName]);
this.Invoke((MethodInvoker)delegate ()
{
onPositionListUnitChanged(unitName);
onUnitPositionOrStateChanged(unitName);
// if this is the first position in history for this unit perform an update to display the unit on map
if (isFirstPositionForUnit)
{
ComputeCheckedVehicles(false);
}
});
}
catch (Exception ex)
{
SM.Debug("Unable to move unit on tab " + tabName + " ex:" + ex.ToString());
}
}
private Hashtable CheckedGroup = new Hashtable();
private volatile Hashtable CheckedGroupTmp = new Hashtable();
/// <summary>
///populates the list of vehicles from the left part of the tab </summary>
/// <param name="listOfVehicles">an array of strings containing the vehicles names</param>
public volatile List<DataforVehList> ListforVehList = new List<DataforVehList>();
volatile String GroupNameforgrid = "";
volatile Image Imageforgrid = null;
volatile String Statusforgrid = "";
volatile Int32 EmergStat = 0;
private List<DataforVehList> getVehiclesGridList()
{
List<DataforVehList> list = new List<DataforVehList>();
List<Vehicle> vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
foreach (Vehicle veh in vehicles)
{
String iconFilePath = IconHelper.GetIconPathForUnit(veh.busName);
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey(iconFilePath))
{
Image img = IconHelper.GetIconForUnit(veh);
MainForm2.imagesDictionary.Add(iconFilePath, img == null ? imageList1.Images[2] : img);
}
///new emergency status
EmergStat = 0;
if (veh.is_emergency)
EmergStat = 1;
Statusforgrid = Vehicle.GetString_Status(veh.actual_status);
// add vehicle with position to the list
list.Add(new DataforVehList()
{
RadioId = veh.IMEI,
SipId = veh.sipID,
GrpName = veh.group.Name,
Pict = MainForm2.imagesDictionary[iconFilePath],
UnitName = veh.busName,
OnMap = VisualSettings.IsDisplayedInLiveTab(veh.sipID, tabName),
UnitStatus = veh.actual_status,
Status = Statusforgrid,
Emerg0off1on = EmergStat,
IsEmergency = veh.is_emergency,
Latitude = veh.LAT,
Longitude = veh.LNG,
Address = veh.GetLastAddress(),
PositionTime = veh.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(), //lastValidPositionTime)),
Speed = veh.GetSpeed(),
IsMPH = MainForm2.isInMile,
HasAlerts = false,
HasVoice = veh.has_voice,
HasText = veh.has_text,
Stolen = veh.is_stolen
});
}
return list;
}
private void SetGroupExpandedStates()
{
GridExpandAnimationType temp = gridVehicles.GroupExpandAnimationType;
gridVehicles.GroupExpandAnimationType = GridExpandAnimationType.None;
for (int i = 0; i < gridVehicles.Groups.Count; i++)
{
bool? isGroupExpanded = VisualSettings.IsGroupExpandedInLiveTab((gridVehicles.Groups[i]).Key + "", tabName);
if (isGroupExpanded == null || isGroupExpanded == true)
gridVehicles.Groups[i].Expand();
else
gridVehicles.Groups[i].Collapse();
}
gridVehicles.GroupExpandAnimationType = temp;
gridVehicles.TableElement.ScrollToRow(0);
}
private void populateVehiclesList(ArrayList listOfVehicles)
{
SM.Debug("Before populate VehicleList");
try
{
ListforVehList.Clear();
gridVehicles.Columns["unitName"].SortOrder = RadSortOrder.None;
int cont = 0;
foreach (String obj in MainForm2.vehicleHT.Keys)
{
GroupNameforgrid = ((Vehicle)MainForm2.vehicleHT[obj]).group.Name;
/*MainForm2.returnLNGString("otherunit");
if (MainForm2.GrpIdforScId[((Vehicle)MainForm2.vehicleHT[obj]).sc_id] != null)
GroupNameforgrid = ((GroupClass)MainForm2.GrpIdforScId[((Vehicle)MainForm2.vehicleHT[obj]).sc_id]).name;
*/
Car crtCar = ((Car)MainForm2.carlist[((Vehicle)MainForm2.vehicleHT[obj]).IconID]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
continue;
}
String iconPath = crtCar.listFilePath;
try
{
Bitmap bmp = new Bitmap(iconPath);
Image tmp2 = Utils.ScaleImage(bmp, 64, 64); //tmp.ToBitmap();
tmp2.Tag = crtCar.listFilePath;
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey(crtCar.listFilePath))
MainForm2.imagesDictionary.Add(crtCar.listFilePath, tmp2);
// set the icon for the unit
Imageforgrid = MainForm2.imagesDictionary[crtCar.listFilePath];
}
catch (Exception)
{
SM.Debug("Grid icon could not be found [" + iconPath + "]");
Imageforgrid = imageList1.Images[2];
}
///new emergency status
EmergStat = 0;
if (((Vehicle)MainForm2.vehicleHT[obj]).is_emergency)
EmergStat = 1;
// get the
Vehicle veh = ((Vehicle)MainForm2.vehicleHT[obj]);
Statusforgrid = Vehicle.GetString_Status(veh.actual_status);
cont++;
RadioGateway rg = MainForm2.myGatewaylist.Find(d => (veh.GwandRadioID).Equals(d.Gw_id + "." + d.Id));
String gatewayName = rg == null ? MainForm2.returnLNGString("Unassigned") : rg.Name;
// add vehicle with position to the list
ListforVehList.Add(new DataforVehList()
{
RadioId = veh.IMEI,
SipId = veh.sipID,
GrpName = GroupNameforgrid,
Pict = Imageforgrid,
UnitName = obj,
OnMap = ((MapElement)veh.MapsHT[tabName]).itemCheck,
UnitStatus = veh.actual_status,
Status = Statusforgrid,
Emerg0off1on = EmergStat,
IsEmergency = veh.is_emergency,
Latitude = veh.LAT,
Longitude = veh.LNG,
Address = veh.GetLastAddress(),
PositionTime = veh.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(), //lastValidPositionTime)),
Speed = veh.GetSpeed(),
IsMPH = MainForm2.isInMile,
HasAlerts = false,
HasVoice = veh.has_voice,
HasText = veh.has_text,
Stolen = veh.is_stolen,
RadioGateway = gatewayName
});
}
try
{
// set data source and refresh it
gridVehicles.DataSource = null;
gridVehicles.DataSource = ListforVehList;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
gridVehicles.Columns["unitName"].SortOrder = RadSortOrder.Ascending;
gridVehicles.MasterTemplate.GroupDescriptors.Clear();
GroupDescriptor groupDescriptor = new GroupDescriptor();
groupDescriptor.GroupNames.Add(gridVehicles.Columns["GroupName"].Name, ListSortDirection.Ascending);
gridVehicles.GroupDescriptors.Add(groupDescriptor);
CheckedGroup.Clear();
GridExpandAnimationType temp = gridVehicles.GroupExpandAnimationType;
gridVehicles.GroupExpandAnimationType = GridExpandAnimationType.None;
for (int i = 0; i < gridVehicles.Groups.Count; i++)
{
string key = this.tabName + "_" + "ExpandGroupingHT_" + (gridVehicles.Groups[i]).Key;
if (MainForm2.HashVal.ContainsKey(key))
{
if(Boolean.Parse(MainForm2.HashVal[key] +"") )
this.Expand(gridVehicles.Groups[i]);
}
else
{
this.Expand(gridVehicles.Groups[i]);
}
//vehiclesList.Groups[i].HeaderRow
CheckedGroup.Add(i, false);
}
gridVehicles.GroupExpandAnimationType = temp;
gridVehicles.TableElement.ScrollToRow(0);
}
catch (Exception ex)
{
SM.Debug("ExLive4:" + ex.ToString());
}
SM.Debug("Finish populate VehicleList");
}
private void Expand(DataGroup group)
{
try
{
group.Expand();
if (group.Groups.Count > 0)
{
for (int i = 0; i < group.Groups.Count; i++)
{
this.Expand(group.Groups[i]);
}
}
}
catch (Exception ex)
{
SM.Debug("EXLive5:" + ex.ToString());
}
}
public void RefreshUnitTimerExpired()
{
Utils.WriteLine("RefreshUnitTimerExpired", ConsoleColor.Yellow);
// go thourgh eatch unit from the grid
for (int contor = 0; contor < gridVehicles.Rows.Count; contor++)
{
// get current vehicle which is updated
Vehicle vehicleTemp = (Vehicle)MainForm2.vehicleHT[(String)gridVehicles.Rows[contor].Cells["UnitName"].Value];
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[contor].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
// check if the position had changed the ago time which needs to be displayed
if (!Utils.GetDateTimeAgo(gridData.PositionTime.AddSeconds(-30)).Equals(Utils.GetDateTimeAgo(gridData.PositionTime)))
{
//Utils.WriteLine("REFRESH TIMER : CHANGE TIME", ConsoleColor.Cyan);
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
// refresh the grid only if the group is POSITION TIME
if (groupType == GroupType.POSITIONTIMEAGO)
gridVehicles_SetGrouping(groupType, false);
}
// if the position didn't change, I can test if the status has changed
else if (gridData.PreviousStatus != null && gridData.PreviousStatus != gridData.Status)
{
//Utils.WriteLine("REFRESH TIMER : CHANGE STATE" + " [" + gridData.PreviousStatus + " -> " + gridData.Status + "]", ConsoleColor.Cyan);
// update the status of the unit
gridData.UnitStatus = Utils.GetStatusFromDisplayString(gridData.Status);
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
// refresh the grid only if the group is STATUS
if (groupType == GroupType.STATUS)
gridVehicles_SetGrouping(groupType, false);
}
}
}
// refresh the grid if positions window is active
if (positionsWindowIsActive)
RefreshPositionsGrid();
}
/// <summary>
/// Refresh the grid only for one unit used when a position is received or when a unit
/// changes it's state
/// </summary>
/// <param name="unitName">Unit name which needs to be updated</param>
public void onUnitPositionOrStateChanged(String unitName)
{
//populateTableVehiclesList2(true, unitName);
UpdateDataGridUnit(unitName, false);
// refresh the grid if positions window is active
if (positionsWindowIsActive)
RefreshPositionsGrid(unitName);
}
public void OnUnitStolenChanged(String unitName, Boolean isStolen)
{
UpdateDataGridUnit(unitName, true);
}
private void UpdateDataGridUnit(String unitName, Boolean shouldUpdateGrid)
{
// find the subscriber in the datasource
DataforVehList result = ListforVehList.Find(d => d.UnitName.Equals(unitName));
// get current vehicle which is updated
Vehicle vehicleTemp = (Vehicle)MainForm2.vehicleHT[unitName];
// update the favorite if found
if (result != null)
{
lock (thisLock)
{
if(shouldUpdateGrid)
gridVehicles.BeginUpdate();
else
gridVehicles.BeginEdit();
// save previous values
int prevSpeed = result.Speed;
string prevStatus = result.PreviousStatus;
string prevTimeAgo = result.PositionTimeAgo;
// remove null values to empty ones
if (prevStatus == null)
prevStatus = "";
if (prevTimeAgo == null)
prevTimeAgo = "";
// update all the new fields and values
result.Address = vehicleTemp.lastAddress;
result.PositionTime = vehicleTemp.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(); // lastValidPositionTime));
result.Latitude = vehicleTemp.LAT;
result.Longitude = vehicleTemp.LNG;
result.Speed = vehicleTemp.GetSpeed();
result.UnitStatus = vehicleTemp.actual_status;
result.Status = Vehicle.GetString_Status(vehicleTemp.actual_status);
result.IsEmergency = vehicleTemp.is_emergency;
result.Stolen = vehicleTemp.is_stolen;
// check to see if the status has changed
if (!prevStatus.Equals(result.Status) || prevSpeed != result.Speed)
{
//Utils.WriteLine("REFRESH GROUPS BY STATUS " + " [" + prevStatus + " -> " + gridData.Status + "]", ConsoleColor.Yellow);
// notify that an update must be made
result.NrOfUpdates = result.NrOfUpdates + 1;
}
// check if the position had changed the ago time which needs to be displayed
if (!prevTimeAgo.Equals(Utils.GetDateTimeAgo(result.PositionTime)))
{
//Utils.WriteLine("REFRESH GROUPS BY TIME", ConsoleColor.Yellow);
// notify that an update must be made
result.NrOfUpdates = result.NrOfUpdates + 1;
}
if (shouldUpdateGrid)
gridVehicles.EndUpdate();
else
gridVehicles.EndEdit();
// check to see if the status has changed
if (!prevStatus.Equals(result.Status))
{
// refresh the grid only if the group is STATUS
if (groupType == GroupType.STATUS)
{
gridVehicles.BeginUpdate();
gridVehicles_SetGrouping(groupType, false);
gridVehicles.EndUpdate();
}
}
// check if the position had changed the ago time which needs to be displayed
if (!prevTimeAgo.Equals(Utils.GetDateTimeAgo(result.PositionTime)))
{
// refresh the grid only if the group is POSITION TIME
if (groupType == GroupType.POSITIONTIMEAGO)
{
gridVehicles.BeginUpdate();
gridVehicles_SetGrouping(groupType, false);
gridVehicles.EndUpdate();
}
}
}
}
}
/// <summary>
/// Event handler for when a unit changed it status to emergency of back to normal
/// </summary>
/// <param name="veh">Vehicle which changed it's status </param>
/// <param name="isEmergency">Flag telling if the unit is in emergency or not</param>
public void onEmergencyStateChangedHandler(Vehicle veh, bool isEmergency)
{
// update status for unit
veh.actual_status = isEmergency ? Status_for_tab.EMERG : Status_for_tab.MADEON;
veh.is_emergency = isEmergency;
if (isEmergency)
{
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Where(d => d.RadioId == veh.IMEI);
foreach (DataforVehList ve in result)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).ActivatePushPin();
VisualSettings.SetDisplayedInLiveTab(ve.SipId, true, tabName);
}
// check and create emergency icon
IconHelper.CheckCreateEmergencyIcon(veh.IconID);
}
// send emergency status update to the map
mapHandler.EmergencyStateUpdate(veh);
if (isEmergency)
{
// put vehicles on map
mapHandler.AddVehicles(new List<Vehicle> { veh }, false);
Thread.Sleep(100);
// center map and open info bubble
mapHandler.CenterMapToPosition(new LatLngZoom() { Lat = veh.GetLat(), Lng = veh.GetLng(), ZoomLevel = -1 });
mapHandler.OpenInfoBubble(veh.busName);
// update the header name
onGroupDisplayedUnitsChangedHandler(veh.group.Name);
}
}
/// <summary>
/// Handler for when a poll response is received from a field radio
/// </summary>
/// <param name="veh">Vehicle which responded to the poll request</param>
public void onPollResponseReceivedHandler(Vehicle veh)
{
// put vehicles on map
mapHandler.AddVehicles(new List<Vehicle> { veh }, false);
Thread.Sleep(100);
// center map and open info bubble
mapHandler.CenterMapToPosition(new LatLngZoom() { Lat = veh.GetLat(), Lng = veh.GetLng(), ZoomLevel = -1 });
mapHandler.OpenInfoBubble(veh.busName);
}
public void CenterAndOpenBubble(String unitName)
{
//ListforGrid.Clear();
for (int contor = 0; contor < gridVehicles.Rows.Count; contor++)
{
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[contor].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
// skip this unit if it doesn't need to be updated
if (!gridData.UnitName.Equals(unitName))
;
else
{
// display the car on the map and then notify the change
if (docLoad && !gridData.OnMap)
{
gridData.OnMap = true;
gridData.NrOfUpdates += 1;
rbDisplay.PerformClick();
}
// open info buble
if (docLoad && gridData.OnMap)
{
if ((gridData.Latitude != 0 && gridData.Latitude != 0.1) ||
(gridData.Longitude != 0 && gridData.Longitude != 0.1))
{
SM.Debug("Send open info");
mapGoogles.ExecuteScript("window.GWTcallback('centerzoom," + MainForm2.FixDoubleLAT(gridData.Latitude + "") + ","
+ MainForm2.FixDoubleLNG(gridData.Longitude + "") + ",-1');");
Thread.Sleep(351);
mapGoogles.ExecuteScript("window.GWTcallback('" + "openInfo," + gridData.UnitName + "');");
Thread.Sleep(50);
mapHandler.CenterMapToPosition(new LatLngZoom() { Lat = gridData.Latitude, Lng = gridData.Longitude, ZoomLevel = -1 });
mapHandler.OpenInfoBubble(gridData.UnitName);
}
else
{
parent.DisplayToast(MainForm2.returnLNGString("noGPS"), MainForm2.returnLNGString("HTMLnoGPS"));
}
}
}
}
}
}
volatile List<DataforGRID> ListforGrid = new List<DataforGRID>();
/// <summary>
/// Update Position Grid for that particular unit
/// </summary>
/// <param name="unitName">Unit name that needs to be updated</param>
private void onPositionListUnitChanged(String unitName)
{
tableVehiclesList.BeginEdit();
DataforGRID gridUnit = ListforGrid.Find(d => d.VehName.Equals(unitName));
// get current vehicle which is updated
Vehicle vehicleTemp = (Vehicle)MainForm2.vehicleHT[unitName];
if (gridUnit != null && vehicleTemp != null)
{
gridUnit.Lat = vehicleTemp.GetLat() + "";
gridUnit.Lng = vehicleTemp.GetLng() + "";
gridUnit.Address = vehicleTemp.GetLastAddress();
gridUnit.Datatime = vehicleTemp.lastValidPositionTime.ConvertGMTToLocal().GetDTFromSeconds();
gridUnit.Speed = Convert.ToString(vehicleTemp.GetSpeed());
gridUnit.Head = Utils.GetDirection(vehicleTemp.GetHeading()).ToString();
gridUnit.DI = Convert.ToString(vehicleTemp.GetDI());
gridUnit.DO = Convert.ToString(vehicleTemp.GetDO());;
}
tableVehiclesList.EndEdit();
}
public void populateTableVehiclesList2(Boolean Refresh, String unitName)
{
Int32 oldColomnSort = 0;
RadSortOrder oldSortType = RadSortOrder.Ascending;
try
{
Vehicle vehicleTemp;
if (Refresh)
{
//ListforGrid.Clear(); //aici e combinatia fatala
try
{
for (int i = 0; i < tableVehiclesList.Columns.Count; i++)
{
if (tableVehiclesList.Columns[i].SortOrder != RadSortOrder.None)
{
oldColomnSort = i;
oldSortType = tableVehiclesList.Columns[i].SortOrder;
break;
}
}
}
catch (Exception ex)
{
SM.Debug("Error on finding the sort column:" + ex.ToString());
}
tableVehiclesList.Columns["VehName"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["datetime"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["address"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["speed"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["head"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["di"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["do"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["lat"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["lng"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["zone"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["Altitude"].SortOrder = RadSortOrder.None;
Thread.Sleep(100);
}
int countlist = -1;
String LatStr = "";
String LngStr = "";
String AltStr = "";
String Zone;
Double LatDou, LngDou;
if (MainForm2.LatLngUTM.CompareTo("Lat/Lng No.") == 0)
{
tableVehiclesList.Columns["lat"].HeaderText = latname;
tableVehiclesList.Columns["lng"].HeaderText = lngname;
tableVehiclesList.Columns["zone"].HeaderText = "";
tableVehiclesList.Columns["Altitude"].HeaderText = altname;
}
else if (MainForm2.LatLngUTM.CompareTo("Lat/Lng Deg.") == 0)
{
tableVehiclesList.Columns["lat"].HeaderText = latname;
tableVehiclesList.Columns["lng"].HeaderText = lngname;
tableVehiclesList.Columns["zone"].HeaderText = "";
tableVehiclesList.Columns["Altitude"].HeaderText = altname;
}
else if (MainForm2.LatLngUTM.CompareTo("UTM") == 0)
{
tableVehiclesList.Columns["lat"].HeaderText = "X";
tableVehiclesList.Columns["lng"].HeaderText = "Y";
tableVehiclesList.Columns["zone"].HeaderText = zonename;
tableVehiclesList.Columns["Altitude"].HeaderText = altname;
}
// refresh the grid if positions window is active
if (positionsWindowIsActive)
RefreshPositionsGrid();
// flag that an update will be made
//gridVehicles.TableElement.BeginUpdate();
//ListforGrid.Clear();
for (int contor = 0; contor < gridVehicles.Rows.Count; contor++)
{
string un = (String)gridVehicles.Rows[contor].Cells["UnitName"].Value;
if (un == null)
continue;
// get current vehicle which is updated
vehicleTemp = (Vehicle)MainForm2.vehicleHT[un];
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[contor].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
// skip this unit if it doesn't need to be updated
if (unitName != null && !gridData.UnitName.Equals(unitName))
;
else
{
// save previous values
string prevStatus = gridData.PreviousStatus;
string prevTimeAgo = gridData.PositionTimeAgo;
// remove null values to empty ones
if (prevStatus == null)
prevStatus = "";
if (prevTimeAgo == null)
prevTimeAgo = "";
// update all the new fields and values
gridData.Address = vehicleTemp.lastAddress;
gridData.PositionTime = vehicleTemp.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(); // lastValidPositionTime));
gridData.Latitude = vehicleTemp.LAT;
gridData.Longitude = vehicleTemp.LNG;
gridData.Speed = vehicleTemp.GetSpeed();
gridData.UnitStatus = vehicleTemp.actual_status;
gridData.Status = Vehicle.GetString_Status(vehicleTemp.actual_status);
gridData.IsEmergency = vehicleTemp.is_emergency;
// check to see if the status has changed
if (!prevStatus.Equals(gridData.Status))
{
//Utils.WriteLine("REFRESH GROUPS BY STATUS " + " [" + prevStatus + " -> " + gridData.Status + "]", ConsoleColor.Yellow);
// refresh the grid only if the group is STATUS
if (groupType == GroupType.STATUS)
gridVehicles_SetGrouping(groupType, false);
}
// check if the position had changed the ago time which needs to be displayed
if (!prevTimeAgo.Equals(Utils.GetDateTimeAgo(gridData.PositionTime)))
{
//Utils.WriteLine("REFRESH GROUPS BY TIME", ConsoleColor.Yellow);
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
// refresh the grid only if the group is POSITION TIME
if (groupType == GroupType.POSITIONTIMEAGO)
gridVehicles_SetGrouping(groupType, false);
}
}
}
// if the update was as a result of a position received
if (unitName != null && gridData.UnitName.Equals(unitName))
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
}
}
catch (Exception ex)
{
SM.Debug("EXLive6:" + ex.ToString());
}
}
volatile String volLatStr = "";
volatile String volLngStr = "";
volatile String volAltStr = "";
volatile String volZone = "";
public Double volLatDou, volLngDou;
volatile LatLngUTM voltmpLatLng = new LatLngUTM();
/// <summary>
///Deletes all used resources
///</summary>
public void Delete()
{
try
{
timerAddPlace.Stop();
timerAddPlace.Enabled = false;
try
{
parent.isCanceled[tabName] = false;
vehiclesDataSet.Delete();
this.mapControl.ActiveMap.Saved = true;
if (this.app != null)
{
app.Quit();
app = null;
}
Thread.Sleep(100);
Killtimer.Enabled = true;
Killtimer.Start();
this.mapControl.ActiveMap.Saved = true;
Killtimer.Stop();
this.mapControl = null;
this.Dispose();
GC.Collect();
}
catch (Exception ex)
{
SM.Debug("Exception on close map LIVETab " + ex.ToString());
}
if ((MainForm2.ClosingApp) || (!KillTimerActive))
{
SM.Debug("Worker Live " + tabName + " FINISHED");
SM.Debug("RELEASE SEMAFOR TAB LIVE: " + tabName);
}
}
catch (Exception ex)
{
SM.Debug("Error on delete live :" + ex.ToString());
}
}
/// <summary>
///treats the click on Display Telerik.WinControls.UI.RadButton - centers map on selected vehicles </summary>
private void displayButton_Click(object sender, EventArgs e)
{
rbDisplay.Enabled = false;
try
{
centeredState = false;
// need to find what this is doing
ComputeCheckedVehicles(true);
// save how many units are selected
////if (nrofunitsChecked == 1)
//// MainForm2.onlyOneUnitSelected = true;
////else
//// MainForm2.onlyOneUnitSelected = false;
if (vehiclesDataSet.RecordCount > 0)
{
vehiclesDataSet.zoomin = true;
vehiclesDataSet.ZoomTo();
MapMarkersLables(MainForm2.HashVal.ContainsKey("showMarkersLables") && Convert.ToBoolean(MainForm2.HashVal["showMarkersLables"]));
}
bool areAllGroupsChecked = true;
foreach (GridViewRowInfo groupRow in gridVehicles.ChildRows)
{
// the group has items
if (groupRow.ChildRows.Count > 0)
{
// group name is groupRow.Group.Header
bool areAllChecked = true;
foreach (GridViewRowInfo gridRow in groupRow.ChildRows)
{
// get the Data bound item for each grid row
DataforVehList gridData = gridRow.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
if (!gridData.OnMap)
{
areAllChecked = false;
areAllGroupsChecked = false;
}
}
}
if (groupRow != null && areAllChecked)
groupRow.Tag = true;
else
groupRow.Tag = false;
}
}
}
catch (Exception ex)
{
SM.Debug("Error on display Telerik.WinControls.UI.RadButton click" + ex.ToString());
}
rbDisplay.Enabled = true;
}
private void MapMarkersLables(bool isDisplayed)
{
MainForm2.Displaywithname = isDisplayed;
if (docLoad)
vehiclesDataSet.ZoomTo();
if (isDisplayed)
{
if (docLoad)
{
System.Threading.Thread.Sleep(100);
mapGoogles.ExecuteScript("window.GWTcallback('" + "putLabels," + vehiclesDataSet.Name + "');");
}
Thread.Sleep(1);
HideALLName = true;
}
else
{
if (HideALLName)
{
HideALLName = false;
if (docLoad)
{
System.Threading.Thread.Sleep(100);
mapGoogles.ExecuteScript("window.GWTcallback('" + "removeLabels," + vehiclesDataSet.Name + "');");
}
Thread.Sleep(1);
}
}
}
private volatile Int32 nrofunitsChecked = 0;
/// <summary>
///only displays on the map the selected vehicles </summary>
public void ComputeCheckedVehicles(bool displayButtonCase)
{
try
{
nrofunitsChecked = 0;
Int32 timenowsec = (int)DateTime.Now.GetSecondsLocalFromDT();
if (displayButtonCase)
{
//for (cont = 0; cont < vehiclesList.Rows.Count; cont++)
foreach (DataforVehList obj2 in (List<DataforVehList>)gridVehicles.DataSource)
{
VisualSettings.SetDisplayedInLiveTab(obj2.SipId, obj2.OnMap, tabName);
if ((bool)obj2.OnMap)
{
try
{
if (!((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).itemCheck)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).itemCheck = true;
if ((parent.NoteAddr[obj2.UnitName] == null))
parent.NoteAddr.Add(obj2.UnitName, "none");
else
parent.NoteAddr[obj2.UnitName] = "none";
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).ActivatePushPin();
}
nrofunitsChecked++;
if (MainForm2.HideInactiveUnitsCheck)
if (((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).lastActivityTime < (timenowsec - (MainForm2.Livelastmin * 60)))
{
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).DeactivatePushpin();
nrofunitsChecked--;
}
}
catch (Exception ex)
{
SM.Debug("Error in compute display not click: " + ex.ToString());
}
}
else
{
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).itemCheck = false;
if (((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).pp != null)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).pp.Highlight = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).DeactivatePushpin();
if (((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).selectCenter)
{
((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).selectCenter = false;
centeredState = false;
}
}
}
if (((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).pp != null)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).MapsHT[tabName]).pp.Highlight = false;
((Vehicle)MainForm2.vehicleHT[obj2.UnitName]).selectCenter = false;
}
}
}
else
{
if (deleteDsetcomand.IndexOf(',') != deleteDsetcomand.LastIndexOf(','))
{
if (docLoad)
{
mapControl.mapGoogles.ExecuteScript("window.GWTcallback('" + "clearFromMap,vehicles_positions');");
Thread.Sleep(1);
ComputeCheckedVehicles(true);
if (vehiclesDataSet.RecordCount > 0)
{
if (vehiclesDataSet.RecordCount == 1) vehiclesDataSet.zoomin = true;
else vehiclesDataSet.zoomin = false;
vehiclesDataSet.ZoomTo();
if (MainForm2.Displaywithname)
{
if (docLoad)
{
System.Threading.Thread.Sleep(100);
mapGoogles.ExecuteScript("window.GWTcallback('" + "putLabels," + vehiclesDataSet.Name + "');");
}
Thread.Sleep(1);
HideALLName = true;
}
else
{
if (HideALLName)
{
HideALLName = false;
if (docLoad)
{
mapGoogles.ExecuteScript("window.GWTcallback('" + "removeLabels," + vehiclesDataSet.Name + "');");
}
Thread.Sleep(1);
}
}
}
}
deleteDsetcomand = "";
}
if (updatecomand.IndexOf(',') != updatecomand.LastIndexOf(','))
{
if (docLoad)
{
mapControl.mapGoogles.ExecuteScript("window.GWTcallback('" + updatecomand + "');");
}
// Console.WriteLine("Update cmd:" + updatecomand);
Thread.Sleep(1);
String[] tmp = updatecomand.Split(',');
if (docLoad)
{
//SM.Debug("Oneunit"+MainForm2.oneunit);
//if (MainForm2.onlyOneUnitSelected)
// mapControl.mapGoogles.ExecuteScript("window.GWTcallback('" + "putOnMap,false," + tmp[1] + "');");
//else
mapControl.mapGoogles.ExecuteScript("window.GWTcallback('" + "putOnMap,false," + tmp[1] + "');");
}
Thread.Sleep(1);
//SM.Debug("Value of displayname:" + MainForm2.Displaywithname);
if (((MainForm2.Displaywithname) && (updatecomand.Contains("setDataset,"))) || (MainForm2.ForcePutLabelsONGoogle))
{
String[] datas = updatecomand.Split(',');
if (datas.Length > 1)
{
//System.Threading.Thread.Sleep(100);
//mapGoogles.ExecuteScript("window.GWTcallback('" + "putLabels," + datas[1] + "');");
}
Thread.Sleep(1);
if (MainForm2.ForcePutLabelsONGoogle) MainForm2.ForcePutLabelsONGoogle = false;
}
updatecomand = "";
//Console.WriteLine("Second cmd:" + "putOnMap,false," + tmp[1]);
}
if (getADDRcomand != "")
{
if (docLoad)
mapControl.mapGoogles.ExecuteScript("window.GWTcallback('" + getADDRcomand + "');");
Thread.Sleep(1);
}
}
}
catch (Exception x)
{
SM.Debug("Erorr compute checked vehicle " + x.ToString());
}
}
public void ForceUnitState(String Name, Boolean check)
{
//gridVehicles.TableElement.BeginUpdate();
foreach (DataforVehList obj2 in (List<DataforVehList>)gridVehicles.DataSource)
{
if (obj2.UnitName.CompareTo(Name) == 0)
{
obj2.OnMap = check;
if (obj2.UnitName.CompareTo("test960") == 0)
Console.WriteLine("Value1 for ONMAP:" + obj2.OnMap);
break;
}
}
// gridVehicles.TableElement.EndUpdate(false);
//gridVehicles.TableElement.Update(GridUINotifyAction.DataChanged);
//gridVehicles.Refresh();
}
/// <summary>
/// Filter the vehicles grid based on a string patter
/// </summary>
/// <param name="vehicleName">Filter for vehicle name</param>
private void FilterGridVehicles(string vehicleName)
{
try
{
for (int i = 0; i < gridVehicles.Rows.Count; i++)
{
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[i].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null && gridData.UnitName.ToUpper().Contains(vehicleName.ToUpper()))
gridVehicles.Rows[i].IsVisible = true;
else
gridVehicles.Rows[i].IsVisible = false;
}
}
catch (Exception ex)
{
SM.Debug("ExLive8:" + ex.ToString());
}
}
/// <summary>
/// Catches the event when
/// the user inputs/deletes a character in/from the search box,
/// and the vehicles list is refreshed accordingly </summary>
/// </summary>
private void searchTextBox_TextChanged(object sender, EventArgs e)
{
FilterGridVehicles(searchTextBox.Text);
}
/// <summary>
/// timer for refresing status in vehicle list
/// </summary>
/// <param name="sender"></param>
private void Killtimer_Tick(object sender, EventArgs e)
{
try
{
if (MainForm2.ClosingApp)
{
SM.Debug("Worker Live: " + tabName + " FINISHED from timer");
SM.Debug("RELEASE SEMAFOR TAB LIVE: " + tabName);
KillTimerActive = true;
}
}
catch (Exception ex)
{
SM.Debug("EXLive9:" + ex.ToString());
}
}
private void sendPOLLToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
smdbObj.Send_cmd_to_val(false, ((Vehicle)MainForm2.vehicleHT[(String)gridVehicles.SelectedRows[0].Cells[2].Value]).IMEI, "");
}
catch (Exception ex)
{
SM.Debug("Cann't send POLL cmd" + ex.ToString());
}
}
private Object thisLock = new Object();
[ChangesAtrribute("4 Nov 2016", "Removed unnecessary if/else clause")]
private void sel_desel_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
lock (thisLock)
{
gridVehicles.BeginUpdate();
try
{
for (int i = 0; i < gridVehicles.Groups.Count; i++)
{
//GridViewRowInfo groupHeaderRow = gridVehicles.Groups[i].GroupRow;
GroupCheckBox_StateChanged(sender, new GRPEventArgs(i, sel_desel.Checked));
//gridVehicles.Groups[i].GroupRow.ViewInfo.ChildRows
DataGroup dg = (gridVehicles.Groups[i]) as DataGroup;
//dg.GroupRow.
}
for (int i = 0; i < gridVehicles.Groups.Count; i++)
CheckedGroup[i] = sel_desel.Checked;
foreach (GridViewRowInfo row in this.gridVehicles.ChildRows)
{
GridViewGroupRowInfo groupRow = row as GridViewGroupRowInfo;
if (groupRow != null)
groupRow.Tag = sel_desel.Checked;
}
}
catch (Exception ex)
{
Utils.WriteLine("gridVehicles exception: " + ex.ToString(), ConsoleColor.DarkRed);
}
gridVehicles.EndUpdate();
}
}
public volatile Int32 maxloadcnt = 1;
private void vehiclesList_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
{
try
{
if (e.ContextMenuProvider is GridHeaderCellElement)
{
// e.ContextMenu = columnHeaderMenu;
}
else if (e.ContextMenuProvider is GridDataCellElement || e.ContextMenuProvider is LiveGridCellElement)
{
GridViewRowInfo row =
(e.ContextMenuProvider is LiveGridCellElement ?
((LiveGridCellElement)e.ContextMenuProvider).RowInfo as GridViewDataRowInfo :
((GridDataCellElement)e.ContextMenuProvider).RowInfo);
RadDropDownMenu TelemMenu = new RadDropDownMenu();
if ((!MainForm2.LimitedUser) && (MainForm2.radioType != RADIOTYPE.ATLAS) && (MainForm2.radioType != RADIOTYPE.TETRA) && (MainForm2.radioType != RADIOTYPE.CONECTPLUS)
&& (MainForm2.radioType != RADIOTYPE.SIMOCO) && (MainForm2.radioType != RADIOTYPE.EXCERA))
{
if (!((Vehicle)MainForm2.vehicleHT[(String)row.Cells["UnitName"].Value]).canMakeSipCalls)
{
RadMenuItem tmpItem2 = new RadMenuItem(MainForm2.returnLNGString("enRadio"));
tmpItem2.Image = Dispatcher.Properties.Resources.l_menu_enable;
tmpItem2.Click += new EventHandler(SendRadioEnable_Click);
TelemMenu.Items.Add(tmpItem2);
RadMenuItem tmpItem3 = new RadMenuItem(MainForm2.returnLNGString("disRadio"));
tmpItem3.Image = Dispatcher.Properties.Resources.l_menu_disable;
tmpItem3.Click += new EventHandler(SendRadioDisable_Click);
TelemMenu.Items.Add(tmpItem3);
}
}
if (docLoad)
{
if ((MainForm2.radioType != RADIOTYPE.EXCERA))
{
RadMenuItem tmpItem4 = new RadMenuItem(MainForm2.returnLNGString("poll"));
tmpItem4.Image = Dispatcher.Properties.Resources.l_menu_poll;
tmpItem4.Click += new EventHandler(SendPOLL_Click);
TelemMenu.Items.Add(tmpItem4);
}
}
if ((MainForm2.radioType == RADIOTYPE.HYT) || (MainForm2.radioType == RADIOTYPE.HARRIS) ||
(MainForm2.radioType == RADIOTYPE.SIMOCO) || (MainForm2.radioType == RADIOTYPE.EXCERA))
{
RadMenuItem tmpItem6 = new RadMenuItem(MainForm2.returnLNGString("radcheck"));
tmpItem6.Click += new EventHandler(SendPOLLARS_Click);
TelemMenu.Items.Add(tmpItem6);
}
RadMenuItem tmpItem5 = null;
//markasstolen
if ((!MainForm2.LimitedUser) && (MainForm2.radioType != RADIOTYPE.ATLAS) && (MainForm2.radioType != RADIOTYPE.TETRA)
&& (MainForm2.radioType != RADIOTYPE.CONECTPLUS)
&& (MainForm2.radioType != RADIOTYPE.SIMOCO) && (MainForm2.radioType != RADIOTYPE.EXCERA))
{
if (!((Vehicle)MainForm2.vehicleHT[(String)row.Cells["UnitName"].Value]).is_stolen)
{
tmpItem5 = new RadMenuItem(MainForm2.returnLNGString("markasstolen"));
tmpItem5.Image = Dispatcher.Properties.Resources.l_menu_stolen;
tmpItem5.Click += new EventHandler(SendStolen_Click);
TelemMenu.Items.Add(tmpItem5);
}
else
{
tmpItem5 = new RadMenuItem(MainForm2.returnLNGString("unmarkasstolen"));
tmpItem5.Image = Dispatcher.Properties.Resources.l_menu_unstolen;
tmpItem5.Click += new EventHandler(SendUNStolen_Click);
TelemMenu.Items.Add(tmpItem5);
}
}
RadMenuItem tmpItem7 = null;
int sc_id = (((Vehicle)MainForm2.vehicleHT[(String)row.Cells["UnitName"].Value])).sc_id;
Int64 alarmsCounter = dbalm.GetNumberOfNonAckAllarmsForRadioId(sc_id);
if (alarmsCounter > 0)
{
tmpItem7 = new RadMenuItem(MainForm2.returnLNGString("alarmALLACK"));
tmpItem7.Click += new EventHandler(AckAlarmForUnit_Click);
TelemMenu.Items.Add(tmpItem7);
}
TelemMenu.Items.Add(new RadMenuSeparatorItem() { BackColor = MainForm2.ButtonColor, Padding = new Padding(0, 8, 0, 0) });
string unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
string groupName = (((Vehicle)MainForm2.vehicleHT[unitName])).group.Name;
RadMenuItem tmpItemDisplay = new RadMenuItem(String.Format(MainForm2.returnLNGString("displayGroup"), groupName));
tmpItemDisplay.Tag = groupName;
tmpItemDisplay.Image = Dispatcher.Properties.Resources.l_menu_display;
tmpItemDisplay.Click += new EventHandler(delegate(object s, EventArgs e2)
{
String group_name = ((RadMenuItem)s).Tag.ToString();
ShowGroup(group_name);
});
TelemMenu.Items.Add(tmpItemDisplay);
RadMenuItem tmpItemHide = new RadMenuItem(String.Format(MainForm2.returnLNGString("hideGroup"), groupName));
tmpItemHide.Tag = groupName;
tmpItemHide.Image = Dispatcher.Properties.Resources.l_menu_hide;
tmpItemHide.Click += new EventHandler(delegate (object s, EventArgs e2)
{
String group_name = ((RadMenuItem)s).Tag.ToString();
HideGroup(group_name, false);
});
TelemMenu.Items.Add(tmpItemHide);
if (MainForm2.GroupHash.Count > 0)
{
TelemMenu.Items.Add(new RadMenuSeparatorItem() { BackColor = MainForm2.ButtonColor, Padding = new Padding(0, 8, 0, 0) });
RadMenuItem tmpShowAll = new RadMenuItem(String.Format(MainForm2.returnLNGString("displayAllUnits"), groupName));
tmpShowAll.Image = Dispatcher.Properties.Resources.l_menu_display_all;
tmpShowAll.Click += new EventHandler(delegate (object s, EventArgs e2)
{
DisplayAllUnits();
});
TelemMenu.Items.Add(tmpShowAll);
RadMenuItem tmpHideAll = new RadMenuItem(String.Format(MainForm2.returnLNGString("hideAllUnits"), groupName));
tmpHideAll.Tag = groupName;
tmpHideAll.Image = Dispatcher.Properties.Resources.l_menu_hide_all;
tmpHideAll.Click += new EventHandler(delegate (object s, EventArgs e2)
{
HideAllUnits();
});
TelemMenu.Items.Add(tmpHideAll);
}
e.ContextMenu = TelemMenu;
}
}
catch (Exception ex)
{
SM.Debug("EXLive10:" + ex.ToString());
}
}
private void DisplayAllUnits()
{
List<Vehicle> htList = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
IEnumerable<IGrouping<int, Vehicle>> query = htList.GroupBy(d => d.group.Id, d => d);
List<Vehicle> toDisplayVehicles = htList.Select(d => d).Where(d => !((MapElement)d.MapsHT[tabName]).itemCheck)
.Where(d => VisualSettings.IsGroupDisplayedInLiveTab(d.group.Name, tabName) == null ||
VisualSettings.IsGroupDisplayedInLiveTab(d.group.Name, tabName) == true).ToList();
if (rseUnitsOnMap.Value < getNumberOfDisplayedUsers() + toDisplayVehicles.Count)
{
if (getMaxUnitsWarningDialogResult(toDisplayVehicles.Count, getNumberOfDisplayedUsers() + toDisplayVehicles.Count, (Int64)rseUnitsOnMap.Value) != DialogResult.Yes)
{
return;
}
else
rseUnitsOnMap.Value = getNumberOfDisplayedUsers() + toDisplayVehicles.Count;
}
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
{
String group_name = group.FirstOrDefault(d => d.sipID > 0).group.Name;
// skip groups that are not displayed in the grid
bool? isGroupDisplayed = VisualSettings.IsGroupDisplayedInLiveTab(group_name, tabName);
if (isGroupDisplayed == false)
continue;
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(group_name)).ToList();
List<Vehicle> toDisplayVehiclesFromGroup = vehicles.Select(d => d).Where(d => !((MapElement)d.MapsHT[tabName]).itemCheck).ToList();
if (toDisplayVehiclesFromGroup.Count > 0)
{
// prevent updates in the livegrid to raise event
parseLiveGridEvents = false;
mapHandler.AddVehicles(toDisplayVehiclesFromGroup, false);
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Select(d => d).Where(d => (toDisplayVehiclesFromGroup.Select(w => w.IMEI)).Contains(d.RadioId));
foreach (DataforVehList ve in result)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).ActivatePushPin();
VisualSettings.SetDisplayedInLiveTab(ve.SipId, true, tabName);
}
if (groupsHeadersByString.ContainsKey(group_name))
groupsHeadersByString[group_name].checkbox.Checked = true;
// enable the event raising
parseLiveGridEvents = true;
}
// update the group header
onGroupDisplayedUnitsChangedHandler(group_name);
}
}
private void HideAllUnits()
{
// prevent updates in the livegrid to raise event
parseLiveGridEvents = false;
List<Vehicle> htList = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
IEnumerable<IGrouping<int, Vehicle>> query = htList.GroupBy(d => d.group.Id, d => d);
List<String> groupNames = new List<string>();
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
{
String group_name = group.FirstOrDefault(d => d.sipID > 0).group.Name;
bool? isGroupDisplayed = VisualSettings.IsGroupDisplayedInLiveTab(group_name, tabName);
// skip groups that are not displayed
if (isGroupDisplayed != null && isGroupDisplayed == false)
continue;
// skip groups that are not having any unit displayed
int displayedUnitsCount = ListforVehList.Select(d => d).Where(d => (htList.Select(w => w.IMEI)).Contains(d.RadioId))
.Where(d => d.OnMap && d.GrpName.Equals(group_name)).Count();
if (displayedUnitsCount == 0)
continue;
// add group name to the list
groupNames.Add(group_name);
// update the header name
onGroupDisplayedUnitsChangedHandler(group_name);
}
// update the live grid
foreach (DataforVehList ve in ListforVehList)
{
ve.OnMap = false;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).DeactivatePushpin();
VisualSettings.SetDisplayedInLiveTab(ve.SipId, false, tabName);
}
/*
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
{
String group_name = group.FirstOrDefault(d => d.sipID > 0).group.Name;
bool? isGroupDisplayed = VisualSettings.IsGroupDisplayedInLiveTab(group_name, tabName);
// skip groups that are not displayed
if (isGroupDisplayed != null && isGroupDisplayed == false)
continue;
// skip groups that are not having any unit displayed
IEnumerable<DataforVehList> result = gridVehicleList.Select(d => d).Where(d => (htList.Select(w => w.IMEI)).Contains(d.RadioId) && d.OnMap == true);
if (result.Count() == 0)
continue;
}*/
// enable the event raising
parseLiveGridEvents = true;
// remove all groups
mapHandler.RemoveGroups(groupNames);
}
private void ShowDisplayedUnitsFromGroup(String groupName)
{
ShowGroup(groupName, false);
}
private void ShowGroup(String groupName)
{
ShowGroup(groupName, true);
}
private void ShowGroup(String groupName, bool forceDisplayAll)
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(groupName)).ToList();
List<Vehicle> toDisplayVehicles = vehicles.Select(d => d).Where(d =>
forceDisplayAll ? !((MapElement)d.MapsHT[tabName]).itemCheck : VisualSettings.IsDisplayedInLiveTab(d.sipID, tabName)).ToList();
if (rseUnitsOnMap.Value < getNumberOfDisplayedUsers() + toDisplayVehicles.Count)
{
if (getMaxUnitsWarningDialogResult(toDisplayVehicles.Count, getNumberOfDisplayedUsers() + toDisplayVehicles.Count, (Int64)rseUnitsOnMap.Value) != DialogResult.Yes)
{
return;
}
else
rseUnitsOnMap.Value = getNumberOfDisplayedUsers() + toDisplayVehicles.Count;
}
if (toDisplayVehicles.Count > 0)
{
// prevent updates in the livegrid to raise event
parseLiveGridEvents = false;
mapHandler.AddVehicles(toDisplayVehicles, false);
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Select(d => d).Where(d => (toDisplayVehicles.Select(w => w.IMEI)).Contains(d.RadioId));
foreach (DataforVehList ve in result)
{
ve.OnMap = true;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).ActivatePushPin();
if (forceDisplayAll)
VisualSettings.SetDisplayedInLiveTab(ve.SipId, true, tabName); ;
}
if (groupsHeadersByString.ContainsKey(groupName))
groupsHeadersByString[groupName].checkbox.Checked = true;
// enable the event raising
parseLiveGridEvents = true;
}
// update the group header
onGroupDisplayedUnitsChangedHandler(groupName);
}
private void HideGroup(String groupName, bool isGroupHiddenFromGrid)
{
// prevent updates in the livegrid to raise event
parseLiveGridEvents = false;
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(groupName)).ToList();
// update the grid units on left map
IEnumerable<DataforVehList> result = ListforVehList.Select(d => d).Where(d => (vehicles.Select(w => w.IMEI)).Contains(d.RadioId));
foreach (DataforVehList ve in result)
{
ve.OnMap = false;
ve.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).itemCheck = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[ve.UnitName]).MapsHT[tabName]).DeactivatePushpin();
// change the value only if the group wasn't hidden from the grid
if (!isGroupHiddenFromGrid)
VisualSettings.SetDisplayedInLiveTab(ve.SipId, false, tabName);
}
mapHandler.RemoveGroup(groupName);
if (groupsHeadersByString.ContainsKey(groupName))
groupsHeadersByString[groupName].checkbox.Checked = false;
// update the header name
onGroupDisplayedUnitsChangedHandler(groupName);
// enable the event raising
parseLiveGridEvents = true;
}
void SetTelem_Click(object sender, EventArgs e)
{
parent.Send_telem((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, ((RadMenuItem)((RadMenuItem)sender).HierarchyParent).Text, 0);
}
async void AckAlarmForUnit_Click(object sender, EventArgs e)
{
try
{
//AlarmTypes type = (((Vehicle)MainForm2.vehicleHT[(String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value])).EventLists.Contains;
//AlarmTypes type = AlarmTypes.emergency;
string unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
int sc_id = (((Vehicle)MainForm2.vehicleHT[(String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value])).sc_id;
//dbalm = new DBalarmManager(MainForm2.cfg.DB_IP, MainForm2.cfg.DB_schema, MainForm2.cfg.DB_user, MainForm2.cfg.DB_passwd, MainForm2.cfg.DB_port);
bool hasEmergencyActivated = dbalm.hasEmergencyActivated(sc_id);
// ack async the alarms
await Task.Factory.StartNew(() => dbalm.ACKALLalarms(sc_id, MainForm2.userIDX));
/*
Thread t = new Thread(() =>
dbalm.ACKALLalarms(sc_id, MainForm2.userIDX));
t.Start();
*/
if (hasEmergencyActivated)
{
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
String Totrans = "#153#" + ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (Int32)Status_for_tab.ON + "#";
parent.Send_UDP_cmd(Totrans, 0, 0);
Utils.WriteLine("Sending ALARM ACK to " + unitName);
//update GwandRadioID for current vehicle if is 0.0
((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
Totrans = "#238#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "."
+ ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#";
parent.Send_UDP_cmd(Totrans, 0, 0);
Thread.Sleep(100);
MainForm2.UpdateStatusLive(unitName);
}
String Totrans2 = "#238#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "."
+ ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (int)AlarmTypes.unknown;
parent.Send_UDP_cmd(Totrans2, 0, 0);
//NEED TO DO SAME STUFF FROM PUT EMERGENCY IN RED
foreach (String name in ((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT.Keys)
{
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT[name]).UpdateSymbol();
MainForm2.RemoveIconsFromMap();
((Vehicle)MainForm2.vehicleHT[unitName]).actual_status = Status_for_tab.ON;
onEmergencyStateChangedHandler((Vehicle)MainForm2.vehicleHT[unitName], false);
}
Thread.Sleep(100);
MainForm2.UpdateStatusLive(unitName);
}
catch (Exception ex)
{
SM.Debug("EX:" + ex.ToString());
}
try
{
this.parent.AlarmTracking_Click(null, null);
((Vehicle)MainForm2.vehicleHT[(String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value]).EventLists = new ArrayList();
}
catch (Exception ex)
{
SM.Debug("EX:" + ex.ToString());
}
}
void ClearTelem_Click(object sender, EventArgs e)
{
parent.Send_telem((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, ((RadMenuItem)((RadMenuItem)sender).HierarchyParent).Text, 1);
}
void TogTelem_Click(object sender, EventArgs e)
{
parent.Send_telem((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, ((RadMenuItem)((RadMenuItem)sender).HierarchyParent).Text, 2);
}
void PulsTelem_Click(object sender, EventArgs e)
{
parent.Send_telem((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, ((RadMenuItem)((RadMenuItem)sender).HierarchyParent).Text, 3);
}
void SendRadioEnable_Click(object sender, EventArgs e)
{
String unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
parent.Send_EnableOrDisable(unitName, CMDTYPE.EnableCMD);
parent.DisplayToast(unitName + MainForm2.returnLNGString("enableReq"),
string.Format(MainForm2.returnLNGString("enableReqHTML"), unitName));
}
void SendRadioDisable_Click(object sender, EventArgs e)
{
String unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
parent.Send_EnableOrDisable((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, CMDTYPE.DisableCMD);
parent.DisplayToast(unitName + MainForm2.returnLNGString("disableReq"),
string.Format(MainForm2.returnLNGString("disableReqHTML"), unitName));
}
void SendStolen_Click(object sender, EventArgs e)
{
String unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
parent.Send_EnableOrDisable((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, CMDTYPE.StolenONCMD);
parent.DisplayToast(unitName + MainForm2.returnLNGString("stolen"),
string.Format(MainForm2.returnLNGString("stolenHTML"), unitName));
DataforVehList veh = (gridVehicles.SelectedRows[0].DataBoundItem as DataforVehList);
if (veh != null)
{
gridVehicles.BeginEdit();
veh.Stolen = true;
veh.NrOfUpdates++;
gridVehicles.EndEdit();
}
}
void SendUNStolen_Click(object sender, EventArgs e)
{
String unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
parent.Send_EnableOrDisable((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, CMDTYPE.StolenOFFCMD);
parent.DisplayToast(unitName + MainForm2.returnLNGString("unstolen"),
string.Format(MainForm2.returnLNGString("unstolenHTML"), unitName));
DataforVehList veh = (gridVehicles.SelectedRows[0].DataBoundItem as DataforVehList);
if (veh != null)
{
gridVehicles.BeginEdit();
veh.Stolen = false;
veh.NrOfUpdates++;
gridVehicles.EndEdit();
}
parent.Send_EnableOrDisable(unitName, CMDTYPE.EnableCMD);
parent.DisplayToast(unitName + MainForm2.returnLNGString("enableReq"),
string.Format(MainForm2.returnLNGString("enableReqHTML"), unitName));
}
void SendPOLLARS_Click(object sender, EventArgs e)
{
String unitName = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
parent.Send_EnableOrDisable((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, CMDTYPE.POLLARSCMD);
if (((RadMenuItem)sender).AccessibleName != MainForm2.returnLNGString("radcheck"))
parent.DisplayToast(unitName + MainForm2.returnLNGString("pollReq"),
string.Format(MainForm2.returnLNGString("pollReqHTML"), unitName));
else
parent.DisplayToast(unitName + MainForm2.returnLNGString("radioOnlineCheckReq"),
string.Format(MainForm2.returnLNGString("radioOnlineCheckReqHTML"), unitName));
}
/// <summary>
/// Send the poll command on the message bus for the selected unit
/// and then display it on the map
/// </summary>
void SendPOLL_Click(object sender, EventArgs e)
{
try
{
// 2 -- POLL UNIT
parent.Send_EnableOrDisable((String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value, CMDTYPE.POLLGPSCMD);
MainForm2.POLLunit = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
if ((Math.Round(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LAT) != 0) && (Math.Round(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LNG) != 0))
{
if (((MapElement)(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).MapsHT[tabName])).isActive) ;
else
{
gridVehicles.SelectedRows[0].Cells["onMap"].Value = true;
rbDisplay.PerformClick();
}
}
Thread.Sleep(1);
}
catch (Exception ex)
{
SM.Debug("EXLive11:" + ex.ToString());
}
}
private System.Threading.Timer timerCheck = null;
private void vehiclesList_CellClick(object sender, GridViewCellEventArgs e)
{
if (e.Column != null && e.Column.Name.Equals("onMap"))// e.ColumnIndex == 3)
{
SM.Debug("Fire the timer");
if (timerCheck != null) timerCheck.Dispose();
timerCheck = new System.Threading.Timer(VerifyChecks, null, 2000, 2000);
}
}
//timer de verificat checkuri
private void VerifyChecks(object state)
{
try
{
this.Invoke(new CheckOnInvokeCallBack(CheckOnInvoke2));
}
catch (Exception ex)
{
SM.Debug("ExLive15:" + ex.ToString());
}
}
private void CheckOnInvoke2()
{
try
{
Boolean someCheck = false;
gridVehicles.TableElement.BeginUpdate();
gridVehicles.TableElement.EndUpdate(false);
gridVehicles.TableElement.Update(GridUINotifyAction.DataChanged);
gridVehicles.Refresh();
String selectedValue = "";
try
{
selectedValue = (String)gridVehicles.SelectedRows[0].Cells["UnitName"].Value;
}
catch
{
selectedValue = " ";
}
SM.Debug("Verify Check");
CheckedGroupTmp.Clear();
foreach (DataforVehList obj2 in (List<DataforVehList>)gridVehicles.DataSource)
{
if ((obj2.OnMap) && (obj2.UnitName.CompareTo(selectedValue) != 0))
{
someCheck = true;
if (CheckedGroupTmp[obj2.GrpName] == null) CheckedGroupTmp.Add(obj2.GrpName, true);
}
}
for (int i = 0; i < gridVehicles.Groups.Count; i++)
if ((Boolean)CheckedGroup[i])
{
if (CheckedGroupTmp[gridVehicles.Groups[i].Header] == null)
{
int j = -1;
foreach (GridViewRowInfo row in this.gridVehicles.ChildRows)
{
j++;
GridViewGroupRowInfo groupRow = row as GridViewGroupRowInfo;
if ((groupRow != null) && (j == i))
{
groupRow.Tag = false;
CheckedGroup[i] = false;
break;
}
}
}
}
if ((sel_desel.Checked) && (!someCheck))
{
SM.Debug("Select all false");
sel_desel.Checked = false;
}
if (timerCheck != null) timerCheck.Dispose();
}
catch (Exception ex)
{
SM.Debug("Error backtop play" + ex.ToString());
}
}
public delegate void CheckOnInvokeCallBack();
/// <summary>
/// Show or hide Landmarks on the map
/// </summary>
private void ckShowLand_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
Utils.WriteLine("ckShowLand_ToggleStateChanged " + (ckShowLand.Checked ? "checked" : "not checked"));
if (ckShowLand.Checked)
{
// Process the list of files found in the directory.
if (LandZoneCfg.landmarkTypesList == null)
LandZoneCfg.landmarkTypesList = smdbObj.GetAllLandmarkTypes();
List<LandmarkUI> landmarks = smdbObj.GetAllLandmarks();
mapHandler.ShowLandmarks(landmarks);
}
//DisplayAllLandmarksOnMap();
else
{
mapHandler.RemoveLandmarks();
}
//HideAllLandmarksOnMap();
if (isFilterLoaded)
VisualSettings.InsertUpdateHTforVisualItems(tabName, ((RadCheckBox)sender).Name, ((RadCheckBox)sender).Checked.ToString());
}
/// <summary>
/// Show or hide geofences on the map
/// </summary>
private void ckShowZone_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
try
{
Utils.WriteLine("ckShowZone_ToggleStateChanged " + (ckShowZone.Checked ? "checked" : "not checked"));
//mapGoogles.ExecuteScript("window.GWTcallback('showconsole,true');");
if (ckShowZone.Checked)
{
List<GeofenceUI> allGeofences = smdbObj.GetAllGeofences();
mapHandler.ShowGeofences(allGeofences);
}
//ForceShowZone();
else
{
mapHandler.RemoveGeofences();
}
//ForceHideZone();
if (isFilterLoaded)
{
VisualSettings.InsertUpdateHTforVisualItems(tabName, ((RadCheckBox)sender).Name, ((RadCheckBox)sender).Checked.ToString());
}
}
catch (Exception ex)
{
Utils.WriteLine("ExLive13:" + ex.ToString());
}
}
/// <summary>
/// Display the geofences on the map
/// </summary>
public void ForceShowZone()
{
try
{
Boolean First = true;
Int32 pas = -1;
if (MainForm2.ZoneIDHash.Count > 1)
{
pas = 0;
ZoneGoogle = MainForm2.ZoneIDHash.Count;
}
Double LatMN = 0, LatMX = 0, LngMN = 0, LngMX = 0;
if (MainForm2.ZoneIDHash.Count > 0)
{
if (cornersDataSet != null)
{
cornersDataSet.Delete();
cornersDataSet = null;
}
//cornersDataSet = mapControl.ActiveMap.DataSets.AddPushpinSet("colturiSafe");
}
First = true;
Boolean first = true;
Double latfirst = 0, lngfirst = 0;
int cont = 0;
Boolean retur = false;
if (docLoad)
{
mapGoogles.ExecuteScript("window.GWTcallback('" + "deletePolygon,ALL');");
}
List<GeofenceUI> allGeofences = smdbObj.GetAllGeofences();
foreach(GeofenceUI geofence in allGeofences)
{
String datasetCMD = "";
foreach (GeofencePoint point in geofence.points)
{
datasetCMD = datasetCMD
+ MainForm2.FixDoubleLAT(point.Latitude + "") + ","
+ MainForm2.FixDoubleLNG(point.Longitude + "") + ",";
}
// get geofence fill color
String hexFillColor = "#" + geofence.FillColor.R.ToString("X2") + geofence.FillColor.G.ToString("X2") + geofence.FillColor.B.ToString("X2");
String hexBorderColor = "#" + geofence.BorderColor.R.ToString("X2") + geofence.BorderColor.G.ToString("X2") + geofence.BorderColor.B.ToString("X2");
try
{
datasetCMD = datasetCMD.Remove(datasetCMD.Length - 1);
}
catch (Exception ex) { SM.Debug("Ex:" + ex.ToString()); }
if (docLoad)
{
mapGoogles.ExecuteScript("window.GWTcallback('" + "setPolygon,"
+ geofence.Name + ","
+ hexFillColor + ","
+ MainForm2.FixDoubleLAT(geofence.FillOpacity.ToString()) + ","
+ hexBorderColor + ","
+ MainForm2.FixDoubleLAT(geofence.BorderOpacity.ToString()) + ","
+ MainForm2.FixDoubleLAT(geofence.BorderWidth.ToString()) + ","
+ datasetCMD + "');");
//mapGoogles.ExecuteScript("window.GWTcallback('" + "removelabels,"+datasetCMD + "');");
}
System.Threading.Thread.Sleep(10);
}
parent.DisplayToast(MainForm2.returnLNGString("geofenceDisplayed"),
"<html><b>" + allGeofences.Count + " " + MainForm2.returnLNGString("geofences") + " </b> " + MainForm2.returnLNGString("mapdisp") + " </html>");
}
catch (Exception ex)
{
SM.Debug("Error zone preview:" + ex.ToString());
}
}
private Int32 ZoneGoogle = 0;
/// <summary>
/// Hide all the geofences on the map
/// </summary>
public void ForceHideZone()
{
try
{
if (docLoad)
{
mapGoogles.ExecuteScript("window.GWTcallback('" + "deletePolygon,ALL');");
}
}
catch (Exception ex)
{
SM.Debug("Unable to remove zones from map " + ex.ToString());
}
}
private MapGoogle.DataSetx cornersDataSet;
/// <summary>
/// Format the unit number which is displayed on the groups header
/// </summary>
private void vehiclesList_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e)
{
try
{
string suff = String.Concat(" (", e.Group.ItemCount.ToString(), ")");
e.Group.Header = e.Group.Key + "" + getGroupHeaderCount(e.Group.Key.ToString());
e.FormatString = e.Group.Header;
}
catch (Exception ex)
{
SM.Debug("Erorr on GroupSummaryEvaluate" + ex.ToString());
}
}
private void toolWindow2_Resize(object sender, EventArgs e)
{
int diffHeight, diffWidth;
Control control = (Control)sender;
diffHeight = control.Size.Height / 2;
diffWidth = control.Size.Width / 2;
diffHeight = diffHeight - 50;
diffWidth = diffWidth - 120;
if ((diffHeight > 0) && (diffWidth > 0))
LivePanel.Location = new System.Drawing.Point(diffWidth, diffHeight);
}
volatile Boolean PingFinish = false;
volatile Boolean PingGoogle = false;
private Boolean firstLoad = true;
DimensionsGoogle GoogleSize = null;
private void sendPOLLARSToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
smdbObj.Send_cmd_to_val(false, ((Vehicle)MainForm2.vehicleHT[(String)gridVehicles.SelectedRows[0].Cells[2].Value]).IMEI, "");
}
catch (Exception ex)
{
SM.Debug("Cann't send POLL cmd" + ex.ToString());
}
}
private Font normalFont = new Font(new FontFamily("Segoe UI"), 10.0F, FontStyle.Regular);
private Font boldFont = new Font(new FontFamily("Segoe UI"), 10.0F, FontStyle.Bold);
private void vehiclesList_ViewCellFormatting(object sender, CellFormattingEventArgs e)
{
if ((MainForm2.radioType == RADIOTYPE.HARRIS) || (MainForm2.radioType == RADIOTYPE.ATLAS))
{
if (e.CellElement is GridGroupContentCellElement)
{
e.CellElement.ForeColor = MainForm2.HarTextColor;
}
else
{
e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local);
}
}
if (e.CellElement.RowInfo.Group == null && (e.CellElement is GridSummaryCellElement || e.CellElement is GridGroupContentCellElement))
{
e.CellElement.ForeColor = Color.Red;
e.CellElement.TextAlignment = ContentAlignment.MiddleCenter;
e.CellElement.Font = new Font("Microsoft Sans Serif", 13,
FontStyle.Bold,
GraphicsUnit.Pixel);
}
if (e.CellElement.RowIndex >= 0)
{
//SM.Debug("VALUE OF THE BOX" + Convert.ToInt32(vehiclesList.Rows[e.CellElement.RowIndex].Cells[5].Value));
//if (Convert.ToInt32(vehiclesList.Rows[e.CellElement.RowIndex].Cells[5].Value) == 1)
if (Convert.ToInt32(e.Row.Cells["Emerg0off1on"].Value) == 1)
{
e.CellElement.ForeColor = Color.Red;
e.CellElement.Font = boldFont;
}
else
{
e.CellElement.ForeColor = Color.Black;
e.CellElement.Font = normalFont;
}
}
}
/// <summary>
/// Event handler for when the groupBox checkbox changes its state
/// </summary>
[ChangesAtrribute("4 Nov 2016", "Fix Select/Deselect all not triggering for all groups [Group.Headers -> Group.Key]")]
private void GroupCheckBox_StateChanged(object sender, GRPEventArgs e)
{
List<String> unitsThatAreInTheGroup = new List<string>();
List<Vehicle> toDisplayVehicles = new List<Vehicle>();
bool actionCancelled = false;
try
{
String groupName = gridVehicles.Groups[e.idx].Key.ToString();
int nrstartPerf = 0;
bool StartPerf = false;
centeredState = false;
//Utils.WriteLine("GroupCheckBox_StateChanged idx " + e.idx + " | " + gridVehicles.Groups[e.idx].Header + " | " + (e.stat ? "checked " : "uncheked"));
//if (e.stat != (Boolean)CheckedGroup[e.idx])
{
CheckedGroup[e.idx] = e.stat;
if (e.stat == true)
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(groupName)).ToList();
// detect how many vehicles are displayed
List<Vehicle> displayedVehicles = vehicles.Select(d => d).Where(d => ((MapElement)d.MapsHT[tabName]).itemCheck).ToList();
toDisplayVehicles = vehicles.Where(w => !((MapElement)w.MapsHT[tabName]).itemCheck).ToList();
// number of units from this group that are not displayed
int toDisplayUnitsFromThisGroup = vehicles.Count - displayedVehicles.Count;
if (rseUnitsOnMap.Value < getNumberOfDisplayedUsers() + toDisplayUnitsFromThisGroup)
{
if (getMaxUnitsWarningDialogResult(toDisplayUnitsFromThisGroup, getNumberOfDisplayedUsers() + toDisplayUnitsFromThisGroup, (Int64)rseUnitsOnMap.Value) != DialogResult.Yes)
{
CustomGroupHeaderCell.CheckBoxClicked = false;
if (groupsHeadersByString.ContainsKey(groupName))
groupsHeadersByString[groupName].checkbox.Checked = false;
actionCancelled = true;
}
else
rseUnitsOnMap.Value = getNumberOfDisplayedUsers() + toDisplayUnitsFromThisGroup;
}
}
if (!actionCancelled)
{
//SM.Debug("Send command to google");
//gridVehicles.TableElement.BeginUpdate();
//timerBegin = new System.Threading.Timer(MakeUpdateToListBegin, null, 300, System.Threading.Timeout.Infinite);
for (int contor = 0; contor < gridVehicles.Rows.Count; contor++)
{
// get current vehicle which is updated
Vehicle vehicleTemp = (Vehicle)MainForm2.vehicleHT[(String)gridVehicles.Rows[contor].Cells["UnitName"].Value];
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[contor].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
bool isInThisGroup = false;
if (groupType == GroupType.STATUS && gridData.Status.Equals(groupName))
{
//Utils.WriteLine("THIS UNIT " + gridData.UnitName + " IS IN THIS GROUP " + gridVehicles.Groups[e.idx].Header, ConsoleColor.Red);
isInThisGroup = true;
}
else if (groupType == GroupType.GROUPNAME && gridData.GrpName.Equals(groupName))
{
//Utils.WriteLine("THIS UNIT " + gridData.UnitName + " IS IN THIS GROUP " + gridVehicles.Groups[e.idx].Key, ConsoleColor.Yellow);
isInThisGroup = true;
}
else if (groupType == GroupType.POSITIONTIMEAGO && gridData.PositionTimeAgo.Equals(groupName))
{
//Utils.WriteLine("THIS UNIT " + gridData.UnitName + " IS IN THIS GROUP " + gridVehicles.Groups[e.idx].Header, ConsoleColor.Cyan);
isInThisGroup = true;
}
// make modifications only if the unit is in the group
if (isInThisGroup)
{
VisualSettings.SetDisplayedInLiveTab(gridData.SipId, e.stat, tabName);
if (!gridData.OnMap && e.stat)
{
nrstartPerf++;
gridData.OnMap = true;
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).ActivatePushPin();
unitsThatAreInTheGroup.Add(gridData.UnitName);
}
else if (!e.stat && gridData.OnMap)
{
gridData.OnMap = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).itemCheck = false;
// notify that an update must be made
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
if (((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).pp != null)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).pp.Highlight = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).pp.BalloonState = GeoBalloonStatex.geoDisplayNone;
((MapElement)((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).MapsHT[tabName]).DeactivatePushpin();
if (((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).selectCenter)
{
((Vehicle)MainForm2.vehicleHT[gridData.UnitName]).selectCenter = false;
centeredState = false;
}
}
unitsThatAreInTheGroup.Add(gridData.UnitName);
}
}
}
}
// if group is selected
if (e.stat)
{
if (StartPerf)
{
txProgStatus.Clear();
Console.WriteLine("Panel visibil false 3");
LivePanel.Visible = false;
//LiveWaitingBar.Visible = false;
txProgStatus.Visible = false;
Cursor = System.Windows.Forms.Cursors.Arrow;
mapControl.MousePointer = GeoPointerx.geoPointerDefault;
}
}
//gridVehicles.TableElement.EndUpdate(false);
//gridVehicles.TableElement.Update(GridUINotifyAction.DataChanged);
if (e.stat)
{
mapHandler.AddGroup(groupName, toDisplayVehicles, false);
}
else
mapHandler.RemoveGroup(groupName);
// update the header name
onGroupDisplayedUnitsChangedHandler(groupName);
}
}
}
catch (Exception ex)
{
SM.Debug("Error on select ALL: " + ex.ToString());
}
}
private void vehiclesList_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e)
{
gridVehicles.TableElement.ScrollToRow(0);
}
volatile Boolean newrowUpdated = false;
volatile RadSortOrder oldSortType = RadSortOrder.Ascending;
volatile Int32 oldColomnSort = 0;
/// <summary>
/// Event handler for when a position row needs to be updated
/// or the timmer expired
/// </summary>
private void NewRowUpdated_Tick(object sender, EventArgs e)
{
try
{
if (newrowUpdated)
{
for (int i = 0; i < 10; i++)
{
if (tableVehiclesList.Columns[i].SortOrder != RadSortOrder.None)
{
oldColomnSort = i;
oldSortType = tableVehiclesList.Columns[i].SortOrder;
tableVehiclesList.Columns[i].SortOrder = RadSortOrder.None;
break;
}
}
tableVehiclesList.TableElement.Update(GridUINotifyAction.DataChanged);
tableVehiclesList.Refresh();
//refresh pe order after
tableVehiclesList.Columns[oldColomnSort].SortOrder = oldSortType;
}
newrowUpdated = false;
}
catch (Exception ex)
{
Console.WriteLine("Error on update rows:" + ex.ToString());
}
}
private void tableVehiclesList_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e)
{
TableViewDataComplete = true;
}
private void tableVehiclesList_SortChanged(object sender, GridViewCollectionChangedEventArgs e)
{
TableViewSortComplete = true;
}
/// <summary>
/// Event handler to check if the map has loaded after five seconds
/// </summary>
private void TimerLoad5Sec_Tick(object sender, EventArgs e)
{
if (WaitWindow!= null && WaitWindow.Visible)
{
try
{
SM.Debug("Timer started for Load5Seconds");
mapControl.RefreshMap(LiveMapPanel.Height, LiveMapPanel.Width);
PingGoogle = true;
PingFinish = true;
GoogleSize = new DimensionsGoogle(LiveMapPanel.Width, LiveMapPanel.Height);
TimerToLoadMap.Enabled = true;
TimerToLoadMap.Start();
docLoad = true;
firstLoad = false;
}
catch (Exception ex)
{
SM.Debug("Error to lateresize:" + ex.ToString());
}
}
TimerLoad3Sec.Stop();
}
Int32 nrtrys = 0;
private void ForceRefreshTimer_Tick(object sender, EventArgs e)
{
nrtrys++;
if (nrtrys > 3)
{
ForceRefreshTimer.Stop();
ForceRefreshTimer.Enabled = false;
}
}
private WaitToLoad WaitWindow = null;
private void MessageScreen_Tick(object sender, EventArgs e)
{
try
{
MessageScreen.Stop();
MessageScreen.Enabled = false;
WaitWindow = new WaitToLoad(false);
WaitWindow.ShowDialog();
}
catch (Exception ex)
{
SM.Debug("Ex10:" + ex.ToString());
}
}
private void ForceLogin_Tick(object sender, EventArgs e)
{
if (MainForm2.forceLogin)
{
sel_desel.Checked = true;
rbDisplay.PerformClick();
}
ForceLogin.Stop();
ForceLogin.Enabled = false;
}
/// <summary>
/// Open a popup window which will desplay the desired info
/// </summary>
/// <param name="unitName"></param>
/// <param name="popupType"></param>
private void openPopupWindow(string unitName, EventType popupType)
{
try
{
if (MainForm2.PopupOpen[((Vehicle)MainForm2.vehicleHT[unitName]).IMEI] == null)
{
((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
FastCommandWindow frmPop = new FastCommandWindow(unitName, ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI, parent, popupType, smdbObj.get_all_DefSMS())
{
has_text = ((Vehicle)MainForm2.vehicleHT[unitName]).has_text,
has_voice = ((Vehicle)MainForm2.vehicleHT[unitName]).has_voice
};
if (MainForm2.HasVoice)
{
if (parent.VoiceFirstTime)
parent.First_time_start_radio();
frmPop.gwandradID = ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID;
frmPop.checkStatus();
}
else frmPop.DisablePTT();
frmPop.Show();
MainForm2.PopupOpen.Add(((Vehicle)MainForm2.vehicleHT[unitName]).IMEI, frmPop);
}
else
{
// the tab is already opened so it needs to change the tab
FastCommandWindow frmPop = (FastCommandWindow)MainForm2.PopupOpen[((Vehicle)MainForm2.vehicleHT[unitName]).IMEI];
frmPop.SelectTab(popupType);
frmPop.Activate();
}
}
catch (Exception ex)
{
SM.Debug("Cann't show new PopupWindow form" + ex.ToString());
}
}
private DialogResult getMaxUnitsWarningDialogResult(Int64 toDisplayVehiclesCount, Int64 totalDisplayed, Int64 displayedLimit )
{
RadMessageBox.Instance.Dispose();
RadMessageBox.SetThemeName("TelerikMetroBlue");
return RadMessageBox.Show(String.Format(MainForm2.returnLNGString("warningMaxNumberOfUnits"), toDisplayVehiclesCount,
totalDisplayed, displayedLimit), MainForm2.returnLNGString("war"), MessageBoxButtons.YesNo);
}
private Dictionary<string, CustomGroupHeaderCell> groupsHeadersByString = new Dictionary<string, CustomGroupHeaderCell>();
/// <summary>
/// Set the type of data which will be displayed inside the grid
/// </summary>
private void gridVehicles_CreateCell(object sender, GridViewCreateCellEventArgs e)
{
// format live column
if (e.Row is GridDataRowElement)
{
// increase row height
//e.Row.RowInfo.Height = 53;
if (e.Column.Name.Equals("live"))
{
e.CellType = typeof(LiveGridColumn);
e.CellElement = new LiveGridCellElement(e.Column, e.Row);
/*
// set the value for the cell
if (e.Row.Data != null && e.Row.Data.DataBoundItem != null &&
e.Row.Data.DataBoundItem is DataforVehList)
e.CellElement.Value = e.Row.Data.DataBoundItem as DataforVehList;*/
}
if (e.Column is GridViewIndentColumn)
{
//e.Column.IsVisible = false;
/*
e.Column.MaxWidth = 7;
e.Column.MinWidth = 7;
e.Column.Width = 7;*/
//e.CellElement.Visibility = ElementVisibility.Hidden;
}
}
}
/// <summary>
/// Format the cells of live units to the custom format, including padding
/// </summary>
private void gridVehicles_CellFormatting(object sender, CellFormattingEventArgs e)
{
GridCellElement cellElement = e.CellElement;
GridViewDataColumn columnInfo = e.CellElement.ColumnInfo as GridViewDataColumn;
// set padding and force the content adding
if (cellElement is LiveGridCellElement && columnInfo.Name == "live")
{
cellElement.Padding = new Padding(0, 0, 0, 0);
//cellElement.SetContent();
// add click listener only if not added before
if ((cellElement.Tag != null && !cellElement.Tag.Equals("done")) || cellElement.Tag == null)
{
((LiveGridCellElement)cellElement).OnLiveCell_Click += delegate(object s, LiveGridCellElement.LiveCellClickEventArgs ea)
{
//Utils.WriteLine("CLICKED " + ea.gridData.UnitName + " | " + ea.eventType, ConsoleColor.Red);
/*
Vehicle veh = (Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName];
ea.gridData.Latitude = veh.LAT;
ea.gridData.Longitude = veh.LNG;
ea.gridData.Speed = veh.GetSpeed();
ea.gridData.PositionTime = new DateTime(veh.lastValidPositionTime);
*/
// skip the wvent while the map isn't loaded
if (!mapLoaded)
return;
switch (ea.eventType)
{
// update the units which are displayed on the map
case EventType.DISPLAY:
{
VisualSettings.SetDisplayedInLiveTab(ea.gridData.SipId, ea.gridData.OnMap, tabName);
// display the car on the map and then notify the change
if (docLoad && ea.gridData.OnMap)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).ActivatePushPin();
MainForm2.SendDataToMapQUE.PostItem(ea.gridData.UnitName);
try
{
if (MainForm2.SendDataToMapHASH[ea.gridData.UnitName] == null)
MainForm2.SendDataToMapHASH.Add(ea.gridData.UnitName, 0);
}
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
// TODO check if the entire group is checked or not and update the group checkbox
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(ea.gridData.GrpName)).ToList();
// detect how many vehicles are displayed
List<Vehicle> notDisplayedVehicles = vehicles.Where(w => ((MapElement)w.MapsHT[tabName]).itemCheck == false).ToList();
// check the checkbox for the group if all the units are checked
if(notDisplayedVehicles.Count == 0 && groupsHeadersByString.ContainsKey(ea.gridData.GrpName))
groupsHeadersByString[ea.gridData.GrpName].checkbox.Checked = true;
if (parseLiveGridEvents)
{
Vehicle veh = ((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]);
mapHandler.AddVehicles(new List<Vehicle>() { veh }, false);
}
}
else
{
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).itemCheck = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).DeactivatePushpin();
List<Vehicle> vehicles = new List<Vehicle>();
vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList()).Where(x => x.group.Name.Equals(ea.gridData.GrpName)).ToList();
// detect how many vehicles are displayed
List<Vehicle> displayedVehicles = vehicles.Select(d => d).Where(d => ((MapElement)d.MapsHT[tabName]).itemCheck).ToList();
// uncheck the checkbox for the group
if(groupsHeadersByString.ContainsKey(ea.gridData.GrpName))
groupsHeadersByString[ea.gridData.GrpName].checkbox.Checked = false;
if (parseLiveGridEvents && displayedVehicles.Count > 0)
mapHandler.RemoveVehicles(new List<Vehicle>() { ((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]) });
else
mapHandler.RemoveGroup(ea.gridData.GrpName);
}
// update the header name
onGroupDisplayedUnitsChangedHandler(ea.gridData.GrpName);
}
//rbDisplay.PerformClick();
break;
case EventType.CENTER:
{
// display the car on the map and then notify the change
if (docLoad && !ea.gridData.OnMap)
{
ea.gridData.OnMap = true;
ea.gridData.NrOfUpdates += 1;
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).itemCheck = true;
((MapElement)((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]).MapsHT[tabName]).ActivatePushPin();
MainForm2.SendDataToMapQUE.PostItem(ea.gridData.UnitName);
try
{
if (MainForm2.SendDataToMapHASH[ea.gridData.UnitName] == null)
MainForm2.SendDataToMapHASH.Add(ea.gridData.UnitName, 0);
}
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
Vehicle veh = ((Vehicle)MainForm2.vehicleHT[ea.gridData.UnitName]);
// TODO check if the entire group is checked or not and update the group checkbox
mapHandler.AddVehicles(new List<Vehicle>() { veh }, true);
// update the header name
onGroupDisplayedUnitsChangedHandler(ea.gridData.GrpName);
}
VisualSettings.SetDisplayedInLiveTab(ea.gridData.SipId, ea.gridData.OnMap, tabName);
// open info buble
if (docLoad && ea.gridData.OnMap)
{
if ((ea.gridData.Latitude != 0 && ea.gridData.Latitude != 0.1) ||
(ea.gridData.Longitude != 0 && ea.gridData.Longitude != 0.1))
{
/*
SM.Debug("Send open info");
mapGoogles.ExecuteScript("window.GWTcallback('" + "openInfo," + ea.gridData.UnitName + "');");
Thread.Sleep(50);
mapGoogles.ExecuteScript("window.GWTcallback('centerzoom," + MainForm2.FixDoubleLAT(ea.gridData.Latitude + "") + ","
+ MainForm2.FixDoubleLNG(ea.gridData.Longitude + "") + ",-1');");
Thread.Sleep(1);
*/
if (mapHandler.IsUnitDisplaydOnMap(ea.gridData.UnitName))
{
mapHandler.OpenInfoBubble(ea.gridData.UnitName);
Thread.Sleep(50);
mapHandler.CenterMapToPosition(new LatLngZoom()
{
Lat = ea.gridData.Latitude,
Lng = ea.gridData.Longitude,
ZoomLevel = -1
});
}
else
parent.DisplayToast(MainForm2.returnLNGString("noGPS"), MainForm2.returnLNGString("HTMLnoGPS"));
}
else
{
parent.DisplayToast(MainForm2.returnLNGString("noGPS"), MainForm2.returnLNGString("HTMLnoGPS"));
}
}
break;
}
case EventType.ALERT:
{
/*
// trigger the event up one level
if (OnAlertRequiredReceived != null)
OnAlertRequiredReceived(new AlertRequiredEventArgs() { gridData = ea.gridData });
break;
* */
openPopupWindow(ea.gridData.UnitName, EventType.ALERT);
break;
}
case EventType.TEXT:
{
openPopupWindow(ea.gridData.UnitName, EventType.TEXT);
break;
}
case EventType.VOICE:
{
openPopupWindow(ea.gridData.UnitName, EventType.VOICE);
break;
}
}
};
}
cellElement.Tag = "done";
}
}
private bool positionsWindowIsActive = false;
/// <summary>
/// Refresh the positions list only when the Window is entered
/// </summary>
private void windowPositions_Enter(object sender, EventArgs e)
{
positionsWindowIsActive = true;
// get the address based on the positionss
rbDisplay.PerformClick();
RefreshPositionsGrid();
}
/// <summary>
/// Flag when the positions windows doesn't need to be refreshed anymore
/// </summary>
private void windowPositions_Leave(object sender, EventArgs e)
{
// flag that the windows was left
positionsWindowIsActive = false;
}
/// <summary>
/// Refresh the grid of positions
/// </summary>
public void RefreshPositionsGrid()
{
// invoke the method in UI Thread if needed
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate ()
{
RefreshPositionsGrid();
});
}
Int32 oldColomnSort = 0;
RadSortOrder oldSortType = RadSortOrder.Ascending;
Vehicle vehicleTemp;
tableVehiclesList.BeginUpdate();
ListforGrid.Clear(); //aici e combinatia fatala
try
{
for (int i = 0; i < tableVehiclesList.Columns.Count; i++)
{
if (tableVehiclesList.Columns[i].SortOrder != RadSortOrder.None)
{
oldColomnSort = i;
oldSortType = tableVehiclesList.Columns[i].SortOrder;
break;
}
}
}
catch (Exception ex)
{
SM.Debug("Error on finding the sort column:" + ex.ToString());
}
tableVehiclesList.Columns["VehName"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["datetime"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["address"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["speed"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["head"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["di"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["do"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["lat"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["lng"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["zone"].SortOrder = RadSortOrder.None;
tableVehiclesList.Columns["Altitude"].SortOrder = RadSortOrder.None;
Thread.Sleep(100);
int countlist = -1;
String LatStr = "";
String LngStr = "";
String AltStr = "";
String Zone;
Double LatDou, LngDou;
// flag that an update will be made
//gridVehicles.TableElement.BeginUpdate();
//ListforGrid.Clear();
for (int contor = 0; contor < gridVehicles.Rows.Count; contor++)
{
// get current vehicle which is updated
vehicleTemp = (Vehicle)MainForm2.vehicleHT[(String)gridVehicles.Rows[contor].Cells["UnitName"].Value];
// get the Data bound item for each grid row
DataforVehList gridData = gridVehicles.Rows[contor].DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
// skip this unit if it doesn't need to be updated
if (gridData.OnMap)
{
LatLngUTM tmpLatLng = new LatLngUTM();
Zone = "";
AltStr = Math.Round(vehicleTemp.GetAlt(), 5).ToString();
if (MainForm2.LatLngUTM.CompareTo("Lat/Lng No.") == 0)
{
LatStr = Math.Round(vehicleTemp.GetLat(), 5).ToString();
LngStr = Math.Round(vehicleTemp.GetLng(), 5).ToString();
}
else if (MainForm2.LatLngUTM.CompareTo("Lat/Lng Deg.") == 0)
tmpLatLng.LatLongtoDeg(vehicleTemp.GetLat(), vehicleTemp.GetLng(), out LatStr, out LngStr);
else if (MainForm2.LatLngUTM.CompareTo("UTM") == 0)
{
tmpLatLng.LatLongtoUTM(vehicleTemp.GetLat(), vehicleTemp.GetLng(), out LatDou, out LngDou, out Zone);
LatStr = LatDou.ToString("###,###,###");
LngStr = LngDou.ToString("###,###,###");
}
// update all the new fields and values
if (!((Math.Round(vehicleTemp.GetLat()) == 0) && (Math.Round(vehicleTemp.GetLng()) == 0)))
ListforGrid.Add(new DataforGRID(countlist.ToString(), vehicleTemp.busName,
vehicleTemp.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(),
vehicleTemp.GetLastAddress(), Convert.ToString(vehicleTemp.GetSpeed()),
Utils.GetDirection(vehicleTemp.GetHeading()).ToString(), Convert.ToString(vehicleTemp.GetDI()),
Convert.ToString(vehicleTemp.GetDO()), Convert.ToString(LatStr),
Convert.ToString(LngStr), Zone, Convert.ToString(AltStr)));
else
ListforGrid.Add(new DataforGRID(countlist.ToString(), vehicleTemp.busName,
vehicleTemp.lastActivityTime.ConvertGMTToLocal().GetDTFromSeconds(), "N/A",
Convert.ToString(vehicleTemp.GetSpeed()), "N/A", Convert.ToString(vehicleTemp.GetDI()),
Convert.ToString(vehicleTemp.GetDO()), "N/A", "N/A", "", "N/A"));
}
}
}
TableViewSortComplete = false;
TableViewDataComplete = false;
try
{
tableVehiclesList.DataSource = null;
tableVehiclesList.DataSource = ListforGrid;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
tableVehiclesList.Columns[oldColomnSort].SortOrder = oldSortType;
tableVehiclesList.TableElement.ScrollToRow(0);
tableVehiclesList.EndUpdate();
//tableVehiclesList.Refresh();
}
/// <summary>
/// Refresh the grid of positions for one unit
/// <param name="unitName">Unit name for which the position should be updated</param>
/// <param name="address">Current address at which the unit is placed</param>
/// </summary>
public void RefreshPositionsGrid(string unitName)
{
for (int contor = 0; contor < tableVehiclesList.Rows.Count; contor++)
{
// get the Data bound item for each grid row
DataforGRID gridData = tableVehiclesList.Rows[contor].DataBoundItem as DataforGRID;
// verify if the unit is valid or not
if (gridData != null)
{
if (!unitName.Equals(gridData.VehName))
continue;
// get current vehicle which is updated
Vehicle vehicleTemp = (Vehicle)MainForm2.vehicleHT[gridData.VehName];
int countlist = -1;
String LatStr = "";
String LngStr = "";
String AltStr = "";
String Zone;
Double LatDou, LngDou;
LatLngUTM tmpLatLng = new LatLngUTM();
Zone = "";
AltStr = Math.Round(vehicleTemp.GetAlt(), 5).ToString();
if (MainForm2.LatLngUTM.CompareTo("Lat/Lng No.") == 0)
{
LatStr = Math.Round(vehicleTemp.GetLat(), 5).ToString();
LngStr = Math.Round(vehicleTemp.GetLng(), 5).ToString();
}
else if (MainForm2.LatLngUTM.CompareTo("Lat/Lng Deg.") == 0)
tmpLatLng.LatLongtoDeg(vehicleTemp.GetLat(), vehicleTemp.GetLng(), out LatStr, out LngStr);
else if (MainForm2.LatLngUTM.CompareTo("UTM") == 0)
{
tmpLatLng.LatLongtoUTM(vehicleTemp.GetLat(), vehicleTemp.GetLng(), out LatDou, out LngDou, out Zone);
LatStr = LatDou.ToString("###,###,###");
LngStr = LngDou.ToString("###,###,###");
}
/*
if (!((Math.Round(vehicleTemp.GetLat()) == 0) && (Math.Round(vehicleTemp.GetLng()) == 0)))
ListforGrid.Add(new DataforGRID(countlist.ToString(), vehicleTemp.busName,
convDT.GetDTFromSeconds(convDT.ConvertGMTToLocal(vehicleTemp.lastActivityTime)),
vehicleTemp.GetLastAddress(), Convert.ToString(vehicleTemp.GetSpeed()),
Utils.GetDirection(vehicleTemp.GetHeading()).ToString(), Convert.ToString(vehicleTemp.GetDI()),
Convert.ToString(vehicleTemp.GetDO()), Convert.ToString(LatStr),
Convert.ToString(LngStr), Zone, Convert.ToString(AltStr)));
else
ListforGrid.Add(new DataforGRID(countlist.ToString(), vehicleTemp.busName,
convDT.GetDTFromSeconds(convDT.ConvertGMTToLocal(vehicleTemp.lastActivityTime)), "N/A",
Convert.ToString(vehicleTemp.GetSpeed()), "N/A", Convert.ToString(vehicleTemp.GetDI()),
Convert.ToString(vehicleTemp.GetDO()), "N/A", "N/A", "", "N/A"));
*/
gridData.Address = vehicleTemp.GetLastAddress();
gridData.Datatime = (vehicleTemp.lastActivityTime).ConvertGMTToLocal().GetDTFromSeconds();
gridData.Speed = Convert.ToString(vehicleTemp.GetSpeed());
gridData.DI = Convert.ToString(vehicleTemp.GetDI());
gridData.DO = Convert.ToString(vehicleTemp.GetDO());
if (!((Math.Round(vehicleTemp.GetLat()) == 0) && (Math.Round(vehicleTemp.GetLng()) == 0)))
{
gridData.Alt = Convert.ToString(AltStr);
gridData.Lat = Convert.ToString(LatStr);
gridData.Lng = Convert.ToString(LngStr);
gridData.Zone = zonename;
gridData.Head = Utils.GetDirection(vehicleTemp.GetHeading()).ToString();
}
else
{
gridData.Alt = gridData.Lat = gridData.Lng = "N/A";
gridData.Zone = "";
gridData.Head = "N/A";
}
gridData.NrOfUpdates = gridData.NrOfUpdates + 1;
}
}
//foreach()
}
public static GroupType groupType = GroupType.GROUPNAME;
public static ListSortDirection sortDirection = ListSortDirection.Ascending;
/// <summary>
/// Event Handler for when a filter picture box is clicked
/// This should group the grid based on its status
/// </summary>
private void pbFilter_Click(object sender, EventArgs e)
{
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_status_g"))
MainForm2.imagesDictionary.Add("l_filter_status_g", Utils.MakeGrayscale3(global::Dispatcher.Properties.Resources.l_bullet_bl, 0.5f));
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_time_g"))
MainForm2.imagesDictionary.Add("l_filter_time_g", Utils.MakeGrayscale3(global::Dispatcher.Properties.Resources.l_history_b, 0.5f));
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_group_g"))
MainForm2.imagesDictionary.Add("l_filter_group_g", Utils.MakeGrayscale3(global::Dispatcher.Properties.Resources.l_user_n, 0.5f));
pbGroupTime.Image = MainForm2.imagesDictionary["l_filter_time_g"];
pbGroupStatusType.Image = MainForm2.imagesDictionary["l_filter_status_g"];
pbGroup.Image = MainForm2.imagesDictionary["l_filter_group_g"];
pbGroupTime.Tag = pbGroupStatusType.Tag = pbGroup.Tag = "disabled";
if ((PictureBox)sender == pbGroupTime)
{
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_time"))
MainForm2.imagesDictionary.Add("l_filter_time",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_history_b, MainForm2.ButtonColor));
pbGroupTime.Image = MainForm2.imagesDictionary["l_filter_time"];
pbGroupTime.Tag = "enabled";
groupType = GroupType.POSITIONTIMEAGO;
}
else if ((PictureBox)sender == pbGroupStatusType)
{
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_status"))
MainForm2.imagesDictionary.Add("l_filter_status",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_bullet_bl, MainForm2.ButtonColor));
pbGroupStatusType.Image = MainForm2.imagesDictionary["l_filter_status"];
pbGroupStatusType.Tag = "enabled";
groupType = GroupType.STATUS;
}
else if ((PictureBox)sender == pbGroup)
{
if (!MainForm2.imagesDictionary.ContainsKey("l_filter_group"))
MainForm2.imagesDictionary.Add("l_filter_group",
Utils.ChangeColor(global::Dispatcher.Properties.Resources.l_user_n, MainForm2.ButtonColor));
pbGroup.Image = MainForm2.imagesDictionary["l_filter_group"];
pbGroup.Tag = "enabled";
groupType = GroupType.GROUPNAME;
}
// group the vehicles
gridVehicles_SetGrouping(groupType, true);
if (isFilterLoaded) VisualSettings.InsertUpdateHTforVisualItems(tabName, "PictureBox_Filter", ((PictureBox)sender).Name);
}
private void pbFilter_MouseEnter(object sender, EventArgs e)
{
PictureBox pbSender = (PictureBox)sender;
String toolTipTitle = "";
String toolTipText = "";
if (pbSender == pbGroup)
{
toolTipTitle = MainForm2.returnLNGString("live_filter_group_title");
toolTipText = MainForm2.returnLNGString("live_filter_group");
}
else if (pbSender == pbGroupStatusType)
{
toolTipTitle = MainForm2.returnLNGString("live_filter_status_title");
toolTipText = MainForm2.returnLNGString("live_filter_status"); ;
}
else if (pbSender == pbGroupTime)
{
toolTipTitle = MainForm2.returnLNGString("live_filter_time_title"); ;
toolTipText = MainForm2.returnLNGString("live_filter_time"); ;
}
toolTipHelp.ToolTipTitle = toolTipTitle + ": " + (pbSender.Tag.Equals("enabled") ? MainForm2.returnLNGString("active") : MainForm2.returnLNGString("inactive"));
if (pbSender == pbCollapseAll)
{
toolTipHelp.ToolTipTitle = "";
toolTipText = MainForm2.returnLNGString("collapseAll");
}
else if (pbSender == pbExpandAll)
{
toolTipHelp.ToolTipTitle = "";
toolTipText = MainForm2.returnLNGString("expandAll");
}
toolTipHelp.Show(
String.Format(toolTipText), pbSender, 150000);
}
private void pbFilter_MouseLeave(object sender, EventArgs e)
{
toolTipHelp.Hide((PictureBox)sender);
}
/// <summary>
/// Change the group type of the grid and mention if the reordering should be
/// made or not
/// </summary>
/// <param name="type">Sorting type which corresponds to the column</param>
/// <param name="changeOrder"></param>
private void gridVehicles_SetGrouping(GroupType type, bool changeOrder)
{
// do not refresh the grid if not desired
if (!rcbAutoRefresh.Checked)
return;
GroupLiveGrid(type, changeOrder);
//Utils.WriteLine("gridVehicles_SetGrouping");
}
/// <summary>
/// Change the group type of the grid and mention if the reordering should be
/// made or not
/// </summary>
/// <param name="type">Sorting type which corresponds to the column</param>
/// <param name="changeOrder"></param>
private void GroupLiveGrid(GroupType type, bool changeOrder)
{
//type = GroupType.GROUPNAME;
//changeOrder = false;
//sortDirection = ListSortDirection.Ascending;
try
{
// set data source and refresh it
gridVehicles.DataSource = null;
gridVehicles.DataSource = ListforVehList;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
string filterName = "GroupName";
if (type == GroupType.GROUPNAME)
filterName = "GroupName";
else if (type == GroupType.POSITIONTIMEAGO)
filterName = "PositionTimeAgo";
else if (type == GroupType.STATUS)
filterName = "Status";
else if (type == GroupType.RADIOGATEWAY)
filterName = "RadioGateway";
if (changeOrder)
{
// reverse the sorting order
if (gridVehicles.GroupDescriptors.Count > 0 &&
gridVehicles.GroupDescriptors[0].Expression.Contains(filterName))
{
GroupDescriptor gd = gridVehicles.GroupDescriptors[0];
sortDirection = gd.Expression.Contains("ASC") ? ListSortDirection.Descending : ListSortDirection.Ascending;
}
else if (type == GroupType.POSITIONTIMEAGO)
{
// time ago should start as descending
sortDirection = ListSortDirection.Descending;
}
if (sortDirection == ListSortDirection.Ascending)
gridVehicles.Columns["unitName"].SortOrder = RadSortOrder.Ascending;
else
gridVehicles.Columns["unitName"].SortOrder = RadSortOrder.Descending;
}
// clear previous filters and add the new one
gridVehicles.GroupDescriptors.Clear();
GroupDescriptor groupDescriptor = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor(filterName, sortDirection) });
gridVehicles.GroupDescriptors.Add(groupDescriptor);
int i = 0;
CheckedGroup.Clear();
foreach (GridViewRowInfo groupRow in gridVehicles.ChildRows)
{
// the group has items
if (groupRow.ChildRows.Count > 0)
{
// group name is groupRow.Group.Header
bool areAllChecked = true;
foreach (GridViewRowInfo gridRow in groupRow.ChildRows)
{
// get the Data bound item for each grid row
DataforVehList gridData = gridRow.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
{
if (!gridData.OnMap)
areAllChecked = false;
}
}
CheckedGroup.Add(i++, areAllChecked);
if (ExpandGroupingHT.Contains(groupRow.Group.Key.ToString()))
groupRow.IsExpanded = (bool)ExpandGroupingHT[groupRow.Group.Key.ToString()];
else
groupRow.IsExpanded = true;
if (groupRow != null && areAllChecked)
groupRow.Tag = true;
}
}
}
private void rbRefreshGroups_Click(object sender, EventArgs e)
{
Utils.WriteLine("rbRefreshGroups_Click", ConsoleColor.Yellow);
GroupLiveGrid(groupType, false);
}
private void gridVehicles_CustomGrouping(object sender, GridViewCustomGroupingEventArgs e)
{
string colName = gridVehicles.GroupDescriptors[e.Level].GroupNames[0].PropertyName;
if (colName == "PositionTimeAgo")
{
// get the Data bound item for each grid row
if (e.Row.DataBoundItem != null && e.Row.DataBoundItem is DataforVehList)
{
DataforVehList gridData = e.Row.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
e.GroupKey = gridData.PositionTimeAgo; //new DateTime(gridData.PositionTime.Year, gridData.PositionTime.Month, gridData.PositionTime.Day);
}
}
else if (colName == "Status")
{
// get the Data bound item for each grid row
if (e.Row.DataBoundItem != null && e.Row.DataBoundItem is DataforVehList)
{
DataforVehList gridData = e.Row.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
e.GroupKey = gridData.Status;
}
}
else if (colName == "GroupName")
{
// get the Data bound item for each grid row
if (e.Row.DataBoundItem != null && e.Row.DataBoundItem is DataforVehList)
{
DataforVehList gridData = e.Row.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
e.GroupKey = gridData.GrpName;
}
}
else if (colName == "RadioGateway")
{
// get the Data bound item for each grid row
if (e.Row.DataBoundItem != null && e.Row.DataBoundItem is DataforVehList)
{
DataforVehList gridData = e.Row.DataBoundItem as DataforVehList;
// verify if the unit is valid or not
if (gridData != null)
e.GroupKey = gridData.RadioGateway;
}
}
/*
else if (colName == "Name")
{
e.GroupKey = e.Row.Cells[colName].Value.ToString().Length;
}*/
}
/// <summary>
/// Event handler for when the left tab panel needs to be docked/transfor in floating state.
/// This will cancel this event in order to prevent the stupid case with hiding the dock window
/// </summary>
private void radDock1_DockStateChanging(object sender, DockStateChangingEventArgs e)
{
e.Cancel = true;
}
private void LiveTab_Load(object sender, EventArgs e)
{
// register for when the unit call status is changed
//this.parent.OnCallStatusChanged += delegate(string unitname, bool inCall)
//{
// Utils.WriteLine("SET CALL " + unitname + " " + inCall);
// mapGoogles.ExecuteScript(String.Format("window.GWTcallback('setCall,{0},{1}')", unitname, inCall));
//};
gridVehicles.DataSource = ListforVehList;
GridExpandAnimationType temp = gridVehicles.GroupExpandAnimationType;
gridVehicles.GroupExpandAnimationType = GridExpandAnimationType.None;
for (int i = 0; i < gridVehicles.Groups.Count; i++)
{
bool? isGroupExpanded = VisualSettings.IsGroupExpandedInLiveTab((gridVehicles.Groups[i]).Key + "", tabName);
if (isGroupExpanded == null || isGroupExpanded == true)
gridVehicles.Groups[i].Expand();
}
gridVehicles.GroupExpandAnimationType = temp;
gridVehicles.TableElement.ScrollToRow(0);
tableVehiclesList.DataSource = ListforGrid;
this.parent.OnCallStatusChanged += parent_OnCallStatusChanged;
if(MainForm2.vehicleHT.Count > 1)
rseUnitsOnMap.Maximum = MainForm2.vehicleHT.Count;
if (MainForm2.HashVal.ContainsKey(tabName + "_" + "setdatasetlimit"))
{
int limit = Convert.ToInt32(MainForm2.HashVal[tabName + "_" + "setdatasetlimit"]);
rseUnitsOnMap.Value = limit < rseUnitsOnMap.Maximum ? limit : rseUnitsOnMap.Maximum;
}
if (MainForm2.HashVal.ContainsKey("showMarkersLables"))
rcbMarkersLables.Checked = Convert.ToBoolean(MainForm2.HashVal["showMarkersLables"]);
}
void parent_OnCallStatusChanged(string unitname, bool inCall, Boolean fromField)
{
Utils.WriteLine($"UpdateMapCall status for {unitname} - {(inCall ? "in call" : "not in a call")}");
mapGoogles.ExecuteScript(String.Format("window.GWTcallback('setCall,{0},{1}')", unitname, inCall));
}
/// <summary>
/// Change background color for the row according to its state and theme
/// </summary>
private void gridVehicles_RowFormatting(object sender, RowFormattingEventArgs e)
{
if (e.RowElement.IsSelected)
{
e.RowElement.DrawFill = true;
e.RowElement.BackColor = MainForm2.GridSelectedRow;
e.RowElement.NumberOfColors = 1;
}
else
{
e.RowElement.DrawFill = false;
}
}
/// <summary>
/// Change background color for the row according to its state and theme
/// </summary>
private void tableVehiclesList_RowFormatting(object sender, RowFormattingEventArgs e)
{
if (e.RowElement.IsSelected)
{
e.RowElement.DrawFill = true;
e.RowElement.BackColor = MainForm2.GridSelectedRow;
e.RowElement.NumberOfColors = 1;
}
else
e.RowElement.DrawFill = false;
}
#region CHANGE TABS BACKGROUND
private DockWindow oldDockWindow = null;
private void radDock1_ActiveWindowChanging(object sender, DockWindowCancelEventArgs e)
{
// reset the background icon for the previous tab
e.OldWindow.TabStripItem.BackColor = Color.White;
e.OldWindow.TabStripItem.DrawFill = true;
e.OldWindow.TabStripItem.NumberOfColors = 1;
// reset the background for the new window
e.NewWindow.TabStripItem.DrawFill = true;
e.NewWindow.TabStripItem.NumberOfColors = 1;
e.NewWindow.TabStripItem.BackColor = MainForm2.TabSelectedColor;
// save old dock window
oldDockWindow = e.OldWindow;
}
private void radDock1_ActiveWindowChanged(object sender, DockWindowEventArgs e)
{
// reset the background icon for the previous tab
oldDockWindow.TabStripItem.BackColor = Color.White;
oldDockWindow.TabStripItem.DrawFill = true;
oldDockWindow.TabStripItem.NumberOfColors = 1;
e.DockWindow.TabStripItem.DrawFill = true;
e.DockWindow.TabStripItem.NumberOfColors = 1;
e.DockWindow.TabStripItem.BackColor = MainForm2.TabSelectedColor;
}
#endregion
private void CollapseExpandGrid(object sender, EventArgs e)
{
bool status = ((PictureBox)sender).Name == "pbExpandAll" ? true : false;
foreach (GridViewRowInfo groupRow in gridVehicles.ChildRows)
{
groupRow.IsExpanded = status;
collapseExpand(groupRow.Group.Header, status);
}
}
private void rcbAutoRefresh_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
if (isFilterLoaded) VisualSettings.InsertUpdateHTforVisualItems(tabName, ((RadCheckBox)sender).Name, ((RadCheckBox)sender).Checked.ToString());
}
private void rseUnitsOnMap_ValueChanged(object sender, EventArgs e)
{
if (docLoad)
{
System.Threading.Thread.Sleep(100);
VisualSettings.InsertUpdateHTforVisualItems(tabName + "_" + "setdatasetlimit", "", rseUnitsOnMap.Value.ToString());
mapGoogles.ExecuteScript("window.GWTcallback('" + "setdatasetlimit," + rseUnitsOnMap.Value.ToString() + "');");
}
if(mapLoaded)
mapHandler.SetDataSetLimit((int)rseUnitsOnMap.Value);
//sel_desel.Visible = (int)rseUnitsOnMap.Value > MainForm2.vehicleHT.Count;
}
private void rcbMarkersLables_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
// add to hash the new value for lables
if (isFilterLoaded)
VisualSettings.InsertUpdateHTforVisualItems(tabName, ((RadCheckBox)sender).Name, ((RadCheckBox)sender).Checked.ToString());
MapMarkersLables(rcbMarkersLables.Checked);
List<Vehicle> htList = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
IEnumerable<IGrouping<int, Vehicle>> query = htList.GroupBy(d => d.group.Id, d => d);
if (mapLoaded)
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, Vehicle> group in query)
{
String groupName = group.FirstOrDefault(d => d.sipID > 0).group.Name;
mapHandler.HasLabels = rcbMarkersLables.Checked;
mapHandler.SetLabelVisibility(rcbMarkersLables.Checked, groupName);
}
}
/// <summary>
/// Prevent the context menu to be shown for this grid
/// </summary>
private void tableVehiclesList_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
{
// do not display the context menu
e.Cancel = true;
}
private bool shouldIgnoreExpandedEvent = false;
private Hashtable ExpandGroupingHT = new Hashtable();
//SD-102 prevent live grid collapse expands by itself
private void gridVehicles_GroupExpanded(object sender, GroupExpandedEventArgs e)
{
collapseExpand(e.DataGroup.Key.ToString(), e.DataGroup.IsExpanded);
}
private void collapseExpand(string groupName, bool status)
{
if (shouldIgnoreExpandedEvent)
return;
if (!ExpandGroupingHT.Contains(groupName))
ExpandGroupingHT.Add(groupName, status);
else
ExpandGroupingHT[groupName] = status;
// add to hash
if (groupName != "")
VisualSettings.SetGroupExpandedInLiveTab(groupName, status, tabName);
//VisualSettings.InsertUpdateHTforVisualItems(tabName + "_" + "ExpandGroupingHT", groupName + "", status + "");
}
public void OnWebSocketStatusChanged(ToggleState isCheckboxChecked)
{
CheckboxSetToggleState(chkWebsocketConnected, isCheckboxChecked);
}
private void CheckboxSetToggleState(RadCheckBox checkBox, ToggleState toggleState)
{
checkBox.ToggleState = toggleState;
checkBox.ForeColor = (toggleState == ToggleState.On) ? Color.LightGreen : Color.Red;
if (checkBox.Name.Equals("chkWebsocketConnected") && toggleState == ToggleState.On)
{
chkWebsocketConnected.ToggleState = toggleState;
chkWebsocketConnected.ForeColor = Color.Green;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor = Color.LightGreen;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor2 = Color.LightGreen;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.LightGreen;
changeCheckboxState.Stop();
changeCheckboxState.Start();
}
else if (checkBox.Name.Equals("chkWebsocketConnected") && toggleState == ToggleState.Off)
{
chkWebsocketConnected.ToggleState = ToggleState.On;
chkWebsocketConnected.ForeColor = Color.Red;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor = Color.Red;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor2 = Color.Red;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.Red;
changeCheckboxState.Stop();
changeCheckboxState.Start();
}
else if (checkBox.Name.Equals("chkWebsocketConnected") && toggleState == ToggleState.Indeterminate)
{
chkWebsocketConnected.ToggleState = toggleState;
chkWebsocketConnected.ForeColor = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor2 = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.Gray;
changeCheckboxState.Stop();
changeCheckboxState.Start();
}
}
private void ChangeCheckboxState(object source, ElapsedEventArgs e)
{
chkWebsocketConnected.ToggleState = ToggleState.Indeterminate;
chkWebsocketConnected.ForeColor = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.BackColor2 = Color.Gray;
chkWebsocketConnected.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.Gray;
}
#region EVENTS
public class AlertRequiredEventArgs : EventArgs
{
public DataforVehList gridData { get; set; }
}
public delegate void AlertRequired(AlertRequiredEventArgs e);
public event AlertRequired OnAlertRequiredReceived;
#endregion
}
/// <summary>
/// Comparer class in order to sort the units list based on custom filters.
/// For time interval, the 'never reported' group will remain at the bottom
/// </summary>
public class CustomGroupComparer : IComparer<Group<GridViewRowInfo>>
{
//public GroupType groupType;
//public ListSortDirection sortDirection;
/*
public GroupComparer(GroupType type, ListSortDirection direction)
{
this.groupType = type;
this.sortDirection = direction;
}*/
public int Compare(Group<GridViewRowInfo> x, Group<GridViewRowInfo> y)
{
try
{
if (x == null || x.Key == null || y == null || y.Key == null)
return 0;
if (LiveTab.groupType == GroupType.GROUPNAME)
{
if (LiveTab.sortDirection == ListSortDirection.Ascending)
return x.Key.ToString().CompareTo(y.Key.ToString());
else
return (-1) * x.Key.ToString().CompareTo(y.Key.ToString());
}
else if (LiveTab.groupType == GroupType.STATUS)
{
if (LiveTab.sortDirection == ListSortDirection.Ascending)
return x.Key.ToString().CompareTo(y.Key.ToString());
else
return (-1) * x.Key.ToString().CompareTo(y.Key.ToString());
}
else if (LiveTab.groupType == GroupType.POSITIONTIMEAGO)
{
string xKey = "";
string yKey = "";
// get date for first group an second
if (x.Key != null)
xKey = x.Key.ToString();
if (y.Key != null)
yKey = y.Key.ToString();
DateTime dx = GetDateTimeFromAgo(xKey.ToString(), LiveTab.sortDirection);
DateTime dy = GetDateTimeFromAgo(yKey.ToString(), LiveTab.sortDirection);
if (LiveTab.sortDirection == ListSortDirection.Ascending)
return dx.CompareTo(dy);
else
return (-1) * dx.CompareTo(dy);
}
return x.Key.ToString().CompareTo(y.Key.ToString());
}
catch (Exception ex)
{
Utils.WriteLine("Grouping exception: " + ex.ToString());
if (LiveTab.sortDirection == ListSortDirection.Ascending)
return 1;
else
return -1;
}
}
/// <summary>
/// Try to recover the day that the ago time indicates. Only thing that needs
/// to be keep in mind is that the never reported will be way in past or in future
/// depending on the sorting direction
/// </summary>
/// <param name="agoTime">String which is a string representation of the day
/// with ago function</param>
/// <returns></returns>
private DateTime GetDateTimeFromAgo(string agoTime, ListSortDirection sortDirection)
{
if (agoTime.ToUpper().Equals(MainForm2.returnLNGString("neverReported").ToUpper()))
{
if (sortDirection == ListSortDirection.Descending)
return new DateTime(1970, 1, 1);
else
return new DateTime(2970, 1, 1);
}
else if (agoTime.ToUpper().Equals("scheduled") ||
agoTime.ToUpper().Equals("future_position"))
{
return new DateTime(2970, 1, 1);
}
else if (agoTime.ToUpper().Equals(MainForm2.returnLNGString("lessThan1Min").ToUpper()))
return DateTime.Now;
else
{
try
{
// split by space to find the day
string[] agoSplit = agoTime.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int timeUnit = 0;
// try and parse the days count which are located at the begining
// eg. 54 days ago
int.TryParse(agoSplit[0], out timeUnit);
if (agoSplit.Length == 1)
return DateTime.Now.AddDays(timeUnit * (-1));
else
{
if (agoSplit[1].ToUpper().StartsWith(MainForm2.returnLNGString("minute").ToUpper()))
return DateTime.Now.AddMinutes(timeUnit * (-1));
else if (agoSplit[1].ToUpper().StartsWith(MainForm2.returnLNGString("hour").ToUpper()))
return DateTime.Now.AddHours(timeUnit * (-1));
else
return DateTime.Now.AddDays(timeUnit * (-1));
}
}
catch (Exception ex)
{
if (sortDirection == ListSortDirection.Descending)
return new DateTime(1970, 1, 1);
else
return new DateTime(2970, 1, 1);
}
}
}
}
public sealed class GroupType
{
private readonly String name;
private readonly int value;
public static readonly GroupType POSITIONTIMEAGO = new GroupType(1, "PositionTimeAgo");
public static readonly GroupType STATUS = new GroupType(2, "Status");
public static readonly GroupType GROUPNAME = new GroupType(3, "GroupName");
public static readonly GroupType RADIOGATEWAY = new GroupType(4, "RadioGateway");
private GroupType(int value, String name)
{
this.name = name;
this.value = value;
}
public override String ToString()
{
return name;
}
}
}