ServerGrid.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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;
  28. using PRSClasses;
  29. using PRSServer.Forms;
  30. using PRSServer.Forms.DatabaseLicense;
  31. using RestSharp;
  32. using Method = RestSharp.Method;
  33. namespace PRSServer
  34. {
  35. class ServerStartupSettings : BaseObject, ILocalConfigurationSettings
  36. {
  37. public List<string> StartServers { get; set; } = new();
  38. }
  39. public class ServerGrid : DynamicGrid<Server>
  40. {
  41. private Task? _monitor;
  42. private ConcurrentBag<ServiceController> _services = new();
  43. private Button _channelButton;
  44. private Button _statusButton;
  45. private CancellationTokenSource cancel = new CancellationTokenSource();
  46. public ServerGrid()
  47. {
  48. Options.AddRange(DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows, DynamicGridOption.ShowHelp);
  49. ActionColumns.Add(new DynamicImageColumn(TypeImage)
  50. { Position = DynamicActionColumnPosition.Start, ToolTip = TypeToolTip });
  51. ActionColumns.Add(new DynamicImageColumn(SecureImage)
  52. { Position = DynamicActionColumnPosition.Start, ToolTip = SecureToolTip });
  53. ActionColumns.Add(new DynamicImageColumn(StateImage, StateAction)
  54. { Position = DynamicActionColumnPosition.End, ToolTip = StateToolTip });
  55. ActionColumns.Add(new DynamicMenuColumn(CreateServerMenu,ServerMenuStatus)
  56. { Position = DynamicActionColumnPosition.End, ToolTip = MenuToolTip });
  57. RowHeight = 40;
  58. FontSize = 14;
  59. _channelButton = AddButton("", Properties.Resources.autoupdate.AsBitmapImage(), "Change Update Channel", EditUpdateChannel_Click);
  60. _statusButton = AddButton("", Properties.Resources.secure.AsBitmapImage(), "Check Service Status", ShowServiceStatus);
  61. }
  62. private BitmapImage secureImage = Properties.Resources.secure.AsBitmapImage();
  63. private BitmapImage insecureImage = Properties.Resources.insecure.AsBitmapImage();
  64. private BitmapImage? SecureImage(CoreRow? row)
  65. {
  66. if(row is null)
  67. {
  68. return secureImage;
  69. }
  70. else
  71. {
  72. var key = row.Get<Server, string>(x => x.Key);
  73. if(_secureConnections.TryGetValue(key, out var secure))
  74. {
  75. return secure
  76. ? secureImage
  77. : insecureImage;
  78. }
  79. else
  80. {
  81. return null;
  82. }
  83. }
  84. }
  85. private FrameworkElement? SecureToolTip(DynamicActionColumn column, CoreRow? row)
  86. {
  87. if(row is null)
  88. {
  89. return column.TextToolTip("Connection Security");
  90. }
  91. else
  92. {
  93. var key = row.Get<Server, string>(x => x.Key);
  94. if (_secureConnections.TryGetValue(key, out var secure))
  95. {
  96. return secure
  97. ? column.TextToolTip("Secure (HTTPS) Connection")
  98. : column.TextToolTip("Insecure (HTTP) Connection");
  99. }
  100. else
  101. {
  102. return null;
  103. }
  104. }
  105. }
  106. private DynamicMenuStatus ServerMenuStatus(CoreRow arg)
  107. {
  108. if (arg == null)
  109. return DynamicMenuStatus.Hidden;
  110. var type = arg.Get<Server, ServerType>(x => x.Type);
  111. var service = GetService(arg.Get<Server, string>(c => c.Key));
  112. var running = service?.Status == ServiceControllerStatus.Running;
  113. if ((type == ServerType.Database) || (type == ServerType.Web) || (type == ServerType.Schedule))
  114. {
  115. return running
  116. ? DynamicMenuStatus.Enabled
  117. : DynamicMenuStatus.Disabled;
  118. }
  119. return running
  120. ? DynamicMenuStatus.Enabled
  121. : DynamicMenuStatus.Hidden;
  122. }
  123. private void CreateServerMenu(DynamicMenuColumn column, CoreRow? row)
  124. {
  125. if (row == null)
  126. return;
  127. var status = ServerMenuStatus(row);
  128. if (status == DynamicMenuStatus.Hidden)
  129. return;
  130. var type = row.Get<Server, ServerType>(x => x.Type);
  131. var key = row.Get<Server, String>(x => x.Key);
  132. column.AddItem(
  133. "View Console",
  134. Properties.Resources.target,
  135. (row) => StartConsole(row, key),
  136. null,
  137. status == DynamicMenuStatus.Enabled && !_consoles.ContainsKey(key)
  138. );
  139. if (type.Equals(ServerType.Database))
  140. {
  141. column.AddSeparator();
  142. column.AddItem(
  143. "Custom Fields",
  144. Properties.Resources.service,
  145. (row) => EditCustomFields(row),
  146. null,
  147. status == DynamicMenuStatus.Enabled
  148. );
  149. column.AddItem(
  150. "Database Scripts",
  151. Properties.Resources.script,
  152. (row) => EditDatabaseScripts(row),
  153. null,
  154. status == DynamicMenuStatus.Enabled
  155. );
  156. column.AddSeparator();
  157. column.AddItem(
  158. "Update License",
  159. Properties.Resources.key,
  160. (row) => UpdateDatabaseLicense(row),
  161. null,
  162. status == DynamicMenuStatus.Enabled
  163. );
  164. column.AddSeparator();
  165. column.AddItem(
  166. "Manage Deletions",
  167. Properties.Resources.delete,
  168. (row) => ManageDeletions(row),
  169. null,
  170. status == DynamicMenuStatus.Enabled
  171. );
  172. }
  173. else if (type.Equals(ServerType.Web))
  174. {
  175. column.AddSeparator();
  176. column.AddItem(
  177. "Edit Templates",
  178. Properties.Resources.script,
  179. (row) => EditWebTemplates(row),
  180. null,
  181. status == DynamicMenuStatus.Enabled
  182. );
  183. column.AddItem(
  184. "Edit Styles",
  185. Properties.Resources.css,
  186. (row) => EditWebStyles(row),
  187. null,
  188. status == DynamicMenuStatus.Enabled
  189. );
  190. column.AddItem(
  191. "Edit Documents",
  192. Properties.Resources.pdf,
  193. (row) => EditWebDocuments(row),
  194. null,
  195. status == DynamicMenuStatus.Enabled
  196. );
  197. column.AddSeparator();
  198. column.AddItem(
  199. "PRS Mobile Settings",
  200. Properties.Resources.web,
  201. (row) => PRSMobileSettings(row),
  202. null,
  203. status == DynamicMenuStatus.Enabled
  204. );
  205. }
  206. else if (type.Equals(ServerType.Schedule))
  207. {
  208. column.AddSeparator();
  209. column.AddItem(
  210. "Scheduled Scripts",
  211. Properties.Resources.script,
  212. (row) => EditScheduledScripts(row),
  213. null,
  214. status == DynamicMenuStatus.Enabled
  215. );
  216. }
  217. }
  218. private ServiceController? GetService(string key)
  219. {
  220. return _services.FirstOrDefault(x => string.Equals(x.ServiceName, key));
  221. }
  222. protected override void ShowHelp(string slug)
  223. {
  224. base.ShowHelp("Server_Configuration");
  225. }
  226. public void BeforeUpdate()
  227. {
  228. var sections = PRSService.GetConfiguration().LoadAll();
  229. RefreshServices(sections);
  230. var closed = new List<string>();
  231. foreach (var service in _services)
  232. {
  233. if(service.Status == ServiceControllerStatus.Running)
  234. {
  235. service.Stop();
  236. closed.Add(service.ServiceName);
  237. }
  238. }
  239. var config = PRSService.GetConfiguration<ServerStartupSettings>();
  240. var startupSettings = config.Load();
  241. startupSettings.StartServers = closed;
  242. config.Save(startupSettings);
  243. }
  244. #region Grid Handling
  245. private void RefreshServices(Dictionary<string, ServerSettings> sections)
  246. {
  247. Interlocked.Exchange(
  248. ref _services,
  249. new ConcurrentBag<ServiceController>(
  250. ServiceController.GetServices().Where(x => sections.ContainsKey(x.ServiceName))
  251. )
  252. );
  253. }
  254. private Dictionary<String, ServiceControllerStatus> _serviceStatuses = new Dictionary<string, ServiceControllerStatus>();
  255. private Dictionary<string, bool> _secureConnections = new Dictionary<string, bool>();
  256. private Dictionary<String,RpcClientPipeTransport> _pipemonitors = new Dictionary<string, RpcClientPipeTransport>();
  257. private Dictionary<String,HttpClient> _webmonitors = new Dictionary<string, HttpClient>();
  258. protected override void Reload(Filters<Server> criteria, Columns<Server> columns, ref SortOrder<Server>? sort,
  259. Action<CoreTable?, Exception?> action)
  260. {
  261. var table = new CoreTable();
  262. table.LoadColumns(typeof(Server));
  263. var sections = PRSService.GetConfiguration().LoadAll();
  264. RefreshServices(sections);
  265. var startupConfig = PRSService.GetConfiguration<ServerStartupSettings>();
  266. var startupSettings = startupConfig.Load();
  267. foreach (var startup in startupSettings.StartServers)
  268. {
  269. _services.FirstOrDefault(x => x.ServiceName == startup)?.Start();
  270. }
  271. startupSettings.StartServers.Clear();
  272. startupConfig.Save(startupSettings);
  273. foreach (var section in sections.OrderBy(x => x.Value.Type))
  274. {
  275. var server = section.Value.CreateServer(section.Key);
  276. var service = _services.FirstOrDefault(x => string.Equals(x.ServiceName, section.Key));
  277. var row = table.NewRow();
  278. table.LoadRow(row, server);
  279. table.Rows.Add(row);
  280. }
  281. action(table, null);
  282. _monitor ??= Task.Run(
  283. () =>
  284. {
  285. while (!cancel.Token.IsCancellationRequested)
  286. {
  287. bool testcertificates = false;
  288. var certrow = table.Rows.FirstOrDefault(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Certificate);
  289. if (certrow != null)
  290. {
  291. var key = certrow.Get<Server, string>(x => x.Key);
  292. var certservice = GetService(key);
  293. certservice.Refresh();
  294. if (certservice.Status == ServiceControllerStatus.Running)
  295. testcertificates = true;
  296. }
  297. foreach (var row in table.Rows)
  298. {
  299. bool bRefresh = false;
  300. var key = row.Get<Server, string>(x => x.Key);
  301. var service = GetService(key);
  302. _serviceStatuses.TryGetValue(key, out var oldstatus);
  303. service.Refresh();
  304. _serviceStatuses[key] = service.Status;
  305. if (_serviceStatuses[key] != oldstatus)
  306. bRefresh = true;
  307. if (testcertificates && (_serviceStatuses[key] == ServiceControllerStatus.Running))
  308. {
  309. var type = row.Get<Server, ServerType>(x => x.Type);
  310. if (type == ServerType.Database)
  311. {
  312. _secureConnections.TryGetValue(key, out bool oldsecure);
  313. if (!_pipemonitors.TryGetValue(key, out RpcClientPipeTransport client))
  314. {
  315. client = new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(key, true));
  316. client.Connect();
  317. _pipemonitors[key] = client;
  318. }
  319. var info = client.IsConnected()
  320. ? client.Send<RpcInfoCommand, RpcInfoParameters, RpcInfoResult>(new RpcInfoParameters()).Info
  321. : null;
  322. _secureConnections[key] = info?.IsHTTPS ?? false;
  323. bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
  324. }
  325. else if (type == ServerType.Web)
  326. {
  327. var props = row.ToObject<Server>().Properties as WebServerProperties;
  328. _secureConnections.TryGetValue(key, out bool oldsecure);
  329. if (!_webmonitors.TryGetValue(key, out HttpClient client))
  330. {
  331. client = new HttpClient { BaseAddress = new Uri($"https://127.0.0.1:{props.ListenPort}") };
  332. _webmonitors[key] = client;
  333. }
  334. try
  335. {
  336. client.GetAsync("/").Wait();
  337. _secureConnections[key] = true;
  338. }
  339. catch (Exception e)
  340. {
  341. _secureConnections[key] = false;
  342. }
  343. bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
  344. }
  345. }
  346. else
  347. {
  348. bRefresh = bRefresh || _secureConnections.ContainsKey(key);
  349. _secureConnections.Remove(key);
  350. }
  351. if (bRefresh)
  352. Dispatcher.Invoke(() =>
  353. {
  354. if (testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Start))
  355. ActionColumns[1].Position = DynamicActionColumnPosition.Start;
  356. else if (!testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Hidden))
  357. ActionColumns[1].Position = DynamicActionColumnPosition.Hidden;
  358. Refresh(true, false);
  359. InvalidateRow(row);
  360. });
  361. }
  362. Task.Delay(TimeSpan.FromSeconds(1)).Wait();
  363. }
  364. },
  365. cancel.Token
  366. );
  367. }
  368. protected override Server LoadItem(CoreRow row)
  369. {
  370. var key = row.Get<Server, string>(x => x.Key);
  371. var settings = PRSService.GetConfiguration(key).Load();
  372. return settings.CreateServer(key);
  373. }
  374. private string CreateKey(ServerType type)
  375. {
  376. var services = ServiceController.GetServices();
  377. var key = string.Format("PRS{0}", type.ToString());
  378. var i = 1;
  379. while (services.Any(x => string.Equals(key, x.ServiceName)))
  380. key = string.Format("PRS{0}_{1}", type.ToString(), i++);
  381. return key;
  382. }
  383. private void CreateMenu(ContextMenu parent, string header, ServerType server, Type properties)
  384. {
  385. var menu = new MenuItem();
  386. menu.Header = header;
  387. menu.Tag = properties;
  388. menu.Icon = new Image() { Source = _typeimages[server] };
  389. menu.IsCheckable = false;
  390. menu.Click += (o, e) =>
  391. {
  392. var itemtype = ((o as MenuItem)?.Tag as Type)!;
  393. var props = (Activator.CreateInstance(itemtype) as ServerProperties)!;
  394. if (EditProperties(properties, props, true))
  395. {
  396. var server = CreateItem();
  397. server.Key = CreateKey(props.Type());
  398. server.Type = props.Type();
  399. server.Properties = props;
  400. SaveItem(server);
  401. Refresh(false, true);
  402. }
  403. };
  404. parent.Items.Add(menu);
  405. }
  406. protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
  407. {
  408. var menu = new ContextMenu();
  409. CreateMenu(menu, "Database", ServerType.Database, typeof(DatabaseServerProperties));
  410. CreateMenu(menu, "GPS Connector", ServerType.GPS, typeof(GPSServerProperties));
  411. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.AutoDiscovery))
  412. CreateMenu(menu, "Auto Discovery", ServerType.AutoDiscovery, typeof(AutoDiscoveryServerProperties));
  413. CreateMenu(menu, "Scheduler", ServerType.Schedule, typeof(ScheduleServerProperties));
  414. CreateMenu(menu, "Web Service", ServerType.Web, typeof(WebServerProperties));
  415. if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.Certificate))
  416. CreateMenu(menu, "HTTPS Certificate Engine", ServerType.Certificate, typeof(CertificateEngineProperties));
  417. menu.IsOpen = true;
  418. }
  419. protected override void DoEdit()
  420. {
  421. if (!SelectedRows.Any())
  422. return;
  423. var server = LoadItem(SelectedRows.First());
  424. var service = GetService(server.Key);
  425. var enabled = service == null || service.Status == ServiceControllerStatus.Stopped;
  426. if (EditProperties(server.Properties.GetType(), server.Properties, enabled))
  427. {
  428. server.Name = server.Properties.Name;
  429. SaveItem(server);
  430. Refresh(false, true);
  431. }
  432. }
  433. public override void SaveItem(Server item)
  434. {
  435. var settings = new ServerSettings();
  436. settings.Type = item.Type;
  437. settings.Properties = Serialization.Serialize(item.Properties, false);
  438. PRSService.GetConfiguration(item.Key).Save(settings);
  439. ReconfigureService(item);
  440. }
  441. private bool isServiceChanged(Server server, ServiceController? service, string newDisplayName)
  442. {
  443. return newDisplayName != service?.DisplayName || (server.Properties.HasOriginalValue(x => x.Username) && server.Properties.GetOriginalValue(x => x.Username) != server.Properties.Username);
  444. }
  445. protected override bool CanDeleteItems(params CoreRow[] rows)
  446. {
  447. var bOK = true;
  448. foreach (var row in rows)
  449. {
  450. var service = GetService(row.Get<Server, string>(x => x.Key));
  451. if (service != null && service.Status != ServiceControllerStatus.Stopped)
  452. bOK = false;
  453. }
  454. return bOK;
  455. }
  456. protected override void DeleteItems(params CoreRow[] rows)
  457. {
  458. foreach (var row in rows)
  459. {
  460. var key = row.Get<Server, string>(x => x.Key);
  461. Interlocked.Exchange(
  462. ref _services,
  463. new ConcurrentBag<ServiceController>(
  464. _services.Where(x => !string.Equals(x.ServiceName, key))
  465. )
  466. );
  467. PRSService.GetConfiguration(key).Delete();
  468. var serverType = row.Get<Server, ServerType>(x => x.Type);
  469. if (serverType == ServerType.Certificate)
  470. {
  471. if (File.Exists(CertificateEngine.CertificateFile))
  472. {
  473. File.Delete(CertificateEngine.CertificateFile);
  474. }
  475. }
  476. PRSServiceInstaller.UninstallService(key);
  477. }
  478. }
  479. protected override void DefineLookups(ILookupEditorControl sender, Server[] items)
  480. {
  481. if(sender.EditorDefinition is ComboLookupEditor lookup && lookup.Type == typeof(DatabaseServerLookupGenerator))
  482. {
  483. base.DefineLookups(sender, Data.Rows.Select(x => x.ToObject<Server>()).ToArray());
  484. }
  485. else
  486. {
  487. base.DefineLookups(sender, items);
  488. }
  489. }
  490. #endregion
  491. #region Server Configuration
  492. private bool EditUpdateChannel_Click(Button arg1, CoreRow[] arg2)
  493. {
  494. var settings = new LocalConfiguration<AutoUpdateSettings>().Load();
  495. var editable = settings.ToEditable();
  496. var buttons = new DynamicEditorButtons()
  497. {
  498. new DynamicEditorButton(
  499. "",
  500. Properties.Resources.help.AsBitmapImage(),
  501. null,
  502. (o, e) => base.ShowHelp("Automatic_Updates"))
  503. };
  504. var propertyEditor = new DynamicEditorForm(typeof(EditableAutoUpdateSettings), null, buttons);
  505. propertyEditor.OnDefineEditor += PropertyEditor_OnDefineEditor;
  506. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  507. propertyEditor.Items = new BaseObject[] { editable };
  508. if (propertyEditor.ShowDialog() == true)
  509. {
  510. settings.FromEditable(editable);
  511. new LocalConfiguration<AutoUpdateSettings>().Save(settings);
  512. }
  513. return false;
  514. }
  515. private BaseEditor? PropertyEditor_OnDefineEditor(object item, DynamicGridColumn column)
  516. {
  517. if (string.Equals(column.ColumnName, "Elevated"))
  518. return new NullEditor();
  519. var result = GetEditor(item, column);
  520. if (result != null)
  521. result = result.CloneEditor();
  522. return result;
  523. }
  524. private void ReconfigureService(Server item)
  525. {
  526. var service = GetService(item.Key);
  527. var newDisplayName = "PRS - " + item.Properties.Name;
  528. string? username = item.Properties.Username;
  529. if (!isServiceChanged(item, service, newDisplayName)) return;
  530. string? password = null;
  531. if (!string.IsNullOrWhiteSpace(username))
  532. {
  533. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  534. if(passwordEditor.ShowDialog() == true)
  535. {
  536. password = passwordEditor.Password;
  537. }
  538. else
  539. {
  540. password = null;
  541. }
  542. }
  543. else
  544. {
  545. username = null;
  546. }
  547. if (service == null)
  548. try
  549. {
  550. using (new WaitCursor())
  551. {
  552. PRSServiceInstaller.InstallService(
  553. item.Key,
  554. item.Properties.Name,
  555. newDisplayName,
  556. username,
  557. password
  558. );
  559. }
  560. }
  561. catch (Exception e)
  562. {
  563. MessageBox.Show(string.Format("Error Installing {0}: {1}", item.Key, e.Message));
  564. }
  565. else
  566. try
  567. {
  568. using (new WaitCursor())
  569. {
  570. PRSServiceInstaller.ChangeService(
  571. item.Key,
  572. item.Properties.Name,
  573. newDisplayName,
  574. username,
  575. password
  576. );
  577. }
  578. }
  579. catch (Exception e)
  580. {
  581. MessageBox.Show(string.Format("Error Configuring {0}: {1}", item.Key, e.Message));
  582. }
  583. }
  584. public bool EditProperties(Type type, ServerProperties item, bool enabled)
  585. {
  586. var pages = new DynamicEditorPages();
  587. if (type == typeof(DatabaseServerProperties))
  588. {
  589. pages.Add(new SMSProviderGrid(!enabled));
  590. }
  591. var buttons = new DynamicEditorButtons();
  592. buttons.Add(
  593. "",
  594. Properties.Resources.help.AsBitmapImage(),
  595. item,
  596. (f, i) =>
  597. {
  598. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + type.Name.SplitCamelCase().Replace(" ", "_"))
  599. { UseShellExecute = true });
  600. }
  601. );
  602. var propertyEditor = new DynamicEditorForm(type, pages, buttons);
  603. if(type == typeof(DatabaseServerProperties))
  604. {
  605. propertyEditor.OnSaveItem += (o, e) =>
  606. {
  607. propertyEditor.UnloadEditorPages(false);
  608. propertyEditor.UnloadEditorPages(true);
  609. };
  610. }
  611. propertyEditor.ReadOnly = !enabled;
  612. propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
  613. propertyEditor.Items = new BaseObject[] { item };
  614. return propertyEditor.ShowDialog() == true;
  615. }
  616. #endregion
  617. #region Service Start / Stop Actions
  618. private readonly Dictionary<int, BitmapImage> _stateimages = new()
  619. {
  620. { 0, Properties.Resources.warning.AsBitmapImage() },
  621. { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
  622. { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
  623. { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
  624. { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
  625. { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
  626. { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
  627. { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
  628. };
  629. private BitmapImage StateImage(CoreRow? arg)
  630. {
  631. if (arg == null)
  632. return Properties.Resources.tick.AsBitmapImage();
  633. var key = arg.Get<Server, string>(c => c.Key);
  634. var service = GetService(key);
  635. int state = service != null ? (int)service.Status : 0;
  636. return _stateimages[state];
  637. }
  638. private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  639. {
  640. if (arg2 == null)
  641. return null;
  642. var service = GetService(arg2.Get<Server, string>(c => c.Key));
  643. return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
  644. }
  645. private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
  646. {
  647. return arg2 != null ? arg1.TextToolTip("Server Options") : null;
  648. }
  649. private bool StateAction(CoreRow? arg)
  650. {
  651. if (arg == null)
  652. return false;
  653. var key = arg.Get<Server, string>(c => c.Key);
  654. var service = GetService(arg.Get<Server, string>(c => c.Key));
  655. if (service != null)
  656. {
  657. Task? task;
  658. if (service.Status == ServiceControllerStatus.Running)
  659. {
  660. task = Task.Run(
  661. () =>
  662. {
  663. service.Stop();
  664. Dispatcher.Invoke(()=> Refresh(false, false));
  665. });
  666. //StopConsole(key);
  667. }
  668. else if (service.Status == ServiceControllerStatus.Stopped)
  669. {
  670. task = Task.Run(
  671. () =>
  672. {
  673. service.Start();
  674. Dispatcher.Invoke(()=> Refresh(false, false));
  675. });
  676. StartConsole(arg,key);
  677. }
  678. else if (service.Status == ServiceControllerStatus.Paused)
  679. {
  680. task = Task.Run(() =>
  681. {
  682. service.Continue();
  683. Dispatcher.Invoke(()=> Refresh(false, false));
  684. });
  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, $"{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(RestClient<>), Platform.Server, 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), false);
  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(IPCClient<>), Platform.Server, 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<>), Platform.Server, 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. private bool ShowServiceStatus(Button arg1, CoreRow[] arg2)
  1115. {
  1116. List<String> domains = new List<String>();
  1117. var certservers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) == ServerType.Certificate)
  1118. .Select(row => LoadItem(row));;
  1119. foreach (var certserver in certservers)
  1120. {
  1121. var certprops = certserver.Properties as CertificateEngineProperties;
  1122. if (certprops != null)
  1123. domains.AddRange(certprops.ParseDomainNames());
  1124. }
  1125. if (!domains.Any())
  1126. domains.Add("localhost");
  1127. var servers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) != ServerType.Certificate)
  1128. .Select(row => LoadItem(row));
  1129. var statusgrid = new ServiceStatus(domains, servers);
  1130. statusgrid.ShowDialog();
  1131. return false;
  1132. }
  1133. #endregion
  1134. }
  1135. }