App.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Windows;
  13. using System.Windows.Data;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using Comal.Classes;
  17. using InABox.Configuration;
  18. using InABox.Core;
  19. using InABox.Logging;
  20. using InABox.WPF;
  21. using InABox.WPF.Themes;
  22. using NDesk.Options;
  23. using PRSDesktop;
  24. using Syncfusion.Licensing;
  25. using Path = System.IO.Path;
  26. namespace PRSDesktop
  27. {
  28. /// <summary>
  29. /// Interaction logic for App.xaml
  30. /// </summary>
  31. public partial class App : Application
  32. {
  33. public static DatabaseSettings DatabaseSettings;
  34. public static AutoUpdateSettings AutoUpdateSettings;
  35. public static Guid EmployeeID = Guid.Empty;
  36. public static String EmployeeCode = "";
  37. public static String EmployeeName = "";
  38. public static String EmployeeEmail = "";
  39. public static string Profile { get; set; } = "";
  40. public static bool IsClosing { get; set; } = false;
  41. public static bool ShouldRestart { get; set; } = false;
  42. /*/ Guid to ensure that only one instance of PRS is running
  43. public static Guid AppGuid = Guid.Parse("237E8828-7F5A-4298-B311-CF0FC27882EC");
  44. private static Mutex AppMutex;*/
  45. private readonly OptionSet _commandLineParameters = new()
  46. {
  47. {
  48. "profile=",
  49. "",
  50. p => { Profile = p; }
  51. }
  52. };
  53. public App()
  54. {
  55. SyncfusionLicenseProvider.RegisterLicense(CoreUtils.SyncfusionLicense(SyncfusionVersion.v23_2));
  56. }
  57. private void AutoDiscover(Dictionary<string, DatabaseSettings> allsettings)
  58. {
  59. var confirm = MessageBox.Show("Try to configure Server Connection Automatically?", "Auto Discover", MessageBoxButton.YesNoCancel);
  60. if (confirm == MessageBoxResult.Yes)
  61. try
  62. {
  63. using (new WaitCursor())
  64. {
  65. AutoDiscoverySettings autodiscover;
  66. using (var client = new UdpClient())
  67. {
  68. client.Client.SendTimeout = 10000;
  69. client.Client.ReceiveTimeout = 20000;
  70. var requestData = Encoding.ASCII.GetBytes("");
  71. var serverEndPoint = new IPEndPoint(IPAddress.Any, 0);
  72. client.EnableBroadcast = true;
  73. client.Send(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888));
  74. var serverResponseData = client.Receive(ref serverEndPoint);
  75. var serverResponse = Encoding.ASCII.GetString(serverResponseData);
  76. autodiscover = Serialization.Deserialize<AutoDiscoverySettings>(serverResponse);
  77. client.Close();
  78. }
  79. var settings = new DatabaseSettings();
  80. settings.IsActive = true;
  81. settings.Logo = autodiscover.Logo;
  82. settings.Protocol = autodiscover.Protocol;
  83. settings.DatabaseType = DatabaseType.Networked;
  84. settings.URLs = autodiscover.URLs;
  85. settings.LibraryLocation = autodiscover.LibraryLocation;
  86. settings.GoogleAPIKey = autodiscover.GoogleAPIKey;
  87. allsettings[autodiscover.Name] = settings;
  88. new LocalConfiguration<DatabaseSettings>(autodiscover.Name).Save(settings);
  89. AutoUpdateSettings = new AutoUpdateSettings
  90. {
  91. Channel = autodiscover.UpdateChannel,
  92. Type = autodiscover.UpdateType,
  93. Location = autodiscover.UpdateLocation,
  94. Elevated = autodiscover.UpdateAdmin
  95. };
  96. new LocalConfiguration<AutoUpdateSettings>().Save(AutoUpdateSettings);
  97. MessageBox.Show($"Server found at {String.Join(";",autodiscover.URLs)}");
  98. }
  99. }
  100. catch
  101. {
  102. MessageBox.Show("No Server Found");
  103. }
  104. }
  105. private void MoveDirectory(string[] source, string target)
  106. {
  107. var stack = new Stack<Folders>();
  108. stack.Push(new Folders(source[0], target));
  109. while (stack.Count > 0)
  110. {
  111. var folders = stack.Pop();
  112. Directory.CreateDirectory(folders.Target);
  113. foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
  114. {
  115. var targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
  116. if (!File.Exists(targetFile))
  117. File.Move(file, targetFile);
  118. else
  119. File.Delete(file);
  120. }
  121. foreach (var folder in Directory.GetDirectories(folders.Source))
  122. stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
  123. }
  124. Directory.Delete(source[0], true);
  125. }
  126. public static void SaveDatabaseSettings()
  127. {
  128. new LocalConfiguration<DatabaseSettings>(Profile).Save(DatabaseSettings);
  129. }
  130. protected override void OnStartup(StartupEventArgs e)
  131. {
  132. base.OnStartup(e);
  133. /*AppMutex = new Mutex(false, $"Global\\{AppGuid}");
  134. // Don't open if PRS is already running.
  135. if(!AppMutex.WaitOne(0, false))
  136. {
  137. Shutdown(0);
  138. SendToProcesses(Message.Maximise);
  139. return;
  140. }*/
  141. AutoUpdateSettings = new LocalConfiguration<AutoUpdateSettings>().Load();
  142. var oldPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Comal.Desktop");
  143. if (Directory.Exists(oldPath))
  144. MoveDirectory(new[] { oldPath }, CoreUtils.GetPath());
  145. ShutdownMode = ShutdownMode.OnExplicitShutdown;
  146. SetupExceptionHandling();
  147. MainLogger.AddLogger(new LogFileLogger(CoreUtils.GetPath()));
  148. Logger.OnLog += MainLogger.Send;
  149. if (e.Args.Any())
  150. {
  151. DatabaseSettings = new DatabaseSettings();
  152. var extras = _commandLineParameters.Parse(e.Args);
  153. if (extras.Any())
  154. {
  155. var sw = new StringWriter();
  156. sw.WriteLine("Unknown Parameter(s) found:");
  157. foreach (var extra in extras)
  158. sw.WriteLine(" " + extra);
  159. sw.WriteLine();
  160. sw.WriteLine("The following parameters are valid:");
  161. _commandLineParameters.WriteOptionDescriptions(sw);
  162. MessageBox.Show(sw.ToString(), "PRS Desktop Startup Options");
  163. }
  164. }
  165. bool bSaveSettings = false;
  166. var allsettings = new LocalConfiguration<DatabaseSettings>().LoadAll();
  167. // Try AutoDiscovery
  168. if (!allsettings.Any())
  169. AutoDiscover(allsettings);
  170. // Create Default Database Entry
  171. if (!allsettings.Any())
  172. {
  173. allsettings["Default"] = new DatabaseSettings();
  174. bSaveSettings = true;
  175. }
  176. // Convert Blank Key to "Default"
  177. if (allsettings.ContainsKey(""))
  178. {
  179. var defaultSettings = allsettings[""];
  180. allsettings.Remove("");
  181. defaultSettings.IsActive = true;
  182. allsettings["Default"] = defaultSettings;
  183. bSaveSettings = true;
  184. }
  185. // Check and Convert from URL + Port => URLs
  186. foreach (var key in allsettings.Keys)
  187. {
  188. var settings = allsettings[key];
  189. var oldurl = CoreUtils.GetPropertyValue(settings, "URL") as String;
  190. var oldport = CoreUtils.GetPropertyValue(settings, "Port");
  191. if (!String.IsNullOrWhiteSpace(oldurl))
  192. {
  193. bSaveSettings = true;
  194. settings.URLs = new String[] { $"{oldurl}:{oldport}" };
  195. CoreUtils.SetPropertyValue(settings, "URL", "");
  196. CoreUtils.SetPropertyValue(settings, "Port", 0);
  197. }
  198. if (settings.URLs != null)
  199. {
  200. var urls = new List<String>();
  201. foreach (var url in settings.URLs)
  202. {
  203. var comps = url.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries);
  204. if (comps.Length > 1)
  205. {
  206. bSaveSettings = true;
  207. urls.Add(comps.Last());
  208. }
  209. else
  210. urls.Add(url);
  211. }
  212. settings.URLs = urls.ToArray();
  213. }
  214. }
  215. if (bSaveSettings)
  216. new LocalConfiguration<DatabaseSettings>().SaveAll(allsettings);
  217. DatabaseSettings = null;
  218. if (!string.IsNullOrWhiteSpace(Profile))
  219. {
  220. if (allsettings.ContainsKey(Profile))
  221. DatabaseSettings = allsettings[Profile];
  222. else
  223. MessageBox.Show(string.Format("Profile {0} does not exist!", Profile));
  224. }
  225. if (DatabaseSettings == null)
  226. {
  227. var keys = allsettings.Keys.Where(x => allsettings[x].IsActive).ToArray();
  228. if (keys.Length > 1)
  229. {
  230. var form = new SelectDatabase(allsettings);
  231. if (form.ShowDialog() == true)
  232. {
  233. Profile = form.Database;
  234. DatabaseSettings = allsettings[form.Database];
  235. }
  236. else
  237. {
  238. Shutdown(1);
  239. return;
  240. }
  241. form = null;
  242. }
  243. else
  244. {
  245. Profile = keys.First();
  246. DatabaseSettings = allsettings[Profile];
  247. }
  248. }
  249. StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
  250. }
  251. private static IEnumerable<string> GetRestartArguments()
  252. {
  253. // Skip the first one, because that is the location.
  254. return Environment.GetCommandLineArgs().Skip(1);
  255. }
  256. protected override void OnExit(ExitEventArgs e)
  257. {
  258. base.OnExit(e);
  259. if (ShouldRestart)
  260. {
  261. Process.Start(Path.ChangeExtension(ResourceAssembly.Location, ".exe"), GetRestartArguments());
  262. }
  263. //AppMutex.ReleaseMutex();
  264. }
  265. private void SetupExceptionHandling()
  266. {
  267. AppDomain.CurrentDomain.UnhandledException += (s, e) =>
  268. LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
  269. DispatcherUnhandledException += (s, e) =>
  270. {
  271. LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
  272. e.Handled = true;
  273. };
  274. }
  275. private void LogUnhandledException(Exception exception, string source)
  276. {
  277. var messages = new List<string>();
  278. var e2 = exception;
  279. while (e2 != null)
  280. {
  281. messages.InsertRange(0, new[] { e2.Message, e2.StackTrace, "============================================" });
  282. e2 = e2.InnerException;
  283. }
  284. MainLogger.Send(LogType.Error, "", string.Join("\n", messages));
  285. // if (exception.Message.StartsWith("Dispatcher processing has been suspended"))
  286. // try
  287. // {
  288. // SendKeys.Send("{ESC}");
  289. // }
  290. // catch (Exception e)
  291. // {
  292. // }
  293. }
  294. private class Folders
  295. {
  296. public Folders(string source, string target)
  297. {
  298. Source = source;
  299. Target = target;
  300. }
  301. public string Source { get; }
  302. public string Target { get; }
  303. }
  304. /*
  305. public enum Message
  306. {
  307. Maximise = 0x2A76
  308. }
  309. private void SendToProcesses(Message message)
  310. {
  311. var process = Process.GetCurrentProcess();
  312. var processes = Process.GetProcessesByName(process.ProcessName);
  313. if(processes.Length > 1)
  314. {
  315. foreach(var p in processes)
  316. {
  317. if(p.Id != process.Id)
  318. {
  319. SendMessage(p.MainWindowHandle, (uint)message, IntPtr.Zero, IntPtr.Zero);
  320. }
  321. }
  322. }
  323. }
  324. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  325. private static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);
  326. */
  327. }
  328. }