App.xaml.cs 14 KB

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