12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313 |
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.ServiceProcess;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media.Imaging;
- using Comal.Classes;
- using Comal.Stores;
- using InABox.Client.IPC;
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.Core;
- using InABox.Database;
- using InABox.Database.SQLite;
- using InABox.DynamicGrid;
- using InABox.IPC;
- using InABox.Rpc;
- using InABox.Wpf.Editors;
- using InABox.Wpf.Console;
- using InABox.WPF;
- using PRSClasses;
- using PRSServer.Forms;
- using PRSServer.Forms.DatabaseLicense;
- using RestSharp;
- using Method = RestSharp.Method;
- using Console = InABox.Wpf.Console.Console;
- using PRSServices;
- namespace PRSServer;
- class ServerStartupSettings : BaseObject, ILocalConfigurationSettings
- {
- public List<string> StartServers { get; set; } = new();
- }
- public class ServerGrid : DynamicGrid<Server>
- {
- private Task? _monitor;
- private ConcurrentBag<ServiceController> _services = new();
-
- private Button _channelButton;
- private Button _statusButton;
- private CancellationTokenSource cancel = new CancellationTokenSource();
- public ServerGrid()
- {
- ActionColumns.Add(new DynamicImageColumn(TypeImage)
- { Position = DynamicActionColumnPosition.Start, ToolTip = TypeToolTip });
-
- ActionColumns.Add(new DynamicImageColumn(SecureImage)
- { Position = DynamicActionColumnPosition.Start, ToolTip = SecureToolTip });
-
- ActionColumns.Add(new DynamicImageColumn(StateImage, StateAction)
- { Position = DynamicActionColumnPosition.End, ToolTip = StateToolTip });
- ActionColumns.Add(new DynamicMenuColumn(CreateServerMenu,ServerMenuStatus)
- { Position = DynamicActionColumnPosition.End, ToolTip = MenuToolTip });
-
- RowHeight = 40;
- FontSize = 14;
- _channelButton = AddButton("", Properties.Resources.autoupdate.AsBitmapImage(), "Change Update Channel", EditUpdateChannel_Click);
- _statusButton = AddButton("", Properties.Resources.secure.AsBitmapImage(), "Check Service Status", ShowServiceStatus);
- }
- protected override void Init()
- {
- }
- protected override void DoReconfigure(FluentList<DynamicGridOption> options)
- {
- options.AddRange(DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows, DynamicGridOption.ShowHelp);
- }
- private BitmapImage secureImage = Properties.Resources.secure.AsBitmapImage();
- private BitmapImage insecureImage = Properties.Resources.insecure.AsBitmapImage();
- private BitmapImage? SecureImage(CoreRow? row)
- {
- if(row is null)
- {
- return secureImage;
- }
- else
- {
- var key = row.Get<Server, string>(x => x.Key);
- if(_secureConnections.TryGetValue(key, out var secure))
- {
- return secure
- ? secureImage
- : insecureImage;
- }
- else
- {
- return null;
- }
- }
- }
- private FrameworkElement? SecureToolTip(DynamicActionColumn column, CoreRow? row)
- {
- if(row is null)
- {
- return column.TextToolTip("Connection Security");
- }
- else
- {
- var key = row.Get<Server, string>(x => x.Key);
- if (_secureConnections.TryGetValue(key, out var secure))
- {
- return secure
- ? column.TextToolTip("Secure (HTTPS) Connection")
- : column.TextToolTip("Insecure (HTTP) Connection");
- }
- else
- {
- return null;
- }
- }
- }
- private DynamicMenuStatus ServerMenuStatus(CoreRow arg)
- {
- if (arg == null)
- return DynamicMenuStatus.Hidden;
- var type = arg.Get<Server, ServerType>(x => x.Type);
- var service = GetService(arg.Get<Server, string>(c => c.Key));
- var running = service?.Status == ServiceControllerStatus.Running;
- if ((type == ServerType.Database) || (type == ServerType.Web) || (type == ServerType.Schedule))
- {
- return running
- ? DynamicMenuStatus.Enabled
- : DynamicMenuStatus.Disabled;
- }
- return running
- ? DynamicMenuStatus.Enabled
- : DynamicMenuStatus.Hidden;
- }
- private void CreateServerMenu(DynamicMenuColumn column, CoreRow? row)
- {
- if (row is null)
- return;
- var status = ServerMenuStatus(row);
- if (status == DynamicMenuStatus.Hidden)
- return;
- var type = row.Get<Server, ServerType>(x => x.Type);
- var key = row.Get<Server, String>(x => x.Key);
- column.AddItem(
- "View Console",
- Properties.Resources.target,
- (row) => StartConsole(row!, key),
- null,
- status == DynamicMenuStatus.Enabled && !_consoles.ContainsKey(key)
- );
- if (type.Equals(ServerType.Database))
- {
- column.AddSeparator();
- column.AddItem(
- "Custom Fields",
- Properties.Resources.service,
- (row) => EditCustomFields(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddItem(
- "Database Scripts",
- Properties.Resources.script,
- (row) => EditDatabaseScripts(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddSeparator();
- column.AddItem(
- "Update License",
- Properties.Resources.key,
- (row) => UpdateDatabaseLicense(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddSeparator();
- column.AddItem(
- "Manage Deletions",
- Properties.Resources.delete,
- (row) => ManageDeletions(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- }
- else if (type.Equals(ServerType.Web))
- {
- column.AddSeparator();
- column.AddItem(
- "Edit Templates",
- Properties.Resources.script,
- (row) => EditWebTemplates(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddItem(
- "Edit Styles",
- Properties.Resources.css,
- (row) => EditWebStyles(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddItem(
- "Edit Documents",
- Properties.Resources.pdf,
- (row) => EditWebDocuments(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- column.AddSeparator();
- column.AddItem(
- "PRS Mobile Settings",
- Properties.Resources.web,
- (row) => PRSMobileSettings(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- }
- else if (type.Equals(ServerType.Schedule))
- {
- column.AddSeparator();
- column.AddItem(
- "Scheduled Scripts",
- Properties.Resources.script,
- (row) => EditScheduledScripts(row!),
- null,
- status == DynamicMenuStatus.Enabled
- );
- }
- }
- private ServiceController? GetService(string key)
- {
- return _services.FirstOrDefault(x => string.Equals(x.ServiceName, key));
- }
- protected override void ShowHelp(string slug)
- {
- base.ShowHelp("Server_Configuration");
- }
- public void BeforeUpdate()
- {
- var sections = PRSService.GetConfiguration().LoadAll();
- RefreshServices(sections);
- var closed = new List<string>();
- foreach (var service in _services)
- {
- if(service.Status == ServiceControllerStatus.Running)
- {
- service.Stop();
- closed.Add(service.ServiceName);
- }
- }
- var config = PRSService.GetConfiguration<ServerStartupSettings>();
- var startupSettings = config.Load();
- startupSettings.StartServers = closed;
- config.Save(startupSettings);
- }
- #region Grid Handling
- private void RefreshServices(Dictionary<string, ServerSettings> sections)
- {
- Interlocked.Exchange(
- ref _services,
- new ConcurrentBag<ServiceController>(
- ServiceController.GetServices().Where(x => sections.ContainsKey(x.ServiceName))
- )
- );
- }
- private Dictionary<String, ServiceControllerStatus> _serviceStatuses = new Dictionary<string, ServiceControllerStatus>();
- private Dictionary<string, bool> _secureConnections = new Dictionary<string, bool>();
- private Dictionary<String,RpcClientPipeTransport> _pipemonitors = new Dictionary<string, RpcClientPipeTransport>();
- private Dictionary<String,HttpClient> _webmonitors = new Dictionary<string, HttpClient>();
- protected override void Reload(Filters<Server> criteria, Columns<Server> columns, ref SortOrder<Server>? sort,
- Action<CoreTable?, Exception?> action)
- {
- var table = new CoreTable();
- table.LoadColumns(typeof(Server));
- var sections = PRSService.GetConfiguration().LoadAll();
- RefreshServices(sections);
- var startupConfig = PRSService.GetConfiguration<ServerStartupSettings>();
- var startupSettings = startupConfig.Load();
- foreach (var startup in startupSettings.StartServers)
- {
- try
- {
- _services.FirstOrDefault(x => x.ServiceName == startup)?.Start();
- }
- catch(Exception e)
- {
- Logger.Send(LogType.Error, "", $"Could not start {startup}: {CoreUtils.FormatException(e)}");
- }
- }
- startupSettings.StartServers.Clear();
- startupConfig.Save(startupSettings);
- foreach (var section in sections.OrderBy(x => x.Value.Type))
- {
- var server = section.Value.CreateServer(section.Key);
- var service = _services.FirstOrDefault(x => string.Equals(x.ServiceName, section.Key));
- var row = table.NewRow();
- table.LoadRow(row, server);
- table.Rows.Add(row);
- }
-
- action(table, null);
- _monitor ??= Task.Run(
- () =>
- {
- while (!cancel.Token.IsCancellationRequested)
- {
- bool testcertificates = false;
- var certrow = table.Rows.FirstOrDefault(x => x.Get<Server, ServerType>(x => x.Type) == ServerType.Certificate);
- if (certrow != null)
- {
- var key = certrow.Get<Server, string>(x => x.Key);
- var certservice = GetService(key);
- if(certservice is not null)
- {
- certservice.Refresh();
- if (certservice.Status == ServiceControllerStatus.Running)
- testcertificates = true;
- }
- }
- foreach (var row in table.Rows)
- {
- bool bRefresh = false;
- var key = row.Get<Server, string>(x => x.Key);
-
- var service = GetService(key);
- if(service is null)
- {
- continue;
- }
- _serviceStatuses.TryGetValue(key, out var oldstatus);
- service.Refresh();
- _serviceStatuses[key] = service.Status;
- if (_serviceStatuses[key] != oldstatus)
- bRefresh = true;
- if (testcertificates && (_serviceStatuses[key] == ServiceControllerStatus.Running))
- {
- var type = row.Get<Server, ServerType>(x => x.Type);
- if (type == ServerType.Database)
- {
- _secureConnections.TryGetValue(key, out var oldsecure);
- if (!_pipemonitors.TryGetValue(key, out var client))
- {
- client = new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(key, true));
- client.Connect();
- _pipemonitors[key] = client;
- }
-
- var info = client.IsConnected()
- ? client.Send<RpcInfoCommand, RpcInfoParameters, RpcInfoResult>(new RpcInfoParameters()).Info
- : null;
- _secureConnections[key] = info?.IsHTTPS ?? false;
-
- bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
- }
- else if (type == ServerType.Web)
- {
- var props = row.ToObject<Server>().Properties as WebServerProperties;
- _secureConnections.TryGetValue(key, out var oldsecure);
- if (!_webmonitors.TryGetValue(key, out var client))
- {
- client = new HttpClient { BaseAddress = new Uri($"https://127.0.0.1:{props.ListenPort}") };
- _webmonitors[key] = client;
- }
- try
- {
- client.GetAsync("/").Wait();
- _secureConnections[key] = true;
- }
- catch (Exception e)
- {
- _secureConnections[key] = false;
- }
- bRefresh = bRefresh || (_secureConnections[key] != oldsecure);
- }
- }
- else
- {
- bRefresh = bRefresh || _secureConnections.ContainsKey(key);
- _secureConnections.Remove(key);
- }
- if (bRefresh)
- Dispatcher.Invoke(() =>
- {
- if (testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Start))
- ActionColumns[1].Position = DynamicActionColumnPosition.Start;
- else if (!testcertificates && (ActionColumns[1].Position != DynamicActionColumnPosition.Hidden))
- ActionColumns[1].Position = DynamicActionColumnPosition.Hidden;
- Refresh(true, false);
- InvalidateRow(row);
- });
- }
-
- Task.Delay(TimeSpan.FromSeconds(1)).Wait();
- }
- },
- cancel.Token
- );
- }
-
- protected override Server LoadItem(CoreRow row)
- {
- var key = row.Get<Server, string>(x => x.Key);
- var settings = PRSService.GetConfiguration(key).Load();
- return settings.CreateServer(key);
- }
- private string CreateKey(ServerType type)
- {
- var services = ServiceController.GetServices();
- var key = string.Format("PRS{0}", type.ToString());
- var i = 1;
- while (services.Any(x => string.Equals(key, x.ServiceName)))
- key = string.Format("PRS{0}_{1}", type.ToString(), i++);
- return key;
- }
- private void CreateMenu(ContextMenu parent, string header, ServerType server, Type properties)
- {
- var menu = new MenuItem();
- menu.Header = header;
- menu.Tag = properties;
- menu.Icon = new Image() { Source = _typeimages[server] };
- menu.IsCheckable = false;
- menu.Click += (o, e) =>
- {
- var itemtype = ((o as MenuItem)?.Tag as Type)!;
- var props = (Activator.CreateInstance(itemtype) as ServerProperties)!;
- if (EditProperties(properties, props, true))
- {
- var server = CreateItem();
- server.Key = CreateKey(props.Type());
- server.Type = props.Type();
- server.Properties = props;
- SaveItem(server);
- Refresh(false, true);
- }
- };
- parent.Items.Add(menu);
- }
- protected override void DoAdd(bool OpenEditorOnDirectEdit = false)
- {
- var menu = new ContextMenu();
- CreateMenu(menu, "Database", ServerType.Database, typeof(DatabaseServerProperties));
- CreateMenu(menu, "GPS Connector", ServerType.GPS, typeof(GPSServerProperties));
- if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.AutoDiscovery))
- CreateMenu(menu, "Auto Discovery", ServerType.AutoDiscovery, typeof(AutoDiscoveryServerProperties));
- CreateMenu(menu, "Scheduler", ServerType.Schedule, typeof(ScheduleServerProperties));
- CreateMenu(menu, "Web Service", ServerType.Web, typeof(WebServerProperties));
- if (!Data.Rows.Any(r => r.Get<Server, ServerType>(c => c.Type) == ServerType.Certificate))
- CreateMenu(menu, "HTTPS Certificate Engine", ServerType.Certificate, typeof(CertificateEngineProperties));
- menu.IsOpen = true;
- }
- protected override void DoEdit()
- {
- if (!SelectedRows.Any())
- return;
- var server = LoadItem(SelectedRows.First());
- var service = GetService(server.Key);
- var enabled = service == null || service.Status == ServiceControllerStatus.Stopped;
- if (EditProperties(server.Properties.GetType(), server.Properties, enabled))
- {
- server.Name = server.Properties.Name;
- SaveItem(server);
- Refresh(false, true);
- }
- }
- public override void SaveItem(Server item)
- {
- var settings = new ServerSettings();
- settings.Type = item.Type;
- settings.Properties = Serialization.Serialize(item.Properties, false);
- PRSService.GetConfiguration(item.Key).Save(settings);
- ReconfigureService(item);
- }
- private bool isServiceChanged(Server server, ServiceController? service, string newDisplayName)
- {
- return newDisplayName != service?.DisplayName || (server.Properties.HasOriginalValue(x => x.Username) && server.Properties.GetOriginalValue(x => x.Username) != server.Properties.Username);
- }
- protected override bool CanDeleteItems(params CoreRow[] rows)
- {
- var bOK = true;
- foreach (var row in rows)
- {
- var service = GetService(row.Get<Server, string>(x => x.Key));
- if (service != null && service.Status != ServiceControllerStatus.Stopped)
- bOK = false;
- }
- return bOK;
- }
- protected override void DeleteItems(params CoreRow[] rows)
- {
- foreach (var row in rows)
- {
- var key = row.Get<Server, string>(x => x.Key);
- Interlocked.Exchange(
- ref _services,
- new ConcurrentBag<ServiceController>(
- _services.Where(x => !string.Equals(x.ServiceName, key))
- )
- );
- PRSService.GetConfiguration(key).Delete();
- var serverType = row.Get<Server, ServerType>(x => x.Type);
- if (serverType == ServerType.Certificate)
- {
- if (File.Exists(CertificateEngine.CertificateFile))
- {
- File.Delete(CertificateEngine.CertificateFile);
- }
- }
- PRSServiceInstaller.UninstallService(key);
- }
- }
- protected override void DefineLookups(ILookupEditorControl sender, Server[] items, bool async = true)
- {
- if(sender.EditorDefinition is ComboLookupEditor lookup && lookup.Type == typeof(DatabaseServerLookupGenerator))
- {
- base.DefineLookups(sender, Data.Rows.Select(x => x.ToObject<Server>()).ToArray());
- }
- else
- {
- base.DefineLookups(sender, items, async);
- }
- }
- #endregion
- #region Server Configuration
- private bool EditUpdateChannel_Click(Button arg1, CoreRow[] arg2)
- {
- var settings = new LocalConfiguration<AutoUpdateSettings>().Load();
- var editable = settings.ToEditable();
- var buttons = new DynamicEditorButtons()
- {
- new DynamicEditorButton(
- "",
- Properties.Resources.help.AsBitmapImage(),
- null,
- (o, e) => base.ShowHelp("Automatic_Updates"))
- };
- var propertyEditor = new DynamicEditorForm(typeof(EditableAutoUpdateSettings), null, buttons);
- propertyEditor.OnDefineEditor += PropertyEditor_OnDefineEditor;
- propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
- propertyEditor.Items = new BaseObject[] { editable };
- if (propertyEditor.ShowDialog() == true)
- {
- settings.FromEditable(editable);
- new LocalConfiguration<AutoUpdateSettings>().Save(settings);
- }
- return false;
- }
- private BaseEditor? PropertyEditor_OnDefineEditor(object item, DynamicGridColumn column)
- {
- if (string.Equals(column.ColumnName, "Elevated"))
- return new NullEditor();
- var result = GetEditor(item, column);
- if (result != null)
- result = result.CloneEditor();
- return result;
- }
- private void ReconfigureService(Server item)
- {
- var service = GetService(item.Key);
- var newDisplayName = "PRS - " + item.Properties.Name;
- string? username = item.Properties.Username;
- if (!isServiceChanged(item, service, newDisplayName)) return;
- string? password = null;
- if (!string.IsNullOrWhiteSpace(username))
- {
- var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
- if(passwordEditor.ShowDialog() == true)
- {
- password = passwordEditor.Password;
- }
- else
- {
- password = null;
- }
- }
- else
- {
- username = null;
- }
- if (service == null)
- try
- {
- using (new WaitCursor())
- {
- PRSServiceInstaller.InstallService(
- item.Key,
- item.Properties.Name,
- newDisplayName,
- username,
- password
- );
- }
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Error Installing {0}: {1}", item.Key, e.Message));
- }
- else
- try
- {
- using (new WaitCursor())
- {
- PRSServiceInstaller.ChangeService(
- item.Key,
- item.Properties.Name,
- newDisplayName,
- username,
- password
- );
- }
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Error Configuring {0}: {1}", item.Key, e.Message));
- }
- }
- public bool EditProperties(Type type, ServerProperties item, bool enabled)
- {
- var pages = new DynamicEditorPages();
- if (type == typeof(DatabaseServerProperties))
- {
- pages.Add(new SMSProviderGrid());
- }
- var buttons = new DynamicEditorButtons();
- buttons.Add(
- "",
- Properties.Resources.help.AsBitmapImage(),
- item,
- (f, i) =>
- {
- Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + type.Name.SplitCamelCase().Replace(" ", "_"))
- { UseShellExecute = true });
- }
- );
- var propertyEditor = new DynamicEditorForm(type, pages, buttons);
- if(type == typeof(DatabaseServerProperties))
- {
- propertyEditor.OnSaveItem += (o, e) =>
- {
- propertyEditor.UnloadEditorPages(false);
- propertyEditor.UnloadEditorPages(true);
- };
- }
- propertyEditor.ReadOnly = !enabled;
- propertyEditor.OnDefineLookups += sender => DefineLookups(sender, new Server[] { });
- propertyEditor.Items = new BaseObject[] { item };
- return propertyEditor.ShowDialog() == true;
- }
- #endregion
- #region Service Start / Stop Actions
- private readonly Dictionary<int, BitmapImage> _stateimages = new()
- {
- { 0, Properties.Resources.warning.AsBitmapImage() },
- { (int)ServiceControllerStatus.Stopped, Properties.Resources.pause.AsBitmapImage() },
- { (int)ServiceControllerStatus.StartPending, Properties.Resources.working.AsBitmapImage() },
- { (int)ServiceControllerStatus.StopPending, Properties.Resources.working.AsBitmapImage() },
- { (int)ServiceControllerStatus.Running, Properties.Resources.tick.AsBitmapImage() },
- { (int)ServiceControllerStatus.ContinuePending, Properties.Resources.working.AsBitmapImage() },
- { (int)ServiceControllerStatus.PausePending, Properties.Resources.working.AsBitmapImage() },
- { (int)ServiceControllerStatus.Paused, Properties.Resources.pause.AsBitmapImage() }
- };
- private BitmapImage StateImage(CoreRow? arg)
- {
- if (arg == null)
- return Properties.Resources.tick.AsBitmapImage();
- var key = arg.Get<Server, string>(c => c.Key);
- var service = GetService(key);
- int state = service != null ? (int)service.Status : 0;
- return _stateimages[state];
- }
- private FrameworkElement? StateToolTip(DynamicActionColumn arg1, CoreRow? arg2)
- {
- if (arg2 == null)
- return null;
- var service = GetService(arg2.Get<Server, string>(c => c.Key));
- return arg1.TextToolTip(service != null ? "Current State: " + service.Status : "Not Installed");
- }
-
- private FrameworkElement? MenuToolTip(DynamicActionColumn arg1, CoreRow? arg2)
- {
- return arg2 != null ? arg1.TextToolTip("Server Options") : null;
- }
- private bool StateAction(CoreRow? arg)
- {
- if (arg == null)
- return false;
- var key = arg.Get<Server, string>(c => c.Key);
- var service = GetService(arg.Get<Server, string>(c => c.Key));
- if (service != null)
- {
- Task? task;
- if (service.Status == ServiceControllerStatus.Running)
- {
- task = Task.Run(
- () =>
- {
- service.Stop();
- Dispatcher.Invoke(()=> Refresh(false, false));
- });
- //StopConsole(key);
- }
- else if (service.Status == ServiceControllerStatus.Stopped)
- {
- task = Task.Run(
- () =>
- {
- service.Start();
- Dispatcher.Invoke(()=> Refresh(false, false));
- });
- StartConsole(arg,key);
- }
- else if (service.Status == ServiceControllerStatus.Paused)
- {
- task = Task.Run(() =>
- {
- service.Continue();
- Dispatcher.Invoke(()=> Refresh(false, false));
- });
- }
- else
- {
- MessageBox.Show(string.Format("Invalid Service State ({0})", service.Status.ToString()));
- return false;
- }
- task?.ContinueWith((e) =>
- {
- if (e.Exception?.InnerException is { } inner)
- {
- if(inner.InnerException != null)
- {
- MessageBox.Show(String.Format("Error while running service:\n{0}", inner.InnerException.Message));
- }
- else
- {
- MessageBox.Show(String.Format("Error while running service:\n{0}", inner.Message));
- }
- PRSServiceInstaller.UninstallService(arg.Get<Server, string>(x => x.Key));
- Refresh(false, true);
- }
- }, TaskScheduler.FromCurrentSynchronizationContext());
- return true;
- }
- MessageBox.Show("Cannot find Service - is it installed?");
- return false;
- }
- public void StopAll()
- {
- foreach (var service in _services.ToArray())
- if (service.Status == ServiceControllerStatus.Running)
- Task.Run(() => { service.Stop(); });
- }
- #endregion
- #region Server Type Images
- private readonly Dictionary<ServerType, BitmapImage> _typeimages = new()
- {
- { ServerType.Database, Properties.Resources.database.AsBitmapImage() },
- { ServerType.GPS, Properties.Resources.gps.AsBitmapImage() },
- { ServerType.AutoDiscovery, Properties.Resources.autodiscover.AsBitmapImage() },
- { ServerType.Schedule, Properties.Resources.schedule.AsBitmapImage() },
- { ServerType.Web, Properties.Resources.web.AsBitmapImage() },
- { ServerType.Certificate, Properties.Resources.certificate.AsBitmapImage() }
- };
- private BitmapImage TypeImage(CoreRow? arg)
- {
- if (arg == null)
- return Properties.Resources.help.AsBitmapImage();
- var type = arg.Get<Server, ServerType>(c => c.Type);
- return _typeimages[type];
- }
-
- private FrameworkElement? TypeToolTip(DynamicActionColumn arg1, CoreRow? arg2)
- {
- if (arg2 == null)
- return null;
- return arg1.TextToolTip(string.Format("{0} Service\nName: {1}",
- arg2.Get<Server, ServerType>(c => c.Type).ToString(),
- arg2.Get<Server, string>(c => c.Key)
- ));
- }
- #endregion
- #region Console Functions
- private BitmapImage? ConsoleImage(CoreRow? arg)
- {
- if (arg == null)
- return Properties.Resources.target.AsBitmapImage();
- var service = GetService(arg.Get<Server, string>(c => c.Key));
- var state = service != null ? (int)service.Status : 0;
- if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
- return Properties.Resources.target.AsBitmapImage();
- return null;
- }
- private bool ConsoleAction(CoreRow? arg)
- {
- if (arg == null)
- return false;
- var key = arg.Get<Server, string>(c => c.Key);
- var service = GetService(key);
- var state = service != null ? (int)service.Status : 0;
- if (state == (int)ServiceControllerStatus.StartPending || state == (int)ServiceControllerStatus.Running)
- StartConsole(arg, key);
- return false;
- }
- private Dictionary<String, Tuple<ServerConsole, int>> _consoles = new Dictionary<string, Tuple<ServerConsole, int>>();
- private void StartConsole(CoreRow arg, string key)
- {
- if (_consoles.ContainsKey(key))
- return;
-
- var name = arg.Get<Server, string>(c => c.Name);
- var console = new ServerConsole(key, $"{key} - {name}");
- var window = Window.GetWindow(this);
- int i = 0;
- while (_consoles.Any(x => x.Value.Item2 == i))
- i++;
-
- _consoles[key] = new Tuple<ServerConsole, int>(console, i);
-
- console.Top = window.Top + (i * 50);
- console.Left = window.Left + window.Width + 2 + (i*50);
- console.Height = window.Height;
- console.Closing += (o, e) =>
- {
- var c = o as ServerConsole;
- if (_consoles.ContainsKey(c.ServiceName))
- _consoles.Remove(c.ServiceName);
- };
- console.Show();
-
- }
- private void StopConsole(String key)
- {
- if (!_consoles.ContainsKey(key))
- return;
- var console = _consoles[key].Item1;
- console.Close();
- }
- #endregion
- #region Individual Server Buttons
- // Check if a database server is running at the given url and port
- private bool IsDatabaseServerRunning(string url, int port)
- {
- var uri = new Uri(string.Format("{0}:{1}", url, port));
- var cli = new RestClient(uri);
- var req = new RestRequest("/classes", Method.Get) { Timeout = 20000 };
- try
- {
- var res = cli.Execute(req);
- if (res.StatusCode != HttpStatusCode.OK || res.ErrorException != null)
- return false;
- return true;
- }
- catch (Exception e)
- {
- }
- return false;
- }
- // The following variables keep track of whether a database is currently being used, since if two people try to access two different databases,
- // terrible things will ensue.
- private int currentServerUsers;
- private string? currentServerURL;
- private int? currentServerPort;
- /// <summary>
- /// Configures a server for the duration of an action
- /// </summary>
- /// <typeparam name="TProperties"></typeparam>
- /// <param name="row"></param>
- /// <param name="hostaddress"></param>
- /// <param name="portnumber"></param>
- /// <param name="action"></param>
- /// <param name="blocking">
- /// If blocking is set to false, then currentServerUsers must be decreased by one manually once the
- /// task finishes
- /// </param>
- private void ConfigureServer<TProperties>(
- CoreRow row,
- Func<TProperties, string> hostaddress,
- Func<TProperties, int> portnumber,
- Action action,
- bool blocking = true
- ) where TProperties : ServerProperties
- {
- try
- {
- if (row == null)
- throw new Exception("No Row Selected!");
- var server = LoadItem(row);
- if (server == null)
- throw new Exception("Unable to load Server!");
- var props = server.Properties as TProperties;
- if (props == null)
- throw new Exception("Unable to Load Properties!");
- var url = hostaddress(props);
- var port = portnumber(props);
- using (new WaitCursor())
- {
- if (!IsDatabaseServerRunning(url, port))
- throw new Exception("Database Server is not available!");
- }
- if (action != null)
- {
- if (currentServerUsers == 0)
- {
- if (currentServerURL != url || currentServerPort != port)
- {
- ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
- ConfigurationCache.ClearAll(ConfigurationCacheType.User);
- }
- currentServerURL = url;
- currentServerPort = port;
- currentServerName = null;
- ClientFactory.SetClientType(typeof(RestClient<>), Platform.Server, CoreUtils.GetVersion(), url, port, true);
- // override the need to provide credentials when configuring the database
- ClientFactory.SetBypass();
- }
- else
- {
- if (url != currentServerURL || port != currentServerPort)
- throw new Exception(string.Format("A different Database Server ({0}:{1}) is currently in use!", currentServerURL,
- currentServerPort));
- }
- currentServerUsers++;
- action();
- if (blocking) currentServerUsers--;
- }
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
- MessageBox.Show(e.Message);
- }
- }
- private string? currentServerName;
- private void ConfigureIPCServer<TProperties>(
- CoreRow row,
- Func<TProperties, string> hostPipeName,
- Action action,
- bool blocking = true
- ) where TProperties : ServerProperties
- {
- try
- {
- if (row == null)
- throw new Exception("No Row Selected!");
- var server = LoadItem(row);
- if (server == null)
- throw new Exception("Unable to load Server!");
- var props = server.Properties as TProperties;
- if (props == null)
- throw new Exception("Unable to Load Properties!");
- var pipeName = DatabaseServerProperties.GetPipeName(hostPipeName(props), false);
- if (action != null)
- {
- if (currentServerUsers == 0)
- {
- if (currentServerName != pipeName)
- {
- ConfigurationCache.ClearAll(ConfigurationCacheType.Global);
- ConfigurationCache.ClearAll(ConfigurationCacheType.User);
- }
- currentServerPort = null;
- currentServerURL = null;
- currentServerName = pipeName;
- ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Server, CoreUtils.GetVersion(), pipeName);
- using (new WaitCursor())
- {
- if (!Client.Ping())
- {
- ClientFactory.ClearClientType();
- throw new Exception("Database Server is not available!");
- }
- }
- // override the need to provide credentials when configuring the database
- ClientFactory.SetBypass();
- }
- else
- {
- if (pipeName != currentServerName)
- throw new Exception(string.Format("A different Database Server ({0}) is currently in use!", currentServerName));
- }
- currentServerUsers++;
- try
- {
- action();
- }
- finally
- {
- if (blocking) currentServerUsers--;
- }
- }
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
- MessageBox.Show(e.Message);
- }
- }
- private void ConfigureLocalDatabase(
- CoreRow row,
- Action action
- )
- {
- try
- {
- if (row == null)
- throw new Exception("No Row Selected!");
- var server = LoadItem(row) ?? throw new Exception("Unable to load Server!");
- if (server.Properties is not DatabaseServerProperties properties)
- throw new Exception("Unable to Load Properties!");
- if (!DbFactory.IsProviderSet || DbFactory.Provider is not SQLiteProvider sql || sql.URL != properties.FileName)
- {
- ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Server, CoreUtils.GetVersion());
- Progress.ShowModal("Configuring database", (progress) =>
- {
- DbFactory.Stores = CoreUtils.TypeList(
- AppDomain.CurrentDomain.GetAssemblies(),
- myType =>
- myType.IsClass
- && !myType.IsAbstract
- && !myType.IsGenericType
- && myType.GetInterfaces().Contains(typeof(IStore))
- ).ToArray();
- DbFactory.Provider = new SQLiteProvider(properties.FileName);
- DbFactory.Start();
- StoreUtils.GoogleAPIKey = properties.GoogleAPIKey;
- PurchaseOrder.PONumberPrefix = properties.PurchaseOrderPrefix;
- Job.JobNumberPrefix = properties.JobPrefix;
- });
- }
- action();
- }
- catch(Exception e)
- {
- Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
- MessageBox.Show(e.Message);
- }
- }
-
- private bool UpdateDatabaseLicense(CoreRow selectedrow)
- {
- ConfigureIPCServer<DatabaseServerProperties>(
- selectedrow,
- //x => "http://127.0.0.1",
- //x => x.Port,
- x => selectedrow.Get<Server, string>(x => x.Key),
- () =>
- {
- new LicenseRenewalForm().ShowDialog();
- }
- );
- return false;
- }
- private bool ManageDeletions(CoreRow row)
- {
- ConfigureLocalDatabase(row, () =>
- {
- new DeletionsWindow().ShowDialog();
- });
- return false;
- }
-
- private bool EditCustomFields(CoreRow selectedrow)
- {
- ConfigureIPCServer<DatabaseServerProperties>(
- selectedrow,
- //x => "http://127.0.0.1",
- //x => x.Port,
- x => selectedrow.Get<Server, string>(x => x.Key),
- () => { new MasterList(typeof(CustomProperty), "Class", null, true).ShowDialog(); }
- );
- return false;
- }
-
- private bool EditDatabaseScripts(CoreRow selectedrow)
- {
- ConfigureIPCServer<DatabaseServerProperties>(
- selectedrow,
- //x => "http://127.0.0.1",
- //x => x.Port,
- x => selectedrow.Get<Server, string>(x => x.Key),
- () => { new MasterList(typeof(Script), "Section", null, true).ShowDialog(); }
- );
- return false;
- }
-
- private bool EditScheduledScripts(CoreRow selectedrow)
- {
- ConfigureIPCServer<ScheduleServerProperties>(
- selectedrow,
- x => x.Server,
- () => { new MasterList(typeof(ScheduledScript), "", null, true, typeof(ScheduledScriptsGrid)).ShowDialog(); }
- );
- return false;
- }
- private bool EditWebTemplates(CoreRow selectedRow)
- {
- ConfigureIPCServer<WebServerProperties>(
- selectedRow,
- x => x.Server,
- () =>
- {
- var window = new MasterList(typeof(WebTemplate), "DataModel", "", true);
- window.Closed += (e, args) => { currentServerUsers--; };
- window.Show();
- },
- false
- );
- return false;
- }
- private bool EditWebStyles(CoreRow selectedRow)
- {
- ConfigureIPCServer<WebServerProperties>(
- selectedRow,
- x => x.Server,
- () =>
- {
- var window = new MasterList(typeof(WebStyle), "Code", "", true);
- window.Closed += (e, args) => { currentServerUsers--; };
- window.Show();
- },
- false
- );
- return false;
- }
- private bool EditWebDocuments(CoreRow selectedRow)
- {
- ConfigureIPCServer<WebServerProperties>(
- selectedRow,
- x => x.Server,
- () =>
- {
- var window = new MasterList(typeof(WebDocument), "Code", "", true);
- window.Closed += (e, args) => { currentServerUsers--; };
- window.Show();
- },
- false
- );
- return false;
- }
- private bool PRSMobileSettings(CoreRow selectedrow)
- {
- ConfigureIPCServer<WebServerProperties>(
- selectedrow,
- x => x.Server,
- () =>
- {
- var editor = new DynamicEditorForm(typeof(WebSettings));
- var settings = new GlobalConfiguration<WebSettings>().Load();
- editor.Items = new[] { settings };
- if (editor.ShowDialog() == true) new GlobalConfiguration<WebSettings>().Save(settings);
- }
- );
- return false;
- }
-
- private bool ShowServiceStatus(Button arg1, CoreRow[] arg2)
- {
- List<String> domains = new List<String>();
- var certservers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) == ServerType.Certificate)
- .Select(row => LoadItem(row));;
- foreach (var certserver in certservers)
- {
- var certprops = certserver.Properties as CertificateEngineProperties;
- if (certprops != null)
- domains.AddRange(certprops.ParseDomainNames());
- }
- if (!domains.Any())
- domains.Add("localhost");
- var servers = Data.Rows.Where(row => row.Get<Server,ServerType>(c=>c.Type) != ServerType.Certificate)
- .Select(row => LoadItem(row));
- var statusgrid = new ServiceStatus(domains, servers);
- statusgrid.ShowDialog();
- return false;
- }
- #endregion
- }
|