using SafeMobileLib.MessageDecoders; using System; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Drawing.Imaging; using System.Net; using System.Threading.Tasks; using System.Net.NetworkInformation; using System.Collections.Specialized; using System.Runtime.InteropServices; using Newtonsoft.Json.Linq; using System.Collections.Generic; using Microsoft.Win32; using System.Net.Sockets; using System.Management.Automation.Runspaces; using System.Collections.ObjectModel; using System.Management.Automation; using System.Data; using System.ComponentModel; using System.IO; namespace SafeMobileLib { public class Utils { public static readonly String MBusUnicodeChar = "***<>"; public static bool isConsoleVisible = true; public static bool TimeWithMs = false; public static readonly String StolenArs = "stolen_ars"; public static readonly String StolenValidGPS = "stolen_valid_gps"; public static readonly String StolenNoGPSFix = "stolen_no_gps_fix"; public static List outputConsoleType = new List(){ConsoleType.ALL }; private static readonly object locker = new object(); /// /// Write a console message with the default console color /// which is Gray /// /// String which needs to be displayed on the console public static void WriteLine(string str) { WriteLine(str, ConsoleColor.Gray, ConsoleType.ALL); } public static void WriteLine(string str, ConsoleColor color) { WriteLine(str, color, ConsoleType.ALL); } public static void WriteLine(string str, ConsoleType type) { WriteLine(str, ConsoleColor.Gray, type); } public static void WriteLine(string str, ConsoleColor color, ConsoleType type) { // do not display the console message if not required if (!outputConsoleType.Contains(ConsoleType.ALL) && !outputConsoleType.Contains(type)) return; if (isConsoleVisible) { lock (locker) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write(String.Format("[### {0:H:mm:ss" + (TimeWithMs ? ".ffffff" : "") + "} ###] ", DateTime.Now)); Console.ForegroundColor = color; Console.Write(String.Format("{0}\n", str)); Console.ForegroundColor = ConsoleColor.Gray; } } if (LOGS.WRITE_LOGS) { if (color == ConsoleColor.Red) LOGS.LOG_Error(str); else LOGS.LOG(str); } } public static void Write(string str, ConsoleType type) { Write(str, ConsoleColor.Gray, type); } public static void Write(string str, ConsoleColor color, ConsoleType type) { // do not display the console message if not required if (!outputConsoleType.Contains(ConsoleType.ALL) && !outputConsoleType.Contains(type)) return; lock (locker) { Console.ForegroundColor = color; Console.Write(String.Format("{0}", str)); Console.ForegroundColor = ConsoleColor.Gray; } if (LOGS.WRITE_LOGS) { if (color == ConsoleColor.Red) LOGS.LOG_Error(str); else LOGS.LOG(str); } } /// /// Write an event log into the system's Event Log /// /// Application name which is the source of the event /// Content of the event log /// Type of the event which needs to be inserted /// An id of the event to filter better the events public static void WriteEventLog(String source, String content, EventLogEntryType type, Int32 eventId) { try { if (!EventLog.SourceExists(source)) EventLog.CreateEventSource(source, "Application"); EventLog.WriteEntry(source, content, type, eventId); } catch (Exception ex) { Utils.WriteLine("Could not write to event log :" + ex.ToString(), ConsoleColor.Red); } } public static string Byte2String(byte[] data, int startIndex, int len) { string sdata = ""; int i; if (startIndex > data.Length) return ""; for (i = startIndex; i < startIndex + len && i < data.Length; i++) { int ii; ii = (int)data[i]; sdata += "0x" + ii.ToString("X") + " "; } return sdata; } public static String ID2IP(string p_CAI, string p_radioIP) { uint radioID = Convert.ToUInt32(p_radioIP); if (radioID > 255 * 255 * 255) throw new Exception("Radio ID out of range"); byte c = (byte)(radioID & 0x0000FF); byte b = (byte)((radioID & 0x00FF00) >> 8); byte a = (byte)((radioID & 0xFF0000) >> 16); String toReturn = "" + p_CAI + "." + a + "." + b + "." + c; return toReturn; } public static string PrintBytesArray(Byte[] receivedBytes) { String result = ""; for (int i = 0; i < receivedBytes.Length; i++) { result = String.Format("{0}0x{1:X} ", result, receivedBytes[i]); } return result; } public static byte[] ID2ByteARR(string p_CAI, string p_radioIP) { byte[] arr = new byte[4]; uint radioID = Convert.ToUInt32(p_radioIP); if (radioID > 255 * 255 * 255) throw new Exception("Radio ID out of range"); arr[0] = Convert.ToByte(p_CAI); arr[3] = (byte)(radioID & 0x0000FF); arr[2] = (byte)((radioID & 0x00FF00) >> 8); arr[1] = (byte)((radioID & 0xFF0000) >> 16); return arr; } public static string ConvertBytesToString(Byte[] receivedBytes) { string response = ""; for (int i = 0; i < receivedBytes.Length; i++) { response = String.Format("{0}{1}", response, (char)receivedBytes[i]); } return response; } public static Int32 GetSecondsLocalFromDT(DateTime param) { System.DateTime datetime = param; long nOfSeconds; System.DateTime dt70 = new DateTime(1970, 1, 1, 0, 0, 0, 0); System.DateTime dttmp1 = new DateTime(1970, 1, 1, 0, 0, 0, 0); System.DateTime dttmp2; dttmp2 = dttmp1.ToLocalTime(); TimeSpan span2 = dttmp2 - dttmp1; TimeSpan span = datetime - dt70; if (System.TimeZone.CurrentTimeZone.IsDaylightSavingTime(param)) nOfSeconds = (long)span.TotalSeconds - (long)span2.TotalSeconds - 3600; //mai scot o ora - 3600 else nOfSeconds = (long)span.TotalSeconds - (long)span2.TotalSeconds; return ((Int32)nOfSeconds); } public static Byte[] createLocationMessage(int opCode, string suid, String[] dataString) { string msg = ""; msg = "#1." + GetSecondsLocalFromDT(DateTime.Now).ToString() + DateTime.Now.Millisecond.ToString() + "#" + opCode + "#" + suid + "#"; msg = msg + dataString[0] + "#" + dataString[1] + "#" + dataString[2] + "#" + dataString[3]; int totalSize = 5 + msg.Length; string sizeMsg = String.Format("#{0:000}", totalSize); msg = sizeMsg + msg; Byte[] toSendMulticast = new Byte[totalSize]; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); Byte[] toSendMulticastPartial = encoding.GetBytes(msg); for (int i = 0; i < toSendMulticastPartial.Length; i++) { toSendMulticast[i] = toSendMulticastPartial[i]; } toSendMulticast[totalSize - 1] = 35;//'#' return toSendMulticast; } public static Byte[] createMulticastMessage(int opCode, string suid, Byte[] dataBytes) { string partialMsg = "#1." + GetSecondsLocalFromDT(DateTime.Now).ToString() + DateTime.Now.Millisecond.ToString() + "#" + opCode + "#" + suid + "#"; int totalSize = 4 + partialMsg.Length + dataBytes.Length + 1;// string sizeMsg = String.Format("#{0:000}", totalSize); partialMsg = sizeMsg + partialMsg; Byte[] toSendMulticast = new Byte[totalSize]; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); Byte[] toSendMulticastPartial = encoding.GetBytes(partialMsg); for (int j = 0; j < toSendMulticastPartial.Length; j++) toSendMulticast[j] = toSendMulticastPartial[j]; for (int i = 0; i < dataBytes.Length; i++) { toSendMulticast[partialMsg.Length + i] = dataBytes[i]; //data } toSendMulticast[totalSize - 1] = 35;//'#' return toSendMulticast; } public static bool isRightToLeft(string message) { int hasRandALCat = 0; foreach(char c in message) { if (c >= 0x5BE && c <= 0x10B7F) { if (c <= 0x85E) { if (c == 0x5BE) hasRandALCat = 1; else if (c == 0x5C0) hasRandALCat = 1; else if (c == 0x5C3) hasRandALCat = 1; else if (c == 0x5C6) hasRandALCat = 1; else if (0x5D0 <= c && c <= 0x5EA) hasRandALCat = 1; else if (0x5F0 <= c && c <= 0x5F4) hasRandALCat = 1; else if (c == 0x608) hasRandALCat = 1; else if (c == 0x60B) hasRandALCat = 1; else if (c == 0x60D) hasRandALCat = 1; else if (c == 0x61B) hasRandALCat = 1; else if (0x61E <= c && c <= 0x64A) hasRandALCat = 1; else if (0x66D <= c && c <= 0x66F) hasRandALCat = 1; else if (0x671 <= c && c <= 0x6D5) hasRandALCat = 1; else if (0x6E5 <= c && c <= 0x6E6) hasRandALCat = 1; else if (0x6EE <= c && c <= 0x6EF) hasRandALCat = 1; else if (0x6FA <= c && c <= 0x70D) hasRandALCat = 1; else if (c == 0x710) hasRandALCat = 1; else if (0x712 <= c && c <= 0x72F) hasRandALCat = 1; else if (0x74D <= c && c <= 0x7A5) hasRandALCat = 1; else if (c == 0x7B1) hasRandALCat = 1; else if (0x7C0 <= c && c <= 0x7EA) hasRandALCat = 1; else if (0x7F4 <= c && c <= 0x7F5) hasRandALCat = 1; else if (c == 0x7FA) hasRandALCat = 1; else if (0x800 <= c && c <= 0x815) hasRandALCat = 1; else if (c == 0x81A) hasRandALCat = 1; else if (c == 0x824) hasRandALCat = 1; else if (c == 0x828) hasRandALCat = 1; else if (0x830 <= c && c <= 0x83E) hasRandALCat = 1; else if (0x840 <= c && c <= 0x858) hasRandALCat = 1; else if (c == 0x85E) hasRandALCat = 1; } else if (c == 0x200F) hasRandALCat = 1; else if (c >= 0xFB1D) { if (c == 0xFB1D) hasRandALCat = 1; else if (0xFB1F <= c && c <= 0xFB28) hasRandALCat = 1; else if (0xFB2A <= c && c <= 0xFB36) hasRandALCat = 1; else if (0xFB38 <= c && c <= 0xFB3C) hasRandALCat = 1; else if (c == 0xFB3E) hasRandALCat = 1; else if (0xFB40 <= c && c <= 0xFB41) hasRandALCat = 1; else if (0xFB43 <= c && c <= 0xFB44) hasRandALCat = 1; else if (0xFB46 <= c && c <= 0xFBC1) hasRandALCat = 1; else if (0xFBD3 <= c && c <= 0xFD3D) hasRandALCat = 1; else if (0xFD50 <= c && c <= 0xFD8F) hasRandALCat = 1; else if (0xFD92 <= c && c <= 0xFDC7) hasRandALCat = 1; else if (0xFDF0 <= c && c <= 0xFDFC) hasRandALCat = 1; else if (0xFE70 <= c && c <= 0xFE74) hasRandALCat = 1; else if (0xFE76 <= c && c <= 0xFEFC) hasRandALCat = 1; else if (0x10800 <= c && c <= 0x10805) hasRandALCat = 1; else if (c == 0x10808) hasRandALCat = 1; else if (0x1080A <= c && c <= 0x10835) hasRandALCat = 1; else if (0x10837 <= c && c <= 0x10838) hasRandALCat = 1; else if (c == 0x1083C) hasRandALCat = 1; else if (0x1083F <= c && c <= 0x10855) hasRandALCat = 1; else if (0x10857 <= c && c <= 0x1085F) hasRandALCat = 1; else if (0x10900 <= c && c <= 0x1091B) hasRandALCat = 1; else if (0x10920 <= c && c <= 0x10939) hasRandALCat = 1; else if (c == 0x1093F) hasRandALCat = 1; else if (c == 0x10A00) hasRandALCat = 1; else if (0x10A10 <= c && c <= 0x10A13) hasRandALCat = 1; else if (0x10A15 <= c && c <= 0x10A17) hasRandALCat = 1; else if (0x10A19 <= c && c <= 0x10A33) hasRandALCat = 1; else if (0x10A40 <= c && c <= 0x10A47) hasRandALCat = 1; else if (0x10A50 <= c && c <= 0x10A58) hasRandALCat = 1; else if (0x10A60 <= c && c <= 0x10A7F) hasRandALCat = 1; else if (0x10B00 <= c && c <= 0x10B35) hasRandALCat = 1; else if (0x10B40 <= c && c <= 0x10B55) hasRandALCat = 1; else if (0x10B58 <= c && c <= 0x10B72) hasRandALCat = 1; else if (0x10B78 <= c && c <= 0x10B7F) hasRandALCat = 1; } } } return hasRandALCat == 1; } /// /// Check if the application is already running in order to prevent it from running multiple /// public static bool testIfAlreadyRunning() { Process[] processlist = Process.GetProcesses(); Process curentP = Process.GetCurrentProcess(); int count = 0; foreach (Process theprocess in processlist) { if (theprocess.ProcessName.Equals(curentP.ProcessName) && !curentP.ProcessName.Contains("vshost")) { count++; } } if (count > 1) { return true; } return false; } private const int SW_SHOW = 5; private const int SW_RESTORE = 9; private const int SW_SHOWMAXIMIZED = 3; private const int SW_SHOWNORMAL = 1; [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern bool SetForegroundWindow(IntPtr hwnd); public static bool testIfAlreadyRunning(bool b) { Process currentProcess = Process.GetCurrentProcess(); var runningProcess = (from process in Process.GetProcesses() where process.Id != currentProcess.Id && process.ProcessName.Equals( currentProcess.ProcessName, StringComparison.Ordinal) select process).FirstOrDefault(); if (!currentProcess.ProcessName.Contains("vshost")) { if (runningProcess != null) { var hWnd = runningProcess.MainWindowHandle; // Code to display a window regardless of its current state ShowWindow(hWnd, SW_SHOW); // Make the window visible if it was hidden ShowWindow(hWnd, SW_RESTORE); // Next, restore it if it was minimized SetForegroundWindow(hWnd); // Finally, activate the window return true; } } return false; } public static int GetDBidFromSUID(string suid) { int DBid = -1; //add data to ht_SUInfo lock (SN_Queues.ht_SUInfo.SyncRoot) { if (SN_Queues.ht_SUInfo != null) { if (SN_Queues.ht_SUInfo.ContainsKey(suid)) DBid = ((SUinfo)SN_Queues.ht_SUInfo[suid]).DBid; } } return DBid; } public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) { // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp); return dtDateTime; } public static byte[] Convert_text_For_multicast(String Cmd_in) { String cmdok = Cmd_in; Int32 tmp = cmdok.Length + 1; tmp += tmp.ToString().Length; String TMPcmdok = "#" + tmp.ToString() + cmdok; if (tmp != TMPcmdok.Length) cmdok = "#" + TMPcmdok.Length + cmdok; else cmdok = TMPcmdok; System.Text.Encoding enc = System.Text.Encoding.ASCII; byte[] buf = enc.GetBytes(cmdok); return buf; } public static byte[] Convert_text_For_multicast(String Cmd_in, out String Cmd_out) { String cmdok = Cmd_in; Int32 tmp = cmdok.Length + 1; tmp += tmp.ToString().Length; String TMPcmdok = "#" + tmp.ToString() + cmdok; if (tmp != TMPcmdok.Length) cmdok = "#" + TMPcmdok.Length + cmdok; else cmdok = TMPcmdok; Cmd_out = cmdok; System.Text.Encoding enc = System.Text.Encoding.ASCII; byte[] buf = enc.GetBytes(cmdok); return buf; } /// /// Class equal with an enum containing a string as a returned value /// public sealed class TicketingStatuses { private readonly String name; private readonly int value; private readonly Color color; public static readonly TicketingStatuses ASSIGNED = new TicketingStatuses(1, "Assigned", Color.FromArgb(61, 133, 132)); public static readonly TicketingStatuses ACCEPTED = new TicketingStatuses(2, "Accepted", Color.FromArgb(61, 113, 113)); public static readonly TicketingStatuses IN_PROGRESS = new TicketingStatuses(3, "In progress", Color.FromArgb(61, 91, 133)); public static readonly TicketingStatuses COMPLETED = new TicketingStatuses(4, "Completed", Color.FromArgb(94, 133, 61)); public static readonly TicketingStatuses REJECTED = new TicketingStatuses(5, "Rejected", Color.FromArgb(169, 61, 71)); public static readonly TicketingStatuses OVERDUE = new TicketingStatuses(6, "Overdue", Color.FromArgb(178, 159, 61)); private TicketingStatuses(int value, String name, Color color) { this.name = name; this.value = value; this.color = color; } public override String ToString() { return name; } public static Color GetTicketStatusColor(String ticketStatus) { if (ticketStatus.Equals(ASSIGNED.ToString())) return ASSIGNED.color; else if (ticketStatus.Equals(ACCEPTED.ToString())) return ACCEPTED.color; else if (ticketStatus.Equals(IN_PROGRESS.ToString())) return IN_PROGRESS.color; else if (ticketStatus.Equals(COMPLETED.ToString())) return COMPLETED.color; else if (ticketStatus.Equals(REJECTED.ToString())) return REJECTED.color; else if (ticketStatus.Equals(OVERDUE.ToString())) return OVERDUE.color; return Color.FromArgb(178, 159, 61); } } /// /// Resize an image keeping the aspect ratio of the image /// /// Image which needs to be resized /// Maximum allowed width for this image /// Maximum allowed height for this image /// The resized image public static Image ScaleImage(Image image, int maxWidth, int maxHeight) { var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight); return newImage; } /// /// Convert a bitmap to a grayscale one. This is done using a ColorMatrix /// /// Bitmap which needs to be converted to a /// grayscale one /// The converted grayscale image public static Bitmap MakeGrayscale3(Bitmap original, float opacity) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][] { new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, opacity, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); return newBitmap; } public static Bitmap MakeTransparent(Bitmap original, float opacity) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][] { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, opacity, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); return newBitmap; } /// /// Convert a bitmap to a grayscale one. This is done using a ColorMatrix /// /// Bitmap which needs to be converted to a /// grayscale one /// The converted grayscale image public static Bitmap ChangeColor(Bitmap original, Color color) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image using (Graphics gr = Graphics.FromImage(newBitmap)) { float r = (float)((1.0 / 256) * color.R);// / 256; float g = (float)((1.0 / 256) * color.G);// / 256; float b = (float)((1.0 / 256) * color.B);// / 256; // create a color matrix in order to change the color float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // Red scaling [multiply] new float[] {0, 1, 0, 0, 0}, // Green scaling [multiply] new float[] {0, 0, 1, 0, 0}, // Blue scaling [multiply] new float[] {r, g, b, 1, 0}, // this will add values to R,G,B,A new float[] {0, 0, 0, 0, 1}}; // three translations of 0.2 //create some image attributes ImageAttributes attributes = new ImageAttributes(); ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); //set the color matrix attribute attributes.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //draw the original image on the new image //using the grayscale color matrix gr.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); } return newBitmap; } /// /// Convert a bitmap to a grayscale one. This is done using a ColorMatrix /// /// Bitmap which needs to be converted to a /// grayscale one /// The converted grayscale image public static Bitmap ChangeColorEmergency(Bitmap original, Color color) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image using (Graphics gr = Graphics.FromImage(newBitmap)) { float r = (float)((1.0 / 256) * color.R);// / 256; float g = (float)((1.0 / 256) * color.G);// / 256; float b = (float)((1.0 / 256) * color.B);// / 256; // create a color matrix in order to change the color float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // Red scaling [multiply] new float[] {0, 1, 0, 0, 0}, // Green scaling [multiply] new float[] {0, 0, 1, 0, 0}, // Blue scaling [multiply] new float[] {r, g, b, 1, 0}, // this will add values to R,G,B,A new float[] {0, 0, 0, 0, 1}}; // three translations of 0.2 //create some image attributes ImageAttributes attributes = new ImageAttributes(); ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); //set the color matrix attribute attributes.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //draw the original image on the new image //using the grayscale color matrix gr.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); } return newBitmap; } /// /// Get a text representation for the date time representing /// the difference in minutes/hours/days from now /// /// DateTime value which needs to be converted /// String 'Ago' representation fot he date public static string GetDateTimeAgo(DateTime time) { String timeValue = ""; if (time.Year < 2000) return "never reported fix gps"; Int64 secondsDifference = (Int64)((DateTime.Now.Subtract(time)).TotalSeconds); if (secondsDifference < 0) { timeValue = "scheduled"; } else if (secondsDifference < 60) timeValue = "less than 1 minute"; else if (secondsDifference < 3600) timeValue = (secondsDifference / 60) + " minute" + ((secondsDifference / 60) > 1 ? "s" : "") + " ago"; else if (secondsDifference < 7200) timeValue = "1 hour ago"; else if (secondsDifference < 86400) { timeValue = (secondsDifference / 3600) + " hours ago"; } else { timeValue = (secondsDifference / 86400) + " days ago"; } return timeValue; } /// /// Verify if an email address is a valid email address, in therm of /// well written, with '@' and '.' in the wright place /// /// Email which needs to be checked /// True if the email is a valid one, or false otherwise public static bool IsValidEmail(string email) { bool isEmail = Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); return isEmail; } public static Status_for_tab GetStatusFromDisplayString(string status) { if (status.Trim().Equals("OFF")) return Status_for_tab.OFF; else if (status.Trim().Equals("ON")) return Status_for_tab.ON; else if (status.Trim().Equals("GPS ON")) return Status_for_tab.GPS_ON; else if (status.Trim().Equals("GPS POOR")) return Status_for_tab.GPS_POOR; else if (status.Trim().Equals("GPS OFF")) return Status_for_tab.GPS_OFF; else if (status.Trim().Equals("NO GPS FIX")) return Status_for_tab.NOGPSFIX; else if (status.Trim().Equals("Enabled")) return Status_for_tab.ENABLE; else if (status.Trim().Equals("Disabled")) return Status_for_tab.DISABLE; else if (status.Trim().Equals("EMERGENCY")) return Status_for_tab.EMERG; else if (status.Trim().Equals("MADE OFF")) return Status_for_tab.MADEOFF; else if (status.Trim().Equals("MADE ON")) return Status_for_tab.MADEON; else { Utils.WriteLine("UNKNOWN STATUS: " + status, ConsoleColor.Yellow); return Status_for_tab.UNKNOW; } } public static String GetStatusFromInt(int status) { String Statusforgrid = "OFF"; Status_for_tab foo = (Status_for_tab)status; switch (foo) { case Status_for_tab.DISABLE: Statusforgrid = "Disabled"; break; case Status_for_tab.ENABLE: Statusforgrid = "Enabled"; break; case Status_for_tab.ON: Statusforgrid = "ON"; break; case Status_for_tab.OFF: Statusforgrid = "OFF"; break; case Status_for_tab.GPS_ON: Statusforgrid = "GPS ON"; break; case Status_for_tab.GPS_POOR: Statusforgrid = "GPS POOR"; break; case Status_for_tab.GPS_OFF: Statusforgrid = "GPS OFF"; break; case Status_for_tab.NOGPSFIX: Statusforgrid = "NO GPS FIX"; break; case Status_for_tab.EMERG: Statusforgrid = "EMERGENCY"; break; case Status_for_tab.MADEOFF: Statusforgrid = "MADE OFF"; break; case Status_for_tab.MADEON: Statusforgrid = "MADE ON"; break; } return Statusforgrid; } public static string Compute4digitALG(double lat, double lng) { string ret = ""; ret = String.Format("{0:0.0000}", lat) + String.Format("{0:0.0000}", lng); return ret; } /// /// Class equal with an enum containing a string as a returned value /// public sealed class Direction { private readonly String name; private readonly int value; public static readonly Direction E = new Direction(1, "E"); public static readonly Direction ENE = new Direction(2, "ENE"); public static readonly Direction NE = new Direction(3, "NE"); public static readonly Direction NNE = new Direction(4, "NNE"); public static readonly Direction N = new Direction(5, "N"); public static readonly Direction NNW = new Direction(6, "NNW"); public static readonly Direction NW = new Direction(7, "NW"); public static readonly Direction WNW = new Direction(8, "WNW"); public static readonly Direction W = new Direction(9, "W"); public static readonly Direction WSW = new Direction(10, "WSW"); public static readonly Direction SW = new Direction(11, "SW"); public static readonly Direction SSW = new Direction(12, "SSW"); public static readonly Direction S = new Direction(13, "S"); public static readonly Direction SSE = new Direction(14, "SSE"); public static readonly Direction SE = new Direction(15, "SE"); public static readonly Direction ESE = new Direction(16, "ESE"); public static readonly Direction UNKNOWN = new Direction(17, "UNKNOWN"); private Direction(int value, String name) { this.name = name; this.value = value; } public override String ToString() { return name; } /// /// Get the direction from a string representation of it /// /// String containing the direction name /// Direction object public static Direction GetDirection(String direction) { if (direction.Equals(E.ToString())) return E; else if (direction.Equals(ENE.ToString())) return ENE; else if (direction.Equals(NE.ToString())) return NE; else if (direction.Equals(NNE.ToString())) return NNE; else if (direction.Equals(N.ToString())) return N; else if (direction.Equals(NNW.ToString())) return NNW; else if (direction.Equals(NW.ToString())) return NW; else if (direction.Equals(WNW.ToString())) return WNW; else if (direction.Equals(W.ToString())) return W; else if (direction.Equals(WSW.ToString())) return WSW; else if (direction.Equals(SW.ToString())) return SW; else if (direction.Equals(SSW.ToString())) return SSW; else if (direction.Equals(S.ToString())) return S; else if (direction.Equals(SSE.ToString())) return SSE; else if (direction.Equals(SE.ToString())) return SE; else if (direction.Equals(ESE.ToString())) return ESE; return UNKNOWN; } } /// /// Get the direction of where the unit is heading based on the degree /// /// Direction expressed in degrees /// Direction as a Direction object public static Direction GetDirection(Int32 degree) { if (((degree >= 0) && (degree < 11.25)) || ((degree > 348.75) && (degree <= 360))) return Direction.E; else if ((degree >= 11.25) && (degree < 33.75)) return Direction.ENE; else if ((degree >= 33.75) && (degree < 56.25)) return Direction.NE; else if ((degree >= 56.25) && (degree < 78.75)) return Direction.NNE; else if ((degree >= 78.75) && (degree < 101.25)) return Direction.N; else if ((degree >= 101.25) && (degree < 123.75)) return Direction.NNW; else if ((degree >= 123.75) && (degree < 146.25)) return Direction.NW; else if ((degree >= 146.25) && (degree < 168.75)) return Direction.WNW; else if ((degree >= 168.75) && (degree < 191.25)) return Direction.W; else if ((degree >= 191.25) && (degree < 213.75)) return Direction.WSW; else if ((degree >= 213.75) && (degree < 236.25)) return Direction.SW; else if ((degree >= 236.25) && (degree < 258.75)) return Direction.SSW; else if ((degree >= 258.75) && (degree < 281.25)) return Direction.S; else if ((degree >= 281.25) && (degree < 303.75)) return Direction.SSE; else if ((degree >= 303.75) && (degree < 326.25)) return Direction.SE; else if ((degree >= 326.25) && (degree < 348.75)) return Direction.ESE; return Direction.UNKNOWN; } public static String getDayCustomFormat(bool is24hours, bool dayFirst) { string returnDateType = null; returnDateType = is24hours ? (dayFirst ? "dd/MM/yyyy HH:mm" : "MM/dd/yyyy HH:mm") : (dayFirst ? "dd/MM/yyyy hh:mm tt" : "MM/dd/yyyy hh:mm tt"); return returnDateType; } public static void SetAlpha(Bitmap bmp, byte alpha) { if (bmp == null) throw new ArgumentNullException("bmp"); var data = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); var line = data.Scan0; var eof = line + data.Height * data.Stride; while (line != eof) { var pixelAlpha = line + 3; var eol = pixelAlpha + data.Width * 4; while (pixelAlpha != eol) { System.Runtime.InteropServices.Marshal.WriteByte( pixelAlpha, alpha); pixelAlpha += 4; } line += data.Stride; } bmp.UnlockBits(data); } public static async Task CallWebServerAsync(string address) { return await Task.Run(() => CallWebServer(address)); } public static string CallWebServer(string address) { string ret = "not_available"; try { //direct link without credentials Uri myUri; if (Uri.TryCreate(address, UriKind.RelativeOrAbsolute, out myUri)) { WebClient wc = new WebClient(); String s = wc.DownloadString(address); WriteLine("Web Server Response: " + s, ConsoleColor.Yellow); ret = s; } } catch { WriteLine("Web Server not available!!!", ConsoleColor.Red); } return ret; } public static async Task GetWebServerAddressAsync() { return await Task.Run(() => GetWebServerAddress()); } public static string GetWebServerAddress() { string ret = "not_available"; try { //2. 192.168.226.128 Utils.WriteLine($"Testing 192.168.226.128..."); ret = CallWebServer("http://192.168.226.128:41414/status"); if (ret == "not_available") { //3. http://linx-server.local Utils.WriteLine($"Testing linx-server.local..."); ret = CallWebServer("http://linx-server.local:41414/status"); if (ret == "not_available") { string myIp = UdpMulticast.getPreferedIPAdress().ToString(); string[] ip = myIp.Split('.'); string baseIP = $"{ip[0]}.{ip[1]}.{ip[2]}"; //4. scan lan range :41414/status for (int i = 1; i <= 255; i++) { string req_ip = $"{baseIP}.{i}"; Utils.WriteLine($"Testing IP {req_ip}..."); if (!PingHost(req_ip)) continue; string request = $"http://{req_ip}:41414/status"; ret = CallWebServer(request); if (ret != "not_available") { if (parseResponse(ret)) break; } } } } } catch { WriteLine("Web Server not available!!!", ConsoleColor.Red); } return ret; } private static bool parseResponse(string response) { bool ret = false; try { JObject o = JObject.Parse(response); string lanIP = o["data"]["network"]["privateIp"].ToString(); string rtpstart = o["data"]["ports"]["rtpstart"].ToString(); string rtpend = o["data"]["ports"]["rtpend"].ToString(); string publicIp = o["data"]["network"]["publicIp"].ToString(); string sipPort = o["data"]["ports"]["udpbindaddr"].ToString().Split(':')[1]; ret = true; } catch { Utils.WriteLine("Error on parse server response!", ConsoleColor.Red); } return ret; } public static bool PingHost(string nameOrAddress) { bool pingable = false; Ping pinger = new Ping(); try { PingReply reply = pinger.Send(nameOrAddress); pingable = reply.Status == IPStatus.Success; } catch (PingException) { // Discard PingExceptions and return false; } return pingable; } public static async Task PostRequestAsync(string url, NameValueCollection data) { return await Task.Run(() => PostRequest(url, data)); } public static bool PostRequest(string url, NameValueCollection data) { Utils.WriteLine($"Post request url: {url}", ConsoleColor.Cyan); bool ret = false; string retString = ""; using (var wb = new WebClient()) { var response = wb.UploadValues(url, "POST", data); retString = Encoding.ASCII.GetString(response); } return ret; } /// /// Gets the path to SafeMobile foder /// /// /// /// public static String GetRegValue(String regKey, String appFolder) { // Write path to the registry string path = "Software\\" + "SafeMobile" + (appFolder.Equals("SafeMobile") ? "" : "\\" + appFolder); RegistryKey key = Registry.CurrentUser.OpenSubKey(path); if (key != null) { try { return (String)key.GetValue(regKey); } catch (Exception) { return String.Empty; } } else { // Key is not in HKEY_CURRENT_USER /SOFTWARE /SafeMobile // Because of registry virtualization, it may be in HKEY_USERS/ SomeUser / SOFTWARE / .... // Check all users key form HKEY_USERS foreach (string user in Registry.Users.GetSubKeyNames()) { key = Registry.Users.OpenSubKey(user + "\\" + path); if (key != null) { try { return (String)key.GetValue(regKey); } catch (Exception) { return String.Empty; } } } return String.Empty; } } public static string GetIP() { string localIP; try { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); return localIP; } } catch { return "127.0.0.1"; } } public static bool PowershellScript(string scriptText, string resultText) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptText); // add an extra command to transform the script output objects into nicely formatted strings // remove this line to get the actual objects that the script returns. For example, the script // "Get-Process" returns a collection of System.Diagnostics.Process instances. pipeline.Commands.Add("Out-String"); // execute the script Collection results = pipeline.Invoke(); // close the runspace runspace.Close(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } return stringBuilder.ToString().Trim().Contains(resultText); } public static bool PowershellScript(string scriptText) { return PowershellScript(scriptText, "True"); } public static string enumConvertToString(Enum e) { string Text = Convert.ToInt32(e).ToString(); return Text; } public static DataTable ToEmptyDataTable() { DataTable table = new DataTable(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } return table; } public static void HeaderToCsv(StreamWriter sw, List excludeColumns) { char separator = ','; char replacer = ';'; PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); for (int i = 0; i < props.Count; i++) { if (excludeColumns.Contains(props[i].Name)) continue; PropertyDescriptor prop = props[i]; sw.Write(prop.Name.Replace(separator, replacer)); if (i < props.Count - 1) sw.Write(separator); } sw.Write(Environment.NewLine); } public static void RowToCsv(StreamWriter sw, T obj, List excludeColumns) { char separator = ','; char replacer = ';'; PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); for (int i = 0; i < props.Count; i++) { if (excludeColumns.Contains(props[i].Name)) continue; String value = props[i].GetValue(obj).ToString(); sw.Write(value.Replace(separator, replacer)); if (i < props.Count - 1) sw.Write(separator); } sw.Write(Environment.NewLine); } public static void DataTable_HeaderToCsvFile(System.IO.StreamWriter sw, DataTable dt) { char separator = ','; char replacer = ';'; int columnCount = dt.Columns.Count; for (int i = 0; i < columnCount; i++) { sw.Write(dt.Columns[i].ToString().Replace(separator, replacer)); if (i < columnCount - 1) sw.Write(separator); } sw.Write(Environment.NewLine); } public static void DataTable_RowToCsvFile(System.IO.StreamWriter sw, DataRow dr) { char separator = ','; char replacer = ';'; int columnCount = dr.Table.Columns.Count; for (int i = 0; i < columnCount; i++) { if (!Convert.IsDBNull(dr[i])) sw.Write(dr[i].ToString().Replace(separator, replacer)); if (i < columnCount - 1) sw.Write(separator); } sw.Write(Environment.NewLine); } public static void DataTableToCsvFile(DataTable dataTable, string filePath, bool includeHeaders = true) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false)) { //================ // write header //================ if (includeHeaders) { DataTable_HeaderToCsvFile(sw, dataTable); } //================ // write rows //================ foreach (DataRow dr in dataTable.Rows) { DataTable_RowToCsvFile(sw, dr); } } } } public class Hyt_cmdMsg { public string m_suid; public int m_cmd; public string m_payload; } public enum Hyt_cmd { SET_REPORT_INTERVAL = 0x01, SEND_SMS = 0x02, SEND_POLL = 0x03 }; public class TallysmanLostLog { public Int64 RadioID { get; set; } public Int64 LogId { get; set; } public TallysmanLostLog() { RadioID = 0; LogId = 0; } } public class TallysmanMsg { public Int64 Id { get; set; } public String EventType { get; set; } public Int64 RadioID { get; set; } public Double EventTime { get; set; } public Double GPSFixTime { get; set; } public Double Speed { get; set; } public Double Latitude { get; set; } public Double Longitude { get; set; } public Double Altitude { get; set; } public Double LevelOfConfidence { get; set; } public Double Bearing { get; set; } public Double HorizontalAccuracy { get; set; } public Double VerticalAccuracy { get; set; } public Double Odometer { get; set; } public Int64 RunTime { get; set; } public Int64 IdleTime { get; set; } public Int32 VioStatus { get; set; } public Int32 VioChanged { get; set; } public Double AverageSpeed { get; set; } public Int64 WaypointId { get; set; } public String FirmwareVersion { get; set; } public Double RSSI { get; set; } public Int64 VitalId { get; set; } public Int64 LogId { get; set; } public TallysmanMsg() { Id = 0; EventType = "BUS_STOP"; RadioID = 0; GPSFixTime = 0; EventTime = 0; Speed = 0; Latitude = 0; Longitude = 0; Altitude = -1; LevelOfConfidence = -1; Bearing = -1; HorizontalAccuracy = 0; VerticalAccuracy = 0; Odometer = 0; RunTime = 0; IdleTime = 0; VioStatus = 0; VioChanged = 0; AverageSpeed = 0; WaypointId = 0; FirmwareVersion = ""; RSSI = 0; VitalId = 0; LogId = 0; } } public class ARSmsg { public string SUID; public string status; } public enum DebugMSG_Type { ARS, SMS, CTRL, ALL, POLL, always, DB, GPS, DEV, Email, Debug, Address, CFG, Routes, ALERTS, test, WIRELINE, LE } public enum ConsoleType { ARS, SMS, CTRL, ALL, POLL, DB, GPS, CFG, WIRELINE, LE, MB, OTHER, XNL, TELEMETRY, SDR } public class ConsoleArgs { public bool isARS = false; public bool isSMS = false; public bool isCTRL = false; public bool isALL = true; public bool isPOLL = false; public bool isDB = false; public bool isGPS = false; public bool isCFG = false; public bool isWIRELINE = false; public bool isLE = false; public bool isMB = false; public bool isLog = false; public ConsoleArgs() { } public bool IsArgActive(ConsoleType type) { if (type == ConsoleType.ALL && isALL) return true; else if (type == ConsoleType.ALL) return false; else if (type == ConsoleType.ARS && isARS) return true; else if (type == ConsoleType.ARS) return false; else if (type == ConsoleType.SMS && isSMS) return true; else if (type == ConsoleType.SMS) return false; else if (type == ConsoleType.CTRL && isCTRL) return true; else if (type == ConsoleType.CTRL) return false; else if (type == ConsoleType.POLL && isPOLL) return true; else if (type == ConsoleType.POLL) return false; else if (type == ConsoleType.DB && isDB) return true; else if (type == ConsoleType.DB) return false; else if (type == ConsoleType.GPS && isGPS) return true; else if (type == ConsoleType.GPS) return false; else if (type == ConsoleType.CFG && isCFG) return true; else if (type == ConsoleType.CFG) return false; else if (type == ConsoleType.WIRELINE && isWIRELINE) return true; else if (type == ConsoleType.WIRELINE) return false; else if (type == ConsoleType.LE && isLE) return true; else if (type == ConsoleType.LE) return false; else if (type == ConsoleType.MB && isMB) return true; else if (type == ConsoleType.MB) return false; return false; } } // Types of events received from the UI and options to open some windows public enum EventType { ALERT, CENTER, TEXT, TICKETING, DISPLAY, VOICE } // Types of alerts that can be set in the alerts tab public enum AdminAlerts { EMERGENCY, LONE_WORKER, EMERGENCY_SOUND, EMERGENCY_POPUP, GEOFENCE, LANDMARK, GEOFENCE_SOUND, GEOFENCE_POPUP, SPEED, SPEED_SOUND, SPEED_POPUP, ALARM_ON_EMAIL, TELEMETRY_SOUND, TELEMETRY_POPUP } public enum TelemetryAlerts { DIGITAL1, DIGITAL2, DIGITAL3, DIGITAL4, DIGITAL5 } }