ServerGrid.cs 46 KB

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