App.xaml.cs 13 KB

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