App.xaml.cs 14 KB

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