SettingsPage.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. using InABox.Clients;
  2. using InABox.Configuration;
  3. using InABox.Mobile;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using Xamarin.Essentials;
  8. using Xamarin.Forms;
  9. using Xamarin.Forms.Xaml;
  10. using XF.Material.Forms.UI.Dialogs;
  11. using Comal.Classes;
  12. using Email = Xamarin.Essentials.Email;
  13. using InABox.Core;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using InABox.Mobile.Shared;
  18. using InABox.Rpc;
  19. namespace PRS.Mobile
  20. {
  21. [XamlCompilation(XamlCompilationOptions.Compile)]
  22. public partial class SettingsPage
  23. {
  24. private int count;
  25. private Dictionary<String,MobileDatabaseSettings> _settings;
  26. private string _current = "";
  27. private Guid[] _caches;
  28. public SettingsPage()
  29. {
  30. _settings = new LocalConfiguration<MobileDatabaseSettings>().LoadAll();
  31. _caches = _settings.Select(x => x.Value.CacheID).ToArray();
  32. _current = _settings.Any(x => x.Value.IsDefault)
  33. ? _settings.First(x => x.Value.IsDefault).Key
  34. : _settings.First().Key;
  35. InitializeComponent();
  36. ProgressVisible = true;
  37. profileButton.BackgroundColor = XF.Material.Forms.Material.Color.Secondary;
  38. ReloadProfiles();
  39. }
  40. private void ReloadProfiles()
  41. {
  42. while (profileMenu.Items.Count > 6)
  43. profileMenu.Items.RemoveAt(0);
  44. int i = 0;
  45. foreach (var key in _settings.Keys)
  46. {
  47. var profile = new MobileMenuItem() { Text = String.IsNullOrWhiteSpace(key) ? "Default Profile" : key };
  48. profile.Clicked += SelectProfile_Click;
  49. profile.BindingContext = key;
  50. profileMenu.Items.Insert(i, profile);
  51. i++;
  52. }
  53. //_restoreProfiles.IsVisible = File.Exists(GetBackupFileName());
  54. }
  55. private async void Save_OnClicked(object sender, EventArgs args)
  56. {
  57. StoreProfileSettings();
  58. new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_settings, true);
  59. DoClearCaches();
  60. ClientFactory.InvalidateUser();
  61. if (App.Current.Properties.ContainsKey("SessionID"))
  62. App.Current.Properties.Remove("SessionID");
  63. App.Data.Reset();
  64. TransportStatus connection = TransportStatus.None;
  65. using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Connecting"))
  66. {
  67. await Task.Run(() =>
  68. {
  69. CoreRepository.CacheID = _settings[_current].CacheID;
  70. connection = App.ConnectTransport(_settings[_current].URLs);
  71. var info = App.Transport.Info();
  72. if (info?.Logo?.Any() == true)
  73. File.WriteAllBytes(Path.Combine(CoreRepository.CacheFolder(),"logo.png"), info.Logo);
  74. });
  75. }
  76. if (connection != TransportStatus.OK)
  77. {
  78. await DisplayAlert("Connection Error", $"Unable to establish a connection!\n\nERR: {connection}", "OK");
  79. return;
  80. }
  81. //Navigation.PopToRootAsync(true);
  82. Navigation.PushAsync(new PinLoginPage());
  83. }
  84. private void StoreProfileSettings()
  85. {
  86. if (!String.Equals(profileName.Text, _current))
  87. {
  88. var current = _settings[_current];
  89. _settings.Remove(_current);
  90. _current = profileName.Text;
  91. _settings[_current] = current;
  92. ReloadProfiles();
  93. }
  94. _settings[_current].URLs = stringList.SaveItems();
  95. _settings[_current].UserID = userIDEnt.Text?.Trim() ?? string.Empty;
  96. _settings[_current].Password = passwordEnt.Text?.Trim() ?? string.Empty;
  97. }
  98. #region Populate Screen
  99. private void Populate()
  100. {
  101. PopulateConnection();
  102. deviceIDEnt.Text = MobileUtils.GetDeviceID();
  103. swVersion.Text = MobileUtils.AppVersion.InstalledVersionNumber;
  104. MobileUtils.AppVersion
  105. .IsUsingLatestVersion()
  106. .BeginInvokeOnMainThread(vt =>
  107. {
  108. if (vt is Task<bool> bt)
  109. {
  110. swVersion.BackgroundColor = bt.Result
  111. ? Color.LightGray
  112. : Color.Red;
  113. swVersion.TextColor = bt.Result
  114. ? Color.DimGray
  115. : Color.WhiteSmoke;
  116. }
  117. }
  118. );
  119. Task.Run(() =>
  120. {
  121. var text = InABox.Mobile.MobileLogging.ReadLog().Split('\n');
  122. Device.BeginInvokeOnMainThread(() =>
  123. {
  124. _log.ItemsSource = text;
  125. ProgressVisible = false;
  126. });
  127. });
  128. }
  129. private void PopulateConnection()
  130. {
  131. profileName.Text = _current;
  132. if (_settings[_current].URLs?.Any() ?? false)
  133. stringList.LoadList(_settings[_current].URLs);
  134. else
  135. stringList.LoadList(new String[] { "" });
  136. userIDEnt.Text = _settings[_current].UserID;
  137. passwordEnt.Text = _settings[_current].Password;
  138. }
  139. protected override async void OnAppearing()
  140. {
  141. base.OnAppearing();
  142. Populate();
  143. }
  144. #endregion
  145. private async void ResetButton_OnClicked(object sender, MobileButtonClickEventArgs args)
  146. {
  147. var confirm = await MaterialDialog.Instance.ConfirmAsync("Are your sure you wish to reset your settings?",
  148. "Confirm Reset", "OK", "Cancel");
  149. if (confirm == true)
  150. {
  151. _settings.Clear();
  152. _current = "Demo Database";
  153. _settings[_current] = new MobileDatabaseSettings();
  154. _settings[_current].URLs = new String[]
  155. {
  156. "demo.prsdigital.com.au:8033",
  157. "demo2.prsdigital.com.au:8033",
  158. };
  159. _settings[_current].UserID = "GUEST";
  160. _settings[_current].Password = "guest";
  161. _settings[_current].IsDefault = true;
  162. _settings[_current].CacheID = Guid.NewGuid();
  163. new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_settings);
  164. DoClearCaches();
  165. Device.BeginInvokeOnMainThread(PopulateConnection);
  166. }
  167. }
  168. private async void EmailLogs_OnClicked(object sender, MobileButtonClickEventArgs args)
  169. {
  170. try
  171. {
  172. var message = new EmailMessage
  173. {
  174. Subject = $"Mobile Error Logs from {App.Data.Me?.Name ?? "Unknown Employee"} ({Device.RuntimePlatform } - v{MobileUtils.AppVersion.InstalledVersionNumber})",
  175. Body = String.Join('\n',_log.ItemsSource as String[]),
  176. To = new List<string> { "support@prsdigital.com.au" }
  177. };
  178. await Email.ComposeAsync(message);
  179. }
  180. catch (Exception e)
  181. {
  182. DisplayAlert("Error", "Unable to Send Email!", "OK");
  183. }
  184. }
  185. private async void ClearCaches_OnClicked(object sender, MobileButtonClickEventArgs args)
  186. {
  187. var confirm = await MaterialDialog.Instance.ConfirmAsync("Are your sure you wish to clear your caches?",
  188. "Clear Caches", "OK", "Cancel");
  189. if (confirm == true)
  190. DoClearCaches();
  191. }
  192. private void DoClearCaches()
  193. {
  194. ProgressVisible = true;
  195. Task.Run(() =>
  196. {
  197. foreach (var _cache in _caches)
  198. {
  199. var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),_cache.ToString());
  200. if (Directory.Exists(path))
  201. {
  202. var files = Directory.GetFiles(path);
  203. foreach (var file in files)
  204. File.Delete(file);
  205. Directory.Delete(path);
  206. }
  207. }
  208. }).Wait();
  209. ProgressVisible = false;
  210. }
  211. private void GoToAppStore_Clicked(object sender, MobileButtonClickEventArgs args)
  212. {
  213. MobileUtils.AppVersion.OpenAppInStore();
  214. }
  215. private void SelectProfile_Click(object sender, EventArgs args)
  216. {
  217. if (sender is MobileMenuItem menu)
  218. {
  219. StoreProfileSettings();
  220. foreach (var key in _settings.Keys)
  221. _settings[key].IsDefault = String.Equals(key, menu.BindingContext);
  222. _current = menu.BindingContext as String ?? string.Empty;
  223. PopulateConnection();
  224. }
  225. }
  226. private void AddProfile_Clicked(object sender, EventArgs e)
  227. {
  228. StoreProfileSettings();
  229. var newsettings = new MobileDatabaseSettings();
  230. int i = 1;
  231. String profile = $"New Connection";
  232. while (_settings.ContainsKey(profile))
  233. profile = $"New Connection ({i++})";
  234. _current = profile;
  235. _settings[profile] = new MobileDatabaseSettings();
  236. foreach (var key in _settings.Keys)
  237. _settings[key].IsDefault = String.Equals(key, _current);
  238. ReloadProfiles();
  239. PopulateConnection();
  240. }
  241. private async void DeleteProfile_Clicked(object sender, EventArgs e)
  242. {
  243. if (await DisplayAlert("Confirm", "Are you sure you want to delete this profile?", "OK", "Cancel"))
  244. {
  245. _settings.Remove(_current);
  246. if (!_settings.Any())
  247. _settings["New Connection"] = new MobileDatabaseSettings() { IsDefault = true };
  248. else
  249. _current = _settings.Keys.First();
  250. _settings[_current].IsDefault = true;
  251. ReloadProfiles();
  252. PopulateConnection();
  253. }
  254. }
  255. private async void ExportProfiles_Clicked(object sender, EventArgs e)
  256. {
  257. var file = Path.Combine(FileSystem.CacheDirectory, "prsmobile.json");
  258. File.WriteAllText(file, Serialization.Serialize(_settings));
  259. await Share.RequestAsync(new ShareFileRequest
  260. {
  261. Title = "Export",
  262. File = new ShareFile(file)
  263. });
  264. }
  265. private async void ImportProfiles_Clicked(object sender, EventArgs e)
  266. {
  267. var customFileType =
  268. new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
  269. {
  270. { DevicePlatform.iOS, new[] { "*.json" } },
  271. { DevicePlatform.Android, new[] { "*/*" } },
  272. });
  273. var options = new PickOptions
  274. {
  275. PickerTitle = "Import Profiles",
  276. FileTypes = customFileType,
  277. };
  278. var file = await FilePicker.PickAsync(options);
  279. if (file != null)
  280. {
  281. var json = await File.ReadAllTextAsync(file.FullPath);
  282. try
  283. {
  284. var settings = Serialization.Deserialize<Dictionary<String, MobileDatabaseSettings>>(json, true);
  285. if (settings != null)
  286. {
  287. _settings = settings;
  288. await DisplayAlert("Import", "Profiles Loaded!", "OK");
  289. Device.BeginInvokeOnMainThread(() =>
  290. {
  291. ReloadProfiles();
  292. PopulateConnection();
  293. });
  294. }
  295. else
  296. await DisplayAlert("Import", "No Profiles found in file!", "OK");
  297. }
  298. catch (Exception err)
  299. {
  300. await DisplayAlert("Import", "File is not valid!", "OK");
  301. }
  302. }
  303. }
  304. }
  305. }