ServerGrid.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Reflection;
  9. using System.Security.Policy;
  10. using System.ServiceProcess;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Media.Imaging;
  16. using Comal.Classes;
  17. using Comal.Stores;
  18. using GenHTTP.Engine;
  19. using H.Pipes.Extensions;
  20. using H.Pipes.Factories;
  21. using InABox.Client.IPC;
  22. using InABox.Clients;
  23. using InABox.Configuration;
  24. using InABox.Core;
  25. using InABox.Database;
  26. using InABox.Database.SQLite;
  27. using InABox.DeviceIdentifier;
  28. using InABox.DynamicGrid;
  29. using InABox.IPC.Shared;
  30. using InABox.Scripting;
  31. using InABox.Wpf.Editors;
  32. using InABox.WPF;
  33. using PRSClasses;
  34. using PRSServer.Forms;
  35. using PRSServer.Forms.DatabaseLicense;
  36. using RestSharp;
  37. using Method = RestSharp.Method;
  38. namespace PRSServer
  39. {
  40. class ServerStartupSettings : BaseObject, ILocalConfigurationSettings
  41. {
  42. public List<string> StartServers { get; set; } = new();
  43. }
  44. public class ServerGrid : DynamicGrid<Server>
  45. {
  46. private Task? _monitor;
  47. private ConcurrentBag<ServiceController> _services = new();
  48. private Button _channelButton;
  49. public ServerGrid()
  50. {
  51. Options.AddRange(DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows, DynamicGridOption.ShowHelp);
  52. ActionColumns.Add(new DynamicImageColumn(TypeImage)
  53. { Position = DynamicActionColumnPosition.Start, ToolTip = TypeToolTip });
  54. ActionColumns.Add(new DynamicImageColumn(StateImage, StateAction)
  55. { Position = DynamicActionColumnPosition.End, ToolTip = StateToolTip });
  56. ActionColumns.Add(new DynamicImageColumn(SecureImage)
  57. { Position = DynamicActionColumnPosition.End, ToolTip = SecureToolTip });
  58. //ActionColumns.Add(new DynamicImageColumn(ConsoleImage, ConsoleAction)
  59. // { Position = DynamicActionColumnPosition.End, ToolTip = StateToolTip });
  60. ActionColumns.Add(new DynamicMenuColumn(CreateServerMenu,ServerMenuStatus)
  61. { Position = DynamicActionColumnPosition.End, ToolTip = MenuToolTip });
  62. RowHeight = 40;
  63. FontSize = 14;
  64. _channelButton = AddButton("", Properties.Resources.autoupdate.AsBitmapImage(), "Change Update Channel", EditUpdateChannel_Click);
  65. }
  66. private BitmapImage secureImage = Properties.Resources.secure.AsBitmapImage();
  67. private BitmapImage insecureImage = Properties.Resources.insecure.AsBitmapImage();
  68. private BitmapImage? SecureImage(CoreRow? row)
  69. {
  70. if(row is null)
  71. {
  72. return secureImage;
  73. }
  74. else
  75. {
  76. var key = row.Get<Server, string>(x => x.Key);
  77. if(DatabaseInfos.TryGetValue(key, out var info))
  78. {
  79. return info.IsHTTPS
  80. ? secureImage
  81. : insecureImage;
  82. }
  83. else
  84. {
  85. return null;
  86. }
  87. }
  88. }
  89. private FrameworkElement? SecureToolTip(DynamicActionColumn column, CoreRow? row)
  90. {
  91. if(row is null)
  92. {
  93. return column.TextToolTip("Connection Security");
  94. }
  95. else
  96. {
  97. var key = row.Get<Server, string>(x => x.Key);
  98. if (DatabaseInfos.TryGetValue(key, out var info))
  99. {
  100. return info.IsHTTPS
  101. ? column.TextToolTip("Secure (HTTPS) Connection")
  102. : column.TextToolTip("Insecure (HTTP) Connection");
  103. }
  104. else
  105. {
  106. return null;
  107. }
  108. }
  109. }
  110. private DynamicMenuStatus ServerMenuStatus(CoreRow arg)
  111. {
  112. if (arg == null)
  113. return DynamicMenuStatus.Hidden;
  114. var type = arg.Get<Server, ServerType>(x => x.Type);
  115. var service = GetService(arg.Get<Server, string>(c => c.Key));
  116. var running = service?.Status == ServiceControllerStatus.Running;
  117. if ((type == ServerType.Database) || (type == ServerType.Web) || (type == ServerType.Schedule))
  118. {
  119. return running
  120. ? DynamicMenuStatus.Enabled
  121. : DynamicMenuStatus.Disabled;
  122. }
  123. return running
  124. ? DynamicMenuStatus.Enabled
  125. : DynamicMenuStatus.Hidden;
  126. }
  127. private void CreateServerMenu(DynamicMenuColumn column, CoreRow? row)
  128. {
  129. if (row == null)
  130. return;
  131. var status = ServerMenuStatus(row);
  132. if (status == DynamicMenuStatus.Hidden)
  133. return;
  134. var type = row.Get<Server, ServerType>(x => x.Type);
  135. var key = row.Get<Server, String>(x => x.Key);
  136. column.AddItem(
  137. "View Console",
  138. Properties.Resources.target,
  139. (row) => StartConsole(row, key),
  140. null,
  141. status == DynamicMenuStatus.Enabled && !_consoles.ContainsKey(key)
  142. );
  143. if (type.Equals(ServerType.Database))
  144. {
  145. column.AddSeparator();
  146. column.AddItem(
  147. "Custom Fields",
  148. Properties.Resources.service,
  149. (row) => EditCustomFields(row),
  150. null,
  151. status == DynamicMenuStatus.Enabled
  152. );
  153. column.AddItem(
  154. "Database Scripts",
  155. Properties.Resources.script,
  156. (row) => EditDatabaseScripts(row),
  157. null,
  158. status == DynamicMenuStatus.Enabled
  159. );
  160. column.AddSeparator();
  161. column.AddItem(
  162. "Update License",
  163. Properties.Resources.key,
  164. (row) => UpdateDatabaseLicense(row),
  165. null,
  166. status == DynamicMenuStatus.Enabled
  167. );
  168. column.AddSeparator();
  169. column.AddItem(
  170. "Manage Deletions",
  171. Properties.Resources.delete,
  172. (row) => ManageDeletions(row),
  173. null,
  174. status == DynamicMenuStatus.Enabled
  175. );
  176. }
  177. else if (type.Equals(ServerType.Web))
  178. {
  179. column.AddSeparator();
  180. column.AddItem(
  181. "Edit Templates",
  182. Properties.Resources.script,
  183. (row) => EditWebTemplates(row),
  184. null,
  185. status == DynamicMenuStatus.Enabled
  186. );
  187. column.AddItem(
  188. "Edit Styles",
  189. Properties.Resources.css,
  190. (row) => EditWebStyles(row),
  191. null,
  192. status == DynamicMenuStatus.Enabled
  193. );
  194. column.AddItem(
  195. "Edit Documents",
  196. Properties.Resources.pdf,
  197. (row) => EditWebDocuments(row),
  198. null,
  199. status == DynamicMenuStatus.Enabled
  200. );
  201. column.AddSeparator();
  202. column.AddItem(
  203. "PRS Mobile Settings",
  204. Properties.Resources.web,
  205. (row) => PRSMobileSettings(row),
  206. null,
  207. status == DynamicMenuStatus.Enabled
  208. );
  209. }
  210. else if (type.Equals(ServerType.Schedule))
  211. {
  212. column.AddSeparator();
  213. column.AddItem(
  214. "Scheduled Scripts",
  215. Properties.Resources.script,
  216. (row) => EditScheduledScripts(row),
  217. null,
  218. status == DynamicMenuStatus.Enabled
  219. );
  220. }
  221. }
  222. private ServiceController? GetService(string key)
  223. {
  224. return _services.FirstOrDefault(x => string.Equals(x.ServiceName, key));
  225. }
  226. protected override void ShowHelp(string slug)
  227. {
  228. base.ShowHelp("Server_Configuration");
  229. }
  230. public void BeforeUpdate()
  231. {
  232. var sections = PRSService.GetConfiguration().LoadAll();
  233. RefreshServices(sections);
  234. var closed = new List<string>();
  235. foreach (var service in _services)
  236. {
  237. if(service.Status == ServiceControllerStatus.Running)
  238. {
  239. service.Stop();
  240. closed.Add(service.ServiceName);
  241. }
  242. }
  243. var config = PRSService.GetConfiguration<ServerStartupSettings>();
  244. var startupSettings = config.Load();
  245. startupSettings.StartServers = closed;
  246. config.Save(startupSettings);
  247. }
  248. #region Grid Handling
  249. private void RefreshServices(Dictionary<string, ServerSettings> sections)
  250. {
  251. Interlocked.Exchange(
  252. ref _services,
  253. new ConcurrentBag<ServiceController>(
  254. ServiceController.GetServices().Where(x => sections.ContainsKey(x.ServiceName))
  255. )
  256. );
  257. }
  258. private Dictionary<string, DatabaseInfo> DatabaseInfos { get; set; } = new Dictionary<string, DatabaseInfo>();
  259. private HashSet<string> LoadingInfos = new HashSet<string>();
  260. protected override void Reload(Filters<Server> criteria, Columns<Server> columns, ref SortOrder<Server>? sort,
  261. Action<CoreTable?, Exception?> action)
  262. {
  263. var table = new CoreTable();
  264. table.LoadColumns(typeof(Server));
  265. var sections = PRSService.GetConfiguration().LoadAll();
  266. RefreshServices(sections);
  267. var startupConfig = PRSService.GetConfiguration<ServerStartupSettings>();
  268. var startupSettings = startupConfig.Load();
  269. foreach (var startup in startupSettings.StartServers)
  270. {
  271. _services.FirstOrDefault(x => x.ServiceName == startup)?.Start();
  272. }
  273. startupSettings.StartServers.Clear();
  274. startupConfig.Save(startupSettings);
  275. foreach (var section in sections.OrderBy(x => x.Value.Type))
  276. {
  277. var server = section.Value.CreateServer(section.Key);
  278. var service = _services.FirstOrDefault(x => string.Equals(x.ServiceName, section.Key));
  279. var row = table.NewRow();
  280. table.LoadRow(row, server);
  281. table.Rows.Add(row);
  282. }
  283. if (table.Rows.Any(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Certificate))
  284. {
  285. foreach (var row in table.Rows.Where(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Database))
  286. {
  287. var key = row.Get<Server, string>(x => x.Key);
  288. var service = GetService(key);
  289. if (service is not null && service.Status == ServiceControllerStatus.Running)
  290. {
  291. if (!LoadingInfos.Contains(key))
  292. {
  293. LoadingInfos.Add(key);
  294. Task.Run(() =>
  295. {
  296. while (true)
  297. {
  298. var client = IPCClientFactory.GetClient(DatabaseServerProperties.GetPipeName(key));
  299. var response = client.Send(PipeRequest.Info(new InfoRequest()), 10_000).GetResponse<InfoResponse>();
  300. if (response.Status != StatusCode.Error)
  301. {
  302. DatabaseInfos[key] = response.Info;
  303. break;
  304. }
  305. else
  306. {
  307. DatabaseInfos.Remove(key);
  308. var service = GetService(key);
  309. if (service is null || service.Status != ServiceControllerStatus.Running)
  310. {
  311. break;
  312. }
  313. }
  314. }
  315. Dispatcher.Invoke(() =>
  316. {
  317. InvalidateRow(row);
  318. });
  319. LoadingInfos.Remove(key);
  320. });
  321. }
  322. }
  323. else
  324. {
  325. if(DatabaseInfos.TryGetValue(key, out var info))
  326. {
  327. DatabaseInfos.Remove(key);
  328. }
  329. }
  330. }
  331. }
  332. action(table, null);
  333. _monitor ??= Task.Run(() =>
  334. {
  335. while (true)
  336. {
  337. try
  338. {
  339. var bRefresh = false;
  340. foreach (var service in _services)
  341. {
  342. var oldstatus = service.Status;
  343. service.Refresh();
  344. bRefresh = bRefresh || service.Status != oldstatus;
  345. /*if ((oldstatus != ServiceControllerStatus.Stopped) && (service.Status == ServiceControllerStatus.Stopped))
  346. Dispatcher.Invoke(() => StopConsole(service.ServiceName));*/
  347. }
  348. if (bRefresh)
  349. Dispatcher.Invoke(() => { Refresh(false, true); });
  350. }
  351. catch (Exception e)
  352. {
  353. }
  354. Task.Delay(500).Wait();
  355. }
  356. });
  357. }
  358. // protected override void SelectItems(CoreRow[] rows)
  359. // {
  360. // base.SelectItems(rows);
  361. // if (rows != null && rows.Length == 1)
  362. // {
  363. // var type = rows.First().Get<Server, ServerType>(x => x.Type);
  364. // DatabaseLicense.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  365. // DatabaseCustomFields.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  366. // DatabaseScripts.Visibility = Equals(type, ServerType.Database) ? Visibility.Visible : Visibility.Collapsed;
  367. //
  368. // EditWebSettings.Visibility = Equals(type, ServerType.Web) ? Visibility.Visible : Visibility.Collapsed;
  369. //
  370. // ScheduledScripts.Visibility = type == ServerType.Schedule ? Visibility.Visible : Visibility.Collapsed;
  371. // }
  372. // else
  373. // {
  374. // EditWebSettings.Visibility = Visibility.Collapsed;
  375. // DatabaseLicense.Visibility = Visibility.Collapsed;
  376. // DatabaseCustomFields.Visibility = Visibility.Collapsed;
  377. // DatabaseScripts.Visibility = Visibility.Collapsed;
  378. // ScheduledScripts.Visibility = Visibility.Collapsed;
  379. // }
  380. // }
  381. protected override Server LoadItem(CoreRow row)
  382. {
  383. var key = row.Get<Server, string>(x => x.Key);
  384. var settings = PRSService.GetConfiguration(key).Load();
  385. return settings.CreateServer(key);
  386. }
  387. private string CreateKey(ServerType type)
  388. {
  389. var services = ServiceController.GetServices();
  390. var key = string.Format("PRS{0}", type.ToString());
  391. var i = 1;
  392. while (services.Any(x => string.Equals(key, x.ServiceName)))
  393. key = string.Format("PRS{0}_{1}", type.ToString(), i++);
  394. return key;
  395. }
  396. private void CreateMenu(ContextMenu parent, string header, ServerType server, Type properties)
  397. {
  398. var menu = new MenuItem();
  399. menu.Header = header;
  400. menu.Tag = properties;
  401. menu.Icon = new Image() { Source = _typeimages[server] };
  402. menu.IsCheckable = false;
  403. menu.Click += (o, e) =>
  404. {
  405. var itemtype = ((o as MenuItem)?.Tag as Type)!;
  406. var props = (Activator.CreateInstance(itemtype) as ServerProperties)!;
  407. if (EditProperties(properties, props, true))
  408. {
  409. var server = CreateItem();
  410. server.Key = CreateKey(props.Type());
  411. server.Type = props.Type();
  412. server.Properties = props;
  413. SaveItem(server);
  414. Refresh(false, true);
  415. }
  416. };
  417. parent.Items.Add(menu);
  418. }
  419. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  420. {
  421. var menu = new ContextMenu();
  422. CreateMenu(menu, "Database", ServerType.Database, typeof(DatabaseServerProperties));
  423. CreateMenu(menu, "GPS Connector", ServerType.GPS, typeof(GPSServerProperties));
  424. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.AutoDiscovery))
  425. CreateMenu(menu, "Auto Discovery", ServerType.AutoDiscovery, typeof(AutoDiscoveryServerProperties));
  426. CreateMenu(menu, "Scheduler", ServerType.Schedule, typeof(ScheduleServerProperties));
  427. CreateMenu(menu, "Web Service", ServerType.Web, typeof(WebServerProperties));
  428. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.Certificate))
  429. CreateMenu(menu, "HTTPS Certificate Engine", ServerType.Certificate, typeof(CertificateEngineProperties));
  430. menu.IsOpen = true;
  431. }
  432. protected override void DoEdit()
  433. {
  434. if (!SelectedRows.Any())
  435. return;
  436. var server = LoadItem(SelectedRows.First());
  437. var service = GetService(server.Key);
  438. var enabled = service == null || service.Status == ServiceControllerStatus.Stopped;
  439. if (EditProperties(server.Properties.GetType(), server.Properties, enabled))
  440. {
  441. server.Name = server.Properties.Name;
  442. SaveItem(server);
  443. Refresh(false, true);
  444. }
  445. }
  446. public override void SaveItem(Server item)
  447. {
  448. var settings = new ServerSettings();
  449. settings.Type = item.Type;
  450. settings.Properties = Serialization.Serialize(item.Properties, false);
  451. PRSService.GetConfiguration(item.Key).Save(settings);
  452. ReconfigureService(item);
  453. }
  454. private bool isServiceChanged(Server server, ServiceController? service, string newDisplayName)
  455. {
  456. return newDisplayName != service?.DisplayName || (server.Properties.HasOriginalValue(x => x.Username) && server.Properties.GetOriginalValue(x => x.Username) != server.Properties.Username);
  457. }
  458. protected override bool CanDeleteItems(params CoreRow[] rows)
  459. {
  460. var bOK = true;
  461. foreach (var row in rows)
  462. {
  463. var service = GetService(row.Get<Server, string>(x => x.Key));
  464. if (service != null && service.Status != ServiceControllerStatus.Stopped)
  465. bOK = false;
  466. }
  467. return bOK;
  468. }
  469. protected override void DeleteItems(params CoreRow[] rows)
  470. {
  471. foreach (var row in rows)
  472. {
  473. var key = row.Get<Server, string>(x => x.Key);
  474. Interlocked.Exchange(
  475. ref _services,
  476. new ConcurrentBag<ServiceController>(
  477. _services.Where(x => !string.Equals(x.ServiceName, key))
  478. )
  479. );
  480. PRSService.GetConfiguration(key).Delete();
  481. var serverType = row.Get<Server, ServerType>(x => x.Type);
  482. if (serverType == ServerType.Certificate)
  483. {
  484. if (File.Exists(CertificateEngine.CertificateFile))
  485. {
  486. File.Delete(CertificateEngine.CertificateFile);
  487. }
  488. }
  489. PRSServiceInstaller.UninstallService(key);
  490. }
  491. }
  492. protected override void DefineLookups(ILookupEditorControl sender, Server[] items)
  493. {
  494. if(sender.EditorDefinition is ComboLookupEditor lookup && lookup.Type == typeof(DatabaseServerLookupGenerator))
  495. {
  496. base.DefineLookups(sender, Data.Rows.Select(x => x.ToObject<Server>()).ToArray());
  497. }
  498. else
  499. {
  500. base.DefineLookups(sender, items);
  501. }
  502. }
  503. #endregion
  504. #region Server Configuration
  505. private bool EditUpdateChannel_Click(Button arg1, CoreRow[] arg2)
  506. {
  507. var settings = new LocalConfiguration<AutoUpdateSettings>().Load();
  508. var editable = settings.ToEditable();
  509. var buttons = new DynamicEditorButtons()
  510. {
  511. new DynamicEditorButton(
  512. "",
  513. Properties.Resources.help.AsBitmapImage(),
  514. null,
  515. (o, e) => base.ShowHelp("Automatic_Updates"))
  516. };
  517. var propertyEditor = new DynamicEditorForm(typeof(EditableAutoUpdateSettings), null, buttons);
  518. propertyEditor.OnDefineEditor += PropertyEditor_OnDefineEditor;
  519. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  520. propertyEditor.Items = new BaseObject[] { editable };
  521. if (propertyEditor.ShowDialog() == true)
  522. {
  523. settings.FromEditable(editable);
  524. new LocalConfiguration<AutoUpdateSettings>().Save(settings);
  525. }
  526. return false;
  527. }
  528. private BaseEditor? PropertyEditor_OnDefineEditor(object item, DynamicGridColumn column)
  529. {
  530. if (string.Equals(column.ColumnName, "Elevated"))
  531. return new NullEditor();
  532. var result = GetEditor(item, column);
  533. if (result != null)
  534. result = result.CloneEditor();
  535. return result;
  536. }
  537. private void ReconfigureService(Server item)
  538. {
  539. var service = GetService(item.Key);
  540. var newDisplayName = "PRS - " + item.Properties.Name;
  541. string? username = item.Properties.Username;
  542. if (!isServiceChanged(item, service, newDisplayName)) return;
  543. string? password = null;
  544. if (!string.IsNullOrWhiteSpace(username))
  545. {
  546. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  547. if(passwordEditor.ShowDialog() == true)
  548. {
  549. password = passwordEditor.Password;
  550. }
  551. else
  552. {
  553. password = null;
  554. }
  555. }
  556. else
  557. {
  558. username = null;
  559. }
  560. if (service == null)
  561. try
  562. {
  563. using (new WaitCursor())
  564. {
  565. PRSServiceInstaller.InstallService(
  566. item.Key,
  567. item.Properties.Name,
  568. newDisplayName,
  569. username,
  570. password
  571. );
  572. }
  573. }
  574. catch (Exception e)
  575. {
  576. MessageBox.Show(string.Format("Error Installing {0}: {1}", item.Key, e.Message));
  577. }
  578. else
  579. try
  580. {
  581. using (new WaitCursor())
  582. {
  583. PRSServiceInstaller.ChangeService(
  584. item.Key,
  585. item.Properties.Name,
  586. newDisplayName,
  587. username,
  588. password
  589. );
  590. }
  591. }
  592. catch (Exception e)
  593. {
  594. MessageBox.Show(string.Format("Error Configuring {0}: {1}", item.Key, e.Message));
  595. }
  596. }
  597. public bool EditProperties(Type type, ServerProperties item, bool enabled)
  598. {
  599. var pages = new DynamicEditorPages();
  600. if (type == typeof(DatabaseServerProperties))
  601. {
  602. pages.Add(new SMSProviderGrid(!enabled));
  603. }
  604. var buttons = new DynamicEditorButtons();
  605. buttons.Add(
  606. "",
  607. Properties.Resources.help.AsBitmapImage(),
  608. item,
  609. (f, i) =>
  610. {
  611. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + type.Name.SplitCamelCase().Replace(" ", "_"))
  612. { UseShellExecute = true });
  613. }
  614. );
  615. var propertyEditor = new DynamicEditorForm(type, pages, buttons);
  616. if(type == typeof(DatabaseServerProperties))
  617. {
  618. propertyEditor.OnSaveItem += (o, e) =>
  619. {
  620. propertyEditor.UnloadEditorPages(false);
  621. propertyEditor.UnloadEditorPages(true);
  622. };
  623. }
  624. propertyEditor.ReadOnly = !enabled;
  625. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  626. propertyEditor.Items = new BaseObject[] { item };
  627. return propertyEditor.ShowDialog() == true;
  628. }
  629. #endregion
  630. #region Service Start / Stop Actions
  631. private readonly Dictionary<int, BitmapImage> _stateimages = new()
  632. {
  633. { 0, Properties.Resources.warning.AsBitmapImage() },
  634. { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
  635. { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
  636. { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
  637. { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
  638. { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
  639. { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
  640. { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
  641. };
  642. private BitmapImage StateImage(CoreRow? arg)
  643. {
  644. if (arg == null)
  645. return Properties.Resources.tick.AsBitmapImage();
  646. var service = GetService(arg.Get<Server, string>(c => c.Key));
  647. var state = service != null ? (int)service.Status : 0;
  648. return _stateimages[state];
  649. }
  650. private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  651. {
  652. if (arg2 == null)
  653. return null;
  654. var service = GetService(arg2.Get<Server, string>(c => c.Key));
  655. return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
  656. }
  657. private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  658. {
  659. return arg2 != null ? arg1.TextToolTip("Server Options") : null;
  660. }
  661. private bool StateAction(CoreRow? arg)
  662. {
  663. if (arg == null)
  664. return false;
  665. var key = arg.Get<Server, string>(c => c.Key);
  666. var service = GetService(arg.Get<Server, string>(c => c.Key));
  667. if (service != null)
  668. {
  669. Task? task;
  670. if (service.Status == ServiceControllerStatus.Running)
  671. {
  672. task = Task.Run(() => { service.Stop(); });
  673. //StopConsole(key);
  674. }
  675. else if (service.Status == ServiceControllerStatus.Stopped)
  676. {
  677. task = Task.Run(() => {
  678. service.Start();
  679. });
  680. StartConsole(arg,key);
  681. }
  682. else if (service.Status == ServiceControllerStatus.Paused)
  683. {
  684. task = Task.Run(() => { service.Continue(); });
  685. }
  686. else
  687. {
  688. MessageBox.Show(string.Format("Invalid Service State ({0})", service.Status.ToString()));
  689. return false;
  690. }
  691. task?.ContinueWith((e) =>
  692. {
  693. if (e.Exception?.InnerException is { } inner)
  694. {
  695. if(inner.InnerException != null)
  696. {
  697. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.InnerException.Message));
  698. }
  699. else
  700. {
  701. MessageBox.Show(String.Format("Error while running service:\n{0}", inner.Message));
  702. }
  703. PRSServiceInstaller.UninstallService(arg.Get<Server, string>(x => x.Key));
  704. Refresh(false, true);
  705. }
  706. }, TaskScheduler.FromCurrentSynchronizationContext());
  707. return true;
  708. }
  709. MessageBox.Show("Cannot find Service - is it installed?");
  710. return false;
  711. }
  712. public void StopAll()
  713. {
  714. foreach (var service in _services.ToArray())
  715. if (service.Status == ServiceControllerStatus.Running)
  716. Task.Run(() => { service.Stop(); });
  717. }
  718. #endregion
  719. #region Server Type Images
  720. private readonly Dictionary<ServerType, BitmapImage> _typeimages = new()
  721. {
  722. { ServerType.Database, Properties.Resources.database.AsBitmapImage() },
  723. { ServerType.GPS, Properties.Resources.gps.AsBitmapImage() },
  724. { ServerType.AutoDiscovery, Properties.Resources.autodiscover.AsBitmapImage() },
  725. { ServerType.Schedule, Properties.Resources.schedule.AsBitmapImage() },
  726. { ServerType.Web, Properties.Resources.web.AsBitmapImage() },
  727. { ServerType.Certificate, Properties.Resources.certificate.AsBitmapImage() }
  728. };
  729. private BitmapImage TypeImage(CoreRow? arg)
  730. {
  731. if (arg == null)
  732. return Properties.Resources.help.AsBitmapImage();
  733. var type = arg.Get<Server, ServerType>(c => c.Type);
  734. return _typeimages[type];
  735. }
  736. private FrameworkElement? TypeToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  737. {
  738. if (arg2 == null)
  739. return null;
  740. return arg1.TextToolTip(string.Format("{0} Service\nName: {1}",
  741. arg2.Get<Server, ServerType>(c => c.Type).ToString(),
  742. arg2.Get<Server, string>(c => c.Key)
  743. ));
  744. }
  745. #endregion
  746. #region Console Functions
  747. private BitmapImage? ConsoleImage(CoreRow? arg)
  748. {
  749. if (arg == null)
  750. return Properties.Resources.target.AsBitmapImage();
  751. var service = GetService(arg.Get<Server, string>(c => c.Key));
  752. var state = service != null ? (int)service.Status : 0;
  753. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  754. return Properties.Resources.target.AsBitmapImage();
  755. return null;
  756. }
  757. private bool ConsoleAction(CoreRow? arg)
  758. {
  759. if (arg == null)
  760. return false;
  761. var key = arg.Get<Server, string>(c => c.Key);
  762. var service = GetService(key);
  763. var state = service != null ? (int)service.Status : 0;
  764. if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
  765. StartConsole(arg, key);
  766. return false;
  767. }
  768. private Dictionary<String, Tuple<Console,int>> _consoles = new Dictionary<string, Tuple<Console,int>>();
  769. private void StartConsole(CoreRow arg, string key)
  770. {
  771. if (_consoles.ContainsKey(key))
  772. return;
  773. var name = arg.Get<Server, string>(c => c.Name);
  774. var console = new Console(key, string.Format("{0} - {1}", key, name));
  775. var window = Window.GetWindow(this);
  776. int i = 0;
  777. while (_consoles.Any(x => x.Value.Item2 == i))
  778. i++;
  779. _consoles[key] = new Tuple<Console, int>(console, i);
  780. console.Top = window.Top + (i * 50);
  781. console.Left = window.Left + window.Width + 2 + (i*50);
  782. console.Height = window.Height;
  783. console.Closing += (o, e) =>
  784. {
  785. Console c = o as Console;
  786. if (_consoles.ContainsKey(c.ServiceName))
  787. _consoles.Remove(c.ServiceName);
  788. };
  789. console.Show();
  790. }
  791. private void StopConsole(String key)
  792. {
  793. if (!_consoles.ContainsKey(key))
  794. return;
  795. Console console = _consoles[key].Item1;
  796. console.Close();
  797. }
  798. #endregion
  799. #region Individual Server Buttons
  800. // Check if a database server is running at the given url and port
  801. private bool IsDatabaseServerRunning(string url, int port)
  802. {
  803. var uri = new Uri(string.Format("{0}:{1}", url, port));
  804. var cli = new RestClient(uri);
  805. var req = new RestRequest("/classes", Method.GET) { Timeout = 20000 };
  806. try
  807. {
  808. var res = cli.Execute(req);
  809. if (res.StatusCode != HttpStatusCode.OK || res.ErrorException != null)
  810. return false;
  811. return true;
  812. }
  813. catch (Exception e)
  814. {
  815. }
  816. return false;
  817. }
  818. // The following variables keep track of whether a database is currently being used, since if two people try to access two different databases,
  819. // terrible things will ensue.
  820. private int currentServerUsers;
  821. private string? currentServerURL;
  822. private int? currentServerPort;
  823. /// <summary>
  824. /// Configures a server for the duration of an action
  825. /// </summary>
  826. /// <typeparam name="TProperties"></typeparam>
  827. /// <param name="row"></param>
  828. /// <param name="hostaddress"></param>
  829. /// <param name="portnumber"></param>
  830. /// <param name="action"></param>
  831. /// <param name="blocking">
  832. /// If blocking is set to false, then currentServerUsers must be decreased by one manually once the
  833. /// task finishes
  834. /// </param>
  835. private void ConfigureServer<TProperties>(
  836. CoreRow row,
  837. Func<TProperties, string> hostaddress,
  838. Func<TProperties, int> portnumber,
  839. Action action,
  840. bool blocking = true
  841. ) where TProperties : ServerProperties
  842. {
  843. try
  844. {
  845. if (row == null)
  846. throw new Exception("No Row Selected!");
  847. var server = LoadItem(row);
  848. if (server == null)
  849. throw new Exception("Unable to load Server!");
  850. var props = server.Properties as TProperties;
  851. if (props == null)
  852. throw new Exception("Unable to Load Properties!");
  853. var url = hostaddress(props);
  854. var port = portnumber(props);
  855. using (new WaitCursor())
  856. {
  857. if (!IsDatabaseServerRunning(url, port))
  858. throw new Exception("Database Server is not available!");
  859. }
  860. if (action != null)
  861. {
  862. if (currentServerUsers == 0)
  863. {
  864. if (currentServerURL != url || currentServerPort != port)
  865. {
  866. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  867. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  868. }
  869. currentServerURL = url;
  870. currentServerPort = port;
  871. currentServerName = null;
  872. ClientFactory.SetClientType(typeof(JsonClient<>), "PRSServer", CoreUtils.GetVersion(), url, port, true);
  873. // override the need to provide credentials when configuring the database
  874. ClientFactory.SetBypass();
  875. }
  876. else
  877. {
  878. if (url != currentServerURL || port != currentServerPort)
  879. throw new Exception(string.Format("A different Database Server ({0}:{1}) is currently in use!", currentServerURL,
  880. currentServerPort));
  881. }
  882. currentServerUsers++;
  883. action();
  884. if (blocking) currentServerUsers--;
  885. }
  886. }
  887. catch (Exception e)
  888. {
  889. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  890. MessageBox.Show(e.Message);
  891. }
  892. }
  893. private string? currentServerName;
  894. private void ConfigureIPCServer<TProperties>(
  895. CoreRow row,
  896. Func<TProperties, string> hostPipeName,
  897. Action action,
  898. bool blocking = true
  899. ) where TProperties : ServerProperties
  900. {
  901. try
  902. {
  903. if (row == null)
  904. throw new Exception("No Row Selected!");
  905. var server = LoadItem(row);
  906. if (server == null)
  907. throw new Exception("Unable to load Server!");
  908. var props = server.Properties as TProperties;
  909. if (props == null)
  910. throw new Exception("Unable to Load Properties!");
  911. var pipeName = DatabaseServerProperties.GetPipeName(hostPipeName(props));
  912. if (action != null)
  913. {
  914. if (currentServerUsers == 0)
  915. {
  916. if (currentServerName != pipeName)
  917. {
  918. ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
  919. ConfigurationCache.ClearAll(ConfigurationCacheType.User);
  920. }
  921. currentServerPort = null;
  922. currentServerURL = null;
  923. currentServerName = pipeName;
  924. ClientFactory.SetClientType(typeof(PipeIPCClient<>), "PRSServer", CoreUtils.GetVersion(), pipeName);
  925. using (new WaitCursor())
  926. {
  927. if (!Client.Ping())
  928. {
  929. ClientFactory.ClearClientType();
  930. throw new Exception("Database Server is not available!");
  931. }
  932. }
  933. // override the need to provide credentials when configuring the database
  934. ClientFactory.SetBypass();
  935. }
  936. else
  937. {
  938. if (pipeName != currentServerName)
  939. throw new Exception(string.Format("A different Database Server ({0}) is currently in use!", currentServerName));
  940. }
  941. currentServerUsers++;
  942. try
  943. {
  944. action();
  945. }
  946. finally
  947. {
  948. if (blocking) currentServerUsers--;
  949. }
  950. }
  951. }
  952. catch (Exception e)
  953. {
  954. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  955. MessageBox.Show(e.Message);
  956. }
  957. }
  958. private void ConfigureLocalDatabase(
  959. CoreRow row,
  960. Action action
  961. )
  962. {
  963. try
  964. {
  965. if (row == null)
  966. throw new Exception("No Row Selected!");
  967. var server = LoadItem(row);
  968. if (server == null)
  969. throw new Exception("Unable to load Server!");
  970. var properties = server.Properties as DatabaseServerProperties;
  971. if (properties == null)
  972. throw new Exception("Unable to Load Properties!");
  973. if (!DbFactory.IsProviderSet || DbFactory.Provider is not SQLiteProvider sql || sql.URL != properties.FileName)
  974. {
  975. ClientFactory.SetClientType(typeof(LocalClient<>), "PRSServer", CoreUtils.GetVersion(), "");
  976. Progress.ShowModal("Configuring database", (progress) =>
  977. {
  978. DbFactory.Stores = CoreUtils.TypeList(
  979. AppDomain.CurrentDomain.GetAssemblies(),
  980. myType =>
  981. myType.IsClass
  982. && !myType.IsAbstract
  983. && !myType.IsGenericType
  984. && myType.GetInterfaces().Contains(typeof(IStore))
  985. ).ToArray();
  986. DbFactory.Provider = new SQLiteProvider(properties.FileName);
  987. DbFactory.Start();
  988. StoreUtils.GoogleAPIKey = properties.GoogleAPIKey;
  989. PurchaseOrderStore.AutoIncrementPrefix = properties.PurchaseOrderPrefix;
  990. JobStore.AutoIncrementPrefix = properties.JobPrefix;
  991. });
  992. }
  993. action();
  994. }
  995. catch(Exception e)
  996. {
  997. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  998. MessageBox.Show(e.Message);
  999. }
  1000. }
  1001. private bool UpdateDatabaseLicense(CoreRow selectedrow)
  1002. {
  1003. ConfigureIPCServer<DatabaseServerProperties>(
  1004. selectedrow,
  1005. //x => "http://127.0.0.1",
  1006. //x => x.Port,
  1007. x => selectedrow.Get<Server, string>(x => x.Key),
  1008. () =>
  1009. {
  1010. new LicenseRenewalForm().ShowDialog();
  1011. }
  1012. );
  1013. return false;
  1014. }
  1015. private bool ManageDeletions(CoreRow row)
  1016. {
  1017. ConfigureLocalDatabase(row, () =>
  1018. {
  1019. new DeletionsWindow().ShowDialog();
  1020. });
  1021. return false;
  1022. }
  1023. private bool EditCustomFields(CoreRow selectedrow)
  1024. {
  1025. ConfigureIPCServer<DatabaseServerProperties>(
  1026. selectedrow,
  1027. //x => "http://127.0.0.1",
  1028. //x => x.Port,
  1029. x => selectedrow.Get<Server, string>(x => x.Key),
  1030. () => { new MasterList(typeof(CustomProperty), "Class", null, true).ShowDialog(); }
  1031. );
  1032. return false;
  1033. }
  1034. private bool EditDatabaseScripts(CoreRow selectedrow)
  1035. {
  1036. ConfigureIPCServer<DatabaseServerProperties>(
  1037. selectedrow,
  1038. //x => "http://127.0.0.1",
  1039. //x => x.Port,
  1040. x => selectedrow.Get<Server, string>(x => x.Key),
  1041. () => { new MasterList(typeof(Script), "Section", null, true).ShowDialog(); }
  1042. );
  1043. return false;
  1044. }
  1045. private bool EditScheduledScripts(CoreRow selectedrow)
  1046. {
  1047. ConfigureIPCServer<ScheduleServerProperties>(
  1048. selectedrow,
  1049. x => x.Server,
  1050. () => { new MasterList(typeof(ScheduledScript), "", null, true, typeof(ScheduledScriptsGrid)).ShowDialog(); }
  1051. );
  1052. return false;
  1053. }
  1054. private bool EditWebTemplates(CoreRow selectedRow)
  1055. {
  1056. ConfigureIPCServer<WebServerProperties>(
  1057. selectedRow,
  1058. x => x.Server,
  1059. () =>
  1060. {
  1061. var window = new MasterList(typeof(WebTemplate), "DataModel", "", true);
  1062. window.Closed += (e, args) => { currentServerUsers--; };
  1063. window.Show();
  1064. },
  1065. false
  1066. );
  1067. return false;
  1068. }
  1069. private bool EditWebStyles(CoreRow selectedRow)
  1070. {
  1071. ConfigureIPCServer<WebServerProperties>(
  1072. selectedRow,
  1073. x => x.Server,
  1074. () =>
  1075. {
  1076. var window = new MasterList(typeof(WebStyle), "Code", "", true);
  1077. window.Closed += (e, args) => { currentServerUsers--; };
  1078. window.Show();
  1079. },
  1080. false
  1081. );
  1082. return false;
  1083. }
  1084. private bool EditWebDocuments(CoreRow selectedRow)
  1085. {
  1086. ConfigureIPCServer<WebServerProperties>(
  1087. selectedRow,
  1088. x => x.Server,
  1089. () =>
  1090. {
  1091. var window = new MasterList(typeof(WebDocument), "Code", "", true);
  1092. window.Closed += (e, args) => { currentServerUsers--; };
  1093. window.Show();
  1094. },
  1095. false
  1096. );
  1097. return false;
  1098. }
  1099. private bool PRSMobileSettings(CoreRow selectedrow)
  1100. {
  1101. ConfigureIPCServer<WebServerProperties>(
  1102. selectedrow,
  1103. x => x.Server,
  1104. () =>
  1105. {
  1106. var editor = new DynamicEditorForm(typeof(WebSettings));
  1107. var settings = new GlobalConfiguration<WebSettings>().Load();
  1108. editor.Items = new[] { settings };
  1109. if (editor.ShowDialog() == true) new GlobalConfiguration<WebSettings>().Save(settings);
  1110. }
  1111. );
  1112. return false;
  1113. }
  1114. #endregion
  1115. }
  1116. }