App.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 EmployeeEmail = "";
  36. public static string Profile = "";
  37. public static bool IsClosing = false;
  38. /*/ Guid to ensure that only one instance of PRS is running
  39. public static Guid AppGuid = Guid.Parse("237E8828-7F5A-4298-B311-CF0FC27882EC");
  40. private static Mutex AppMutex;*/
  41. private readonly OptionSet _commandLineParameters = new()
  42. {
  43. {
  44. "profile=",
  45. "",
  46. p => { Profile = p; }
  47. }
  48. };
  49. public App()
  50. {
  51. SyncfusionLicenseProvider.RegisterLicense(CoreUtils.SyncfusionLicense(SyncfusionVersion.v20_2));
  52. }
  53. private void AutoDiscover(Dictionary<string, DatabaseSettings> allsettings)
  54. {
  55. var confirm = MessageBox.Show("Try to configure Server Connection Automatically?", "Auto Discover", MessageBoxButton.YesNoCancel);
  56. if (confirm == MessageBoxResult.Yes)
  57. try
  58. {
  59. using (new WaitCursor())
  60. {
  61. AutoDiscoverySettings autodiscover;
  62. using (var client = new UdpClient())
  63. {
  64. client.Client.SendTimeout = 10000;
  65. client.Client.ReceiveTimeout = 20000;
  66. var requestData = Encoding.ASCII.GetBytes("");
  67. var serverEndPoint = new IPEndPoint(IPAddress.Any, 0);
  68. client.EnableBroadcast = true;
  69. client.Send(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888));
  70. var serverResponseData = client.Receive(ref serverEndPoint);
  71. var serverResponse = Encoding.ASCII.GetString(serverResponseData);
  72. autodiscover = Serialization.Deserialize<AutoDiscoverySettings>(serverResponse);
  73. client.Close();
  74. }
  75. var settings = new DatabaseSettings();
  76. settings.IsActive = true;
  77. settings.Logo = autodiscover.Logo;
  78. settings.Protocol = autodiscover.Protocol;
  79. settings.DatabaseType = DatabaseType.Networked;
  80. settings.URL = autodiscover.URL;
  81. settings.Port = autodiscover.Port;
  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 {autodiscover.URL}:{autodiscover.Port}");
  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. var allsettings = new LocalConfiguration<DatabaseSettings>().LoadAll();
  163. if (!allsettings.Any())
  164. AutoDiscover(allsettings);
  165. if (!allsettings.Any())
  166. {
  167. var settings = new DatabaseSettings();
  168. new LocalConfiguration<DatabaseSettings>("Default").Save(settings);
  169. allsettings["Default"] = settings;
  170. }
  171. if (allsettings.ContainsKey(""))
  172. {
  173. var defaultSettings = allsettings[""];
  174. allsettings.Remove("");
  175. new LocalConfiguration<DatabaseSettings>().Delete();
  176. defaultSettings.IsActive = true;
  177. allsettings["Default"] = defaultSettings;
  178. new LocalConfiguration<DatabaseSettings>("Default").Save(defaultSettings);
  179. }
  180. DatabaseSettings = null;
  181. if (!string.IsNullOrWhiteSpace(Profile))
  182. {
  183. if (allsettings.ContainsKey(Profile))
  184. DatabaseSettings = allsettings[Profile];
  185. else
  186. MessageBox.Show(string.Format("Profile {0} does not exist!", Profile));
  187. }
  188. if (DatabaseSettings == null)
  189. {
  190. var keys = allsettings.Keys.Where(x => allsettings[x].IsActive).ToArray();
  191. if (keys.Length > 1)
  192. {
  193. var form = new SelectDatabase(allsettings);
  194. if (form.ShowDialog() == true)
  195. {
  196. Profile = form.Database;
  197. DatabaseSettings = allsettings[form.Database];
  198. }
  199. else
  200. {
  201. Shutdown(1);
  202. return;
  203. }
  204. form = null;
  205. }
  206. else
  207. {
  208. Profile = keys.First();
  209. DatabaseSettings = allsettings.Values.First();
  210. }
  211. }
  212. StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
  213. }
  214. protected override void OnExit(ExitEventArgs e)
  215. {
  216. base.OnExit(e);
  217. //AppMutex.ReleaseMutex();
  218. }
  219. private void SetupExceptionHandling()
  220. {
  221. AppDomain.CurrentDomain.UnhandledException += (s, e) =>
  222. LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
  223. DispatcherUnhandledException += (s, e) =>
  224. {
  225. LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
  226. e.Handled = true;
  227. };
  228. }
  229. private void LogUnhandledException(Exception exception, string source)
  230. {
  231. var messages = new List<string>();
  232. var e2 = exception;
  233. while (e2 != null)
  234. {
  235. messages.InsertRange(0, new[] { e2.Message, e2.StackTrace, "============================================" });
  236. e2 = e2.InnerException;
  237. }
  238. MainLogger.Send(LogType.Error, "", string.Join("\n", messages));
  239. // if (exception.Message.StartsWith("Dispatcher processing has been suspended"))
  240. // try
  241. // {
  242. // SendKeys.Send("{ESC}");
  243. // }
  244. // catch (Exception e)
  245. // {
  246. // }
  247. }
  248. private class Folders
  249. {
  250. public Folders(string source, string target)
  251. {
  252. Source = source;
  253. Target = target;
  254. }
  255. public string Source { get; }
  256. public string Target { get; }
  257. }
  258. /*
  259. public enum Message
  260. {
  261. Maximise = 0x2A76
  262. }
  263. private void SendToProcesses(Message message)
  264. {
  265. var process = Process.GetCurrentProcess();
  266. var processes = Process.GetProcessesByName(process.ProcessName);
  267. if(processes.Length > 1)
  268. {
  269. foreach(var p in processes)
  270. {
  271. if(p.Id != process.Id)
  272. {
  273. SendMessage(p.MainWindowHandle, (uint)message, IntPtr.Zero, IntPtr.Zero);
  274. }
  275. }
  276. }
  277. }
  278. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  279. private static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);
  280. */
  281. }
  282. }