Console.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using H.Pipes;
  2. using InABox.Core;
  3. using InABox.DynamicGrid;
  4. using InABox.Wpf.Editors;
  5. using InABox.WPF;
  6. using PRSServices;
  7. using System;
  8. using System.ComponentModel;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.CompilerServices;
  12. using System.Threading.Tasks;
  13. using System.Timers;
  14. using System.Windows;
  15. using InABox.Clients;
  16. using InABox.Rpc;
  17. using PRSServer;
  18. using Comal.Classes;
  19. using H.Formatters;
  20. using InABox.Wpf;
  21. using Microsoft.Win32;
  22. using PRS.Shared;
  23. namespace PRSLicensing;
  24. public class LicenseEditData : BaseObject
  25. {
  26. [EditorSequence(1)]
  27. public CustomerLink Customer => InitializeField(ref _customer, nameof(Customer));
  28. private CustomerLink? _customer;
  29. [EditorSequence(2)]
  30. public DateTime ExpiryDate { get; set; }
  31. [EditorSequence(3)]
  32. public bool IsDynamic { get; set; }
  33. }
  34. /// <summary>
  35. /// Interaction logic for MainWindow.xaml
  36. /// </summary>
  37. public partial class Console : Window, INotifyPropertyChanged
  38. {
  39. private LicensingConfiguration Settings { get; set; }
  40. private Timer timer;
  41. public event PropertyChangedEventHandler? PropertyChanged;
  42. private bool _isRunning = false;
  43. public bool IsRunning
  44. {
  45. get => _isRunning;
  46. set
  47. {
  48. _isRunning = value;
  49. OnPropertyChanged();
  50. }
  51. }
  52. private bool _isInstalled = false;
  53. public bool IsInstalled
  54. {
  55. get => _isInstalled;
  56. set
  57. {
  58. _isInstalled = value;
  59. OnPropertyChanged();
  60. }
  61. }
  62. private bool _hasDbServer = false;
  63. public bool HasDbServer
  64. {
  65. get => _hasDbServer;
  66. set
  67. {
  68. _hasDbServer = value;
  69. OnPropertyChanged();
  70. }
  71. }
  72. private PipeClient<string>? _client;
  73. private Timer? RefreshTimer;
  74. public Console()
  75. {
  76. InitializeComponent();
  77. LoadSettings();
  78. Progress.DisplayImage = PRSLicensing.Resources.splash_small.AsBitmapImage();
  79. timer = new Timer(2000);
  80. timer.Elapsed += Timer_Elapsed;
  81. timer.AutoReset = true;
  82. timer.Start();
  83. }
  84. private string GetUpdateLocation() => "https://prsdigital.com.au/updates/prs";
  85. private string GetLatestVersion(string location) => Update.GetRemoteFile($"{location}/PreRelease/version.txt").Content;
  86. private string GetReleaseNotes(string location)=> Update.GetRemoteFile($"{location}/Release Notes.txt").Content;
  87. private void Window_Loaded(object sender, RoutedEventArgs e)
  88. {
  89. Title = Title = $"PRS Licensing (Release {CoreUtils.GetVersion()})";
  90. var isUpdateAvailable = Update.CheckForUpdates(
  91. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, null, null, false, "");
  92. RefreshStatus();
  93. Progress.ShowModal("Registering Classes", progress =>
  94. {
  95. var tasks = new Task[]
  96. {
  97. Task.Run(() => CoreUtils.RegisterClasses()),
  98. Task.Run(() => ComalUtils.RegisterClasses()),
  99. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  100. };
  101. Task.WaitAll(tasks.ToArray());
  102. });
  103. }
  104. private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
  105. {
  106. RefreshStatus();
  107. }
  108. protected override void OnClosing(CancelEventArgs e)
  109. {
  110. base.OnClosing(e);
  111. _client?.DisposeAsync().AsTask().Wait();
  112. _client = null;
  113. RefreshTimer?.Stop();
  114. }
  115. private void RefreshStatus()
  116. {
  117. IsRunning = PRSServiceInstaller.IsRunning(Settings.GetServiceName());
  118. IsInstalled = PRSServiceInstaller.IsInstalled(Settings.GetServiceName());
  119. HasDbServer = !String.IsNullOrWhiteSpace(GetProperties().Server);
  120. if(_client is null)
  121. {
  122. if (IsRunning)
  123. {
  124. CreateClient();
  125. }
  126. }
  127. else if(_client.PipeName != GetPipeName())
  128. {
  129. _client.DisposeAsync().AsTask().Wait();
  130. _client = null;
  131. CreateClient();
  132. }
  133. }
  134. private bool _creatingClient = false;
  135. private void CreateClient()
  136. {
  137. if (_creatingClient) return;
  138. _creatingClient = true;
  139. var client = new PipeClient<string>(GetPipeName(), ".", formatter:new BinaryFormatter());
  140. client.MessageReceived += (o, args) =>
  141. {
  142. Dispatcher.BeginInvoke(() =>
  143. {
  144. ConsoleControl.LoadLogEntry(args.Message ?? "");
  145. });
  146. };
  147. client.Connected += (o, args) =>
  148. {
  149. Dispatcher.BeginInvoke(() =>
  150. {
  151. ConsoleControl.Enabled = true;
  152. });
  153. };
  154. client.Disconnected += (o, args) =>
  155. {
  156. Dispatcher.BeginInvoke(() =>
  157. {
  158. ConsoleControl.Enabled = false;
  159. });
  160. if (RefreshTimer == null)
  161. {
  162. RefreshTimer = new Timer(1000);
  163. RefreshTimer.Elapsed += RefreshTimer_Elapsed;
  164. }
  165. RefreshTimer.Start();
  166. };
  167. client.ExceptionOccurred += (o, args) =>
  168. {
  169. };
  170. if (!client.IsConnecting)
  171. {
  172. client.ConnectAsync();
  173. }
  174. _client = client;
  175. _creatingClient = false;
  176. }
  177. private void RefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
  178. {
  179. if (_client is null) return;
  180. if (!_client.IsConnected)
  181. {
  182. if (!_client.IsConnecting)
  183. {
  184. _client.ConnectAsync();
  185. }
  186. }
  187. else
  188. {
  189. RefreshTimer?.Stop();
  190. }
  191. }
  192. private string GetPipeName()
  193. {
  194. return Settings.GetServiceName();
  195. }
  196. private void LoadSettings()
  197. {
  198. Settings = PRSLicensingService.GetConfiguration().Load();
  199. ServiceName.Content = Settings.ServiceName;
  200. }
  201. private void SaveSettings()
  202. {
  203. PRSLicensingService.GetConfiguration().Save(Settings);
  204. }
  205. private void Install()
  206. {
  207. var username = GetProperties().Username;
  208. string? password = null;
  209. if (!string.IsNullOrWhiteSpace(username))
  210. {
  211. var passwordEditor = new PasswordDialog(string.Format("Enter password for {0}", username));
  212. if(passwordEditor.ShowDialog() == true)
  213. {
  214. password = passwordEditor.Password;
  215. }
  216. else
  217. {
  218. password = null;
  219. }
  220. }
  221. else
  222. {
  223. username = null;
  224. }
  225. PRSServiceInstaller.InstallService(
  226. Settings.GetServiceName(),
  227. "PRS Licensing Service",
  228. Settings.ServiceName,
  229. username,
  230. password);
  231. }
  232. private void InstallButton_Click(object sender, RoutedEventArgs e)
  233. {
  234. if (PRSServiceInstaller.IsInstalled(Settings.GetServiceName()))
  235. {
  236. Progress.ShowModal("Uninstalling Service", (progress) =>
  237. {
  238. PRSServiceInstaller.UninstallService(Settings.GetServiceName());
  239. });
  240. }
  241. else
  242. {
  243. Progress.ShowModal("Installing Service", (progress) =>
  244. {
  245. Install();
  246. });
  247. }
  248. RefreshStatus();
  249. }
  250. private void StartButton_Click(object sender, RoutedEventArgs e)
  251. {
  252. if (PRSServiceInstaller.IsRunning(Settings.GetServiceName()))
  253. {
  254. Progress.ShowModal("Stopping Service", (progress) =>
  255. {
  256. PRSServiceInstaller.StopService(Settings.GetServiceName());
  257. });
  258. }
  259. else
  260. {
  261. Progress.ShowModal("Starting Service", (progress) =>
  262. {
  263. PRSServiceInstaller.StartService(Settings.GetServiceName());
  264. });
  265. }
  266. RefreshStatus();
  267. }
  268. private LicensingEngineProperties GetProperties()
  269. {
  270. var properties = Serialization.Deserialize<LicensingEngineProperties>(Settings.Properties) ?? new LicensingEngineProperties();
  271. properties.Name = Settings.ServiceName;
  272. var tokens = CoreUtils.TypeList(x =>x.IsSubclassOf(typeof(LicenseToken)))
  273. .OrderBy(x => x.EntityName().Split('.').Last())
  274. .ToArray();
  275. foreach (var token in tokens)
  276. {
  277. if (!properties.Mappings.Any(x => String.Equals(x.License, token.EntityName())))
  278. properties.Mappings.Add(new LicenseProductMapping() { License = token.EntityName() });
  279. }
  280. return properties;
  281. }
  282. private bool CheckConnection()
  283. {
  284. var properties = GetProperties();
  285. if (!String.IsNullOrWhiteSpace(properties.Server))
  286. {
  287. ClientFactory.SetClientType(
  288. typeof(RpcClient<>),
  289. Platform.LicensingEngine,
  290. CoreUtils.GetVersion(),
  291. new RpcClientPipeTransport(DatabaseServerProperties.GetPipeName(properties.Server, true))
  292. );
  293. if (Client.Ping())
  294. {
  295. ClientFactory.SetBypass();
  296. return true;
  297. }
  298. }
  299. return false;
  300. }
  301. private void EditButton_Click(object sender, RoutedEventArgs e)
  302. {
  303. var grid = new DynamicItemsListGrid<LicensingEngineProperties>();
  304. grid.OnEditorLoaded += (editor, items) =>
  305. {
  306. var control = editor.FindEditor(nameof(LicensingEngineProperties.Mappings)) as ButtonEditorControl;
  307. if (control != null)
  308. {
  309. control.OnClick += (o, args) =>
  310. {
  311. DynamicItemsListGrid<LicenseProductMapping> mappinggrid =
  312. new DynamicItemsListGrid<LicenseProductMapping>();
  313. mappinggrid.OnReconfigure += options => options.Clear();
  314. mappinggrid.Items = items.First().Mappings;
  315. DynamicGridUtils.CreateGridWindow("License Mappings", mappinggrid).ShowDialog();
  316. };
  317. }
  318. };
  319. Settings.CommitChanges();
  320. var properties = GetProperties();
  321. CheckConnection();
  322. if(grid.EditItems(new LicensingEngineProperties[] { properties }))
  323. {
  324. Settings.Properties = Serialization.Serialize(properties);
  325. Settings.ServiceName = properties.Name;
  326. if (Settings.IsChanged())
  327. {
  328. if(Settings.HasOriginalValue(x => x.ServiceName) || properties.HasOriginalValue(x => x.Username))
  329. {
  330. var oldService = LicensingConfiguration.GetServiceName(Settings.GetOriginalValue(x => x.ServiceName));
  331. if (PRSServiceInstaller.IsInstalled(oldService))
  332. {
  333. Progress.ShowModal("Modifying Service", (progress) =>
  334. {
  335. PRSServiceInstaller.UninstallService(oldService);
  336. Install();
  337. });
  338. }
  339. }
  340. SaveSettings();
  341. ServiceName.Content = Settings.ServiceName;
  342. RefreshStatus();
  343. }
  344. }
  345. }
  346. protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
  347. {
  348. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  349. }
  350. private void GenerateButton_Click(object sender, RoutedEventArgs e)
  351. {
  352. if (!CheckConnection())
  353. {
  354. MessageWindow.ShowMessage("Unable to connect to Server", "Error");
  355. return;
  356. }
  357. var ofd = new OpenFileDialog()
  358. {
  359. FileName = "license.request",
  360. Filter = "Request Files (*.request)|*.request"
  361. };
  362. if (ofd.ShowDialog() == true && System.IO.File.Exists(ofd.FileName))
  363. {
  364. var text = System.IO.File.ReadAllText(ofd.FileName);
  365. if (LicenseUtils.TryDecryptLicenseRequest(text, out var request, out var _))
  366. {
  367. var data = new LicenseEditData();
  368. data.Customer.ID = request.CustomerID;
  369. data.IsDynamic = request.IsDynamic;
  370. var grid = new DynamicItemsListGrid<LicenseEditData>();
  371. grid.OnValidate += (o, items, errors) =>
  372. {
  373. if (items.Any(x => x.Customer.ID == Guid.Empty))
  374. errors.Add("Customer may not be blank!");
  375. if (items.Any(x => x.ExpiryDate <= DateTime.Today))
  376. errors.Add("Expiry must be in the future!");
  377. };
  378. if (grid.EditItems(new LicenseEditData[] { data }))
  379. {
  380. var license = new LicenseData()
  381. {
  382. CustomerID = data.Customer.ID,
  383. Expiry = data.ExpiryDate,
  384. RenewalAvailable = data.ExpiryDate.AddMonths(-1),
  385. LastRenewal = DateTime.Today,
  386. Addresses = request.Addresses,
  387. IsDynamic = data.IsDynamic
  388. };
  389. SaveFileDialog sfd = new SaveFileDialog()
  390. {
  391. FileName = "license.key"
  392. };
  393. if (sfd.ShowDialog() == true)
  394. File.WriteAllText(sfd.FileName, LicenseUtils.EncryptLicense(license));
  395. }
  396. }
  397. else
  398. MessageWindow.ShowMessage("Invalid Request File","Error");
  399. }
  400. }
  401. }