Console.xaml.cs 13 KB

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