| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352 |
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.Mobile;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using Xamarin.Essentials;
- using Xamarin.Forms;
- using Xamarin.Forms.Xaml;
- using XF.Material.Forms.UI.Dialogs;
- using Comal.Classes;
- using Email = Xamarin.Essentials.Email;
- using InABox.Core;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using InABox.Mobile.Shared;
- using InABox.Rpc;
- namespace PRS.Mobile
- {
- [XamlCompilation(XamlCompilationOptions.Compile)]
- public partial class SettingsPage
- {
- private int count;
- private Dictionary<String,MobileDatabaseSettings> _settings;
- private string _current = "";
- private Guid[] _caches;
-
- public SettingsPage()
- {
- _settings = new LocalConfiguration<MobileDatabaseSettings>().LoadAll();
-
- _caches = _settings.Select(x => x.Value.CacheID).ToArray();
-
- _current = _settings.Any(x => x.Value.IsDefault)
- ? _settings.First(x => x.Value.IsDefault).Key
- : _settings.First().Key;
-
- InitializeComponent();
- ProgressVisible = true;
- profileButton.BackgroundColor = XF.Material.Forms.Material.Color.Secondary;
- ReloadProfiles();
- }
- private void ReloadProfiles()
- {
- while (profileMenu.Items.Count > 6)
- profileMenu.Items.RemoveAt(0);
- int i = 0;
- foreach (var key in _settings.Keys)
- {
- var profile = new MobileMenuItem() { Text = String.IsNullOrWhiteSpace(key) ? "Default Profile" : key };
- profile.Clicked += SelectProfile_Click;
- profile.BindingContext = key;
- profileMenu.Items.Insert(i, profile);
- i++;
- }
- //_restoreProfiles.IsVisible = File.Exists(GetBackupFileName());
- }
-
- private async void Save_OnClicked(object sender, EventArgs args)
- {
- StoreProfileSettings();
- new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_settings, true);
- DoClearCaches();
- ClientFactory.InvalidateUser();
- if (App.Current.Properties.ContainsKey("SessionID"))
- App.Current.Properties.Remove("SessionID");
-
- App.Data.Reset();
-
- TransportStatus connection = TransportStatus.None;
- using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Connecting"))
- {
-
- await Task.Run(() =>
- {
- CoreRepository.CacheID = _settings[_current].CacheID;
- connection = App.ConnectTransport(_settings[_current].URLs);
- var info = App.Transport.Info();
- if (info?.Logo?.Any() == true)
- File.WriteAllBytes(Path.Combine(CoreRepository.CacheFolder(),"logo.png"), info.Logo);
- });
- }
- if (connection != TransportStatus.OK)
- {
- await DisplayAlert("Connection Error", $"Unable to establish a connection!\n\nERR: {connection}", "OK");
- return;
- }
-
- //Navigation.PopToRootAsync(true);
- Navigation.PushAsync(new PinLoginPage());
- }
- private void StoreProfileSettings()
- {
- if (!String.Equals(profileName.Text, _current))
- {
- var current = _settings[_current];
- _settings.Remove(_current);
- _current = profileName.Text;
- _settings[_current] = current;
- ReloadProfiles();
- }
- _settings[_current].URLs = stringList.SaveItems();
- _settings[_current].UserID = userIDEnt.Text?.Trim() ?? string.Empty;
- _settings[_current].Password = passwordEnt.Text?.Trim() ?? string.Empty;
- }
- #region Populate Screen
- private void Populate()
- {
- PopulateConnection();
- deviceIDEnt.Text = MobileUtils.GetDeviceID();
- swVersion.Text = MobileUtils.AppVersion.InstalledVersionNumber;
- MobileUtils.AppVersion
- .IsUsingLatestVersion()
- .BeginInvokeOnMainThread(vt =>
- {
- if (vt is Task<bool> bt)
- {
- swVersion.BackgroundColor = bt.Result
- ? Color.LightGray
- : Color.Red;
- swVersion.TextColor = bt.Result
- ? Color.DimGray
- : Color.WhiteSmoke;
- }
- }
- );
-
- Task.Run(() =>
- {
- var text = InABox.Mobile.MobileLogging.ReadLog().Split('\n');
- Device.BeginInvokeOnMainThread(() =>
- {
- _log.ItemsSource = text;
- ProgressVisible = false;
- });
-
- });
- }
- private void PopulateConnection()
- {
- profileName.Text = _current;
- if (_settings[_current].URLs?.Any() ?? false)
- stringList.LoadList(_settings[_current].URLs);
- else
- stringList.LoadList(new String[] { "" });
- userIDEnt.Text = _settings[_current].UserID;
- passwordEnt.Text = _settings[_current].Password;
- }
- protected override async void OnAppearing()
- {
-
- base.OnAppearing();
-
- Populate();
-
- }
- #endregion
-
-
- private async void ResetButton_OnClicked(object sender, MobileButtonClickEventArgs args)
- {
- var confirm = await MaterialDialog.Instance.ConfirmAsync("Are your sure you wish to reset your settings?",
- "Confirm Reset", "OK", "Cancel");
- if (confirm == true)
- {
- _settings.Clear();
- _current = "Demo Database";
- _settings[_current] = new MobileDatabaseSettings();
- _settings[_current].URLs = new String[]
- {
- "demo.prsdigital.com.au:8033",
- "demo2.prsdigital.com.au:8033",
- };
- _settings[_current].UserID = "GUEST";
- _settings[_current].Password = "guest";
- _settings[_current].IsDefault = true;
- _settings[_current].CacheID = Guid.NewGuid();
- new LocalConfiguration<MobileDatabaseSettings>().SaveAll(_settings);
- DoClearCaches();
- Device.BeginInvokeOnMainThread(PopulateConnection);
- }
- }
-
- private async void EmailLogs_OnClicked(object sender, MobileButtonClickEventArgs args)
- {
- try
- {
- var message = new EmailMessage
- {
- Subject = $"Mobile Error Logs from {App.Data.Me?.Name ?? "Unknown Employee"} ({Device.RuntimePlatform } - v{MobileUtils.AppVersion.InstalledVersionNumber})",
- Body = String.Join('\n',_log.ItemsSource as String[]),
- To = new List<string> { "support@prsdigital.com.au" }
- };
- await Email.ComposeAsync(message);
- }
- catch (Exception e)
- {
- DisplayAlert("Error", "Unable to Send Email!", "OK");
- }
- }
- private async void ClearCaches_OnClicked(object sender, MobileButtonClickEventArgs args)
- {
- var confirm = await MaterialDialog.Instance.ConfirmAsync("Are your sure you wish to clear your caches?",
- "Clear Caches", "OK", "Cancel");
- if (confirm == true)
- DoClearCaches();
- }
- private void DoClearCaches()
- {
- ProgressVisible = true;
- Task.Run(() =>
- {
- foreach (var _cache in _caches)
- {
- var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),_cache.ToString());
- if (Directory.Exists(path))
- {
- var files = Directory.GetFiles(path);
- foreach (var file in files)
- File.Delete(file);
- Directory.Delete(path);
- }
- }
- }).Wait();
- ProgressVisible = false;
- }
- private void GoToAppStore_Clicked(object sender, MobileButtonClickEventArgs args)
- {
- MobileUtils.AppVersion.OpenAppInStore();
- }
- private void SelectProfile_Click(object sender, EventArgs args)
- {
- if (sender is MobileMenuItem menu)
- {
- StoreProfileSettings();
- foreach (var key in _settings.Keys)
- _settings[key].IsDefault = String.Equals(key, menu.BindingContext);
- _current = menu.BindingContext as String ?? string.Empty;
- PopulateConnection();
- }
- }
-
- private void AddProfile_Clicked(object sender, EventArgs e)
- {
- StoreProfileSettings();
- var newsettings = new MobileDatabaseSettings();
- int i = 1;
- String profile = $"New Connection";
- while (_settings.ContainsKey(profile))
- profile = $"New Connection ({i++})";
- _current = profile;
- _settings[profile] = new MobileDatabaseSettings();
- foreach (var key in _settings.Keys)
- _settings[key].IsDefault = String.Equals(key, _current);
- ReloadProfiles();
- PopulateConnection();
- }
- private async void DeleteProfile_Clicked(object sender, EventArgs e)
- {
- if (await DisplayAlert("Confirm", "Are you sure you want to delete this profile?", "OK", "Cancel"))
- {
- _settings.Remove(_current);
- if (!_settings.Any())
- _settings["New Connection"] = new MobileDatabaseSettings() { IsDefault = true };
- else
- _current = _settings.Keys.First();
- _settings[_current].IsDefault = true;
- ReloadProfiles();
- PopulateConnection();
- }
- }
-
- private async void ExportProfiles_Clicked(object sender, EventArgs e)
- {
-
- var file = Path.Combine(FileSystem.CacheDirectory, "prsmobile.json");
- File.WriteAllText(file, Serialization.Serialize(_settings));
- await Share.RequestAsync(new ShareFileRequest
- {
- Title = "Export",
- File = new ShareFile(file)
- });
-
- }
- private async void ImportProfiles_Clicked(object sender, EventArgs e)
- {
- var customFileType =
- new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
- {
- { DevicePlatform.iOS, new[] { "*.json" } },
- { DevicePlatform.Android, new[] { "*/*" } },
- });
- var options = new PickOptions
- {
- PickerTitle = "Import Profiles",
- FileTypes = customFileType,
- };
- var file = await FilePicker.PickAsync(options);
- if (file != null)
- {
- var json = await File.ReadAllTextAsync(file.FullPath);
- try
- {
- var settings = Serialization.Deserialize<Dictionary<String, MobileDatabaseSettings>>(json, true);
- if (settings != null)
- {
- _settings = settings;
- await DisplayAlert("Import", "Profiles Loaded!", "OK");
- Device.BeginInvokeOnMainThread(() =>
- {
- ReloadProfiles();
- PopulateConnection();
- });
- }
- else
- await DisplayAlert("Import", "No Profiles found in file!", "OK");
- }
- catch (Exception err)
- {
- await DisplayAlert("Import", "File is not valid!", "OK");
- }
- }
- }
-
-
- }
- }
|