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