public BackgroundViewModel(IAppSettings settings, IUserDialogs dialogs) { this.ServiceUuid = settings.BackgroundScanServiceUuid.ToString(); this.IsEnabled = settings.EnableBackgroundScan; this.WhenAnyValue(x => x.IsEnabled) .Skip(1) .Subscribe(x => { if (!x) { settings.EnableBackgroundScan = false; } else { var uuid = Guid.Empty; if (!Guid.TryParse(this.ServiceUuid, out uuid)) { dialogs.Alert("Invalid UUID"); } else { settings.EnableBackgroundScan = true; settings.BackgroundScanServiceUuid = uuid; dialogs.Alert("Background Settings Updated", "Success"); } } }); }
async Task LoginToMenu() { var user = new UserToLoginDto { UserName = Login, Password = this.Password }; try { LoggedUserDto loggedUser = await _api.Login(user); if (loggedUser.UserType == "P") { ShowViewModel <MenuPoliceViewModel>(); _userDialogs.Alert("Logged as Police"); } else if (loggedUser.UserType == "U") { ShowViewModel <MenuViewModel>(); _userDialogs.Alert("Logged as User"); } else { ShowViewModel <MenuPoliceViewModel>(); //_userDialogs.Alert("Logged as Admin"); } } catch (Exception ex) { _userDialogs.Alert(ex.Message); } }
void StateChangedEvent(object sender, CSLibrary.Events.OnStateChangedEventArgs e) { InvokeOnMainThread(() => { switch (e.state) { case CSLibrary.Constants.RFState.IDLE: ClassBattery.SetBatteryMode(ClassBattery.BATTERYMODE.IDLE); _cancelVoltageValue = true; switch (BleMvxApplication._reader.rfid.LastMacErrorCode) { case 0x00: // normal end break; case 0x0309: // _userDialogs.Alert("Too near to metal, please move CS108 away from metal and start inventory again."); break; default: _userDialogs.Alert("Mac error : 0x" + BleMvxApplication._reader.rfid.LastMacErrorCode.ToString("X4")); break; } break; } }); }
public async Task EditCase() { var CaseToEdit = new CaseDto { CaseId = CaseId, RefNumber = RefNumber, FirstName = FirstName, SecondName = SecondName, CaseStatus = CaseStatus, ReportDate = ReportDate, Address = Address, PhoneNumber = PhoneNumber, Email = Email, OfficerId = OfficerId, TypeOfCrime = TypeOfCrime }; try { await _api.UpdateCase(CaseToEdit); Close(this); _userDialogs.Alert("Case updated!"); } catch { _userDialogs.Alert("We had a problem handling your request."); } }
public static async Task <T> TryTask <T>(IUserDialogs userDialogs, Func <Task <T> > operation, string badRequest = null, string unauthorized = null, string notFound = null, string defaultMsg = null) { try { return(await operation()); } catch (HttpResponseException ex) when(ex.StatusCode == HttpStatusCode.BadRequest) { userDialogs.Alert(badRequest ?? "Der var fejl i det angivne data", "Data fejl"); } catch (HttpResponseException ex) when(ex.StatusCode == HttpStatusCode.Unauthorized) { userDialogs.Alert(unauthorized ?? "Login er krævet for at bruge denne funktion. Log venligst ind", "Login mangler"); } catch (HttpResponseException ex) when(ex.StatusCode == HttpStatusCode.NotFound) { userDialogs.Alert(notFound ?? "Det anmodne data kunne ikke findes på serveren", "Ikke fundet"); } catch (HttpResponseException) { userDialogs.Alert(defaultMsg ?? "En ukendt fejl opstod på serveren. Prøv igen senere", "Fejl"); } catch (Exception) { userDialogs.Alert("En ukendt fejl opstod. Prøv igen senere", "Fejl"); } return(default(T)); }
public async void Login() { try { if (CurrentRole.Value.Equals(RolesEnum.Продавец.ToString())) { roleLog <MainViewModel>(_loginService); } else if (CurrentRole.Value.Equals(RolesEnum.Управляющий.ToString())) { roleLog <StatisticOwnerViewModel>(_ownerAuthService); } else { var toastConfig = new ToastConfig("Выберете роль!") { BackgroundColor = Color.DarkRed }; this._userArcDialogs.Toast(toastConfig); } } catch (System.Exception) { _userArcDialogs.Loading().Hide(); _userArcDialogs.Alert("Ошибка авторизации", "Неправильный логин или пароль"); } }
/// <summary> /// Handles the selection of a device by the user /// </summary> /// <param name="deviceViewModel">Device view model.</param> private async void HandleSelectedDevice() { _log.Info("Attempting to handle selected bluetooth device"); // Check bluetooth status and if not on, exit if (!_bluetoothService.IsOn) { _log.Info("Bluetooth is not on"); _userDialogs.Toast($"\tError: {_bluetoothService.StateText}"); return; } // Device is already connected if (IsConnected) { _log.Info("Device is already connected. Attempting to disconnect."); Task.Run(async() => await TryToDisconnectDevice()); _log.Debug("Disconnection task <TryToDisconnectDevice> has been spawned."); return; } // Device has not connected yet else { _log.Info("Connecting to device."); var slots = _deviceSlotService.GetAvailableSlots(); var buttons = new List <string>(); if (slots.Count > 0) { foreach (var slotIndex in slots) { try { string name = _deviceSlotService.SlotName[slotIndex]; buttons.Add(name); } catch (KeyNotFoundException) { _userDialogs.Alert("Invalid slot index value"); return; } } var result = await _userDialogs.ActionSheetAsync("Which device?", "Cancel", null, null, buttons.ToArray()); if (result == "Cancel") { return; } var selected = _deviceSlotService.SlotName.IndexOf(result); await Task.Run(async() => await TryToConnectDevice(selected)); return; } else { _userDialogs.Alert("Please disconnect from a device before attempt to connect to another one"); } } }
private async Task Disconnect() { try { await _adapter.DisconnectDeviceAsync(_band.Device); } catch (Exception ex) { _userDialogs.Alert(ex.Message, $"Error al desconectarse de {_band.Device.Name}"); } }
private bool IsAnyFieldEmpty() { if (string.IsNullOrWhiteSpace(_userRegistration) || string.IsNullOrWhiteSpace(_userPassword)) { _dialog.Alert(message: "Não podem haver campos vazios!", okText: "OK"); return(true); } return(false); }
public MainViewModel() { this.ActionSheet = new Command(() => { this.dialogs.ActionSheet( new ActionSheetConfig { Title = "TEST ACTIONSHEET", Message = "HELL I AM TALKING TO YOU", } .Add("1", () => dialogs.Alert("1")) .Add("2", () => dialogs.Alert("2")) ); }); this.Alert = new Command(async() => { await this.dialogs .Alert(new AlertConfig { Title = "TEST TITLE", Message = "This is a really long piece of text that can fit in a scrollview. You can ramble on and on and on and on and on and on and on", OkLabel = "HI" }); }); this.Confirm = new Command(async() => { var result = await this.dialogs .Confirm(new ConfirmConfig { Title = "TEST TITLE", Message = "This is a really long piece of text that can fit in a scrollview. You can ramble on and on and on and on and on and on and on", OkLabel = "Yes", CancelLabel = "No" }); }); this.Prompt = new Command(async() => { var result = await this.dialogs.Prompt("Test", "Hello"); this.dialogs.Toast($"OK: {result.Ok} - Text: {result.Value}"); }); this.Toast = new Command(() => { this.dialogs.Toast(new ToastConfig { Message = "Hello from the toast window", MessageTextColor = Color.White, BackgroundColor = Color.Black, DisplayTime = TimeSpan.FromSeconds(5), OnTap = () => { } }); }); }
public void AddOption() { if (IsFieldBlank(OptionEntry)) { _dialog.Alert(message: "Não se pode adicionar uma opção vazia!", okText: "OK"); } else { Options.Add(OptionEntry); OptionEntry = null; } }
private async Task SetupBT() { try { await App.BTService.Connect(); App.BTService.RcvdDataHandler += BTService_RcvdDataHandler; //App.BTService. += BTService_PropertyChanged; } catch (Exception ex) { Dialogs.Alert($"Sorry an error while setting up the BT connection - {ex.Message}"); } }
private async Task ActionStartMeasurement() { try { IsBusy = false; SensorReadCount = 0; await App.BTService.SendUARTCommand("M0"); await App.BTService.SendUARTCommand("A7"); } catch (Exception ex) { Dialogs.Alert($"Sorry an error sneding the command - {ex.Message}"); } }
public ReactiveAddIncomeTransactionViewModel(ITransactionService transactionService, IViewModelNavigationService navigationService, ICategoriesService categoriesService, IUserDialogs userDialogs) { _transactionService = transactionService; _navigationService = navigationService; _categoriesService = categoriesService; var isValidCategory = this.WhenAnyValue(m => m.SelectedCategory) .Select(c => c != null); var isValidValue = this.WhenAnyValue(m => m.Value) .Select(IsValidValue); var canAddTransaction = isValidCategory.Merge(isValidValue); AddTransactionCommand = ReactiveCommand.CreateFromObservable <Unit>(AddTransactionAsync, canAddTransaction); GetCategories = ReactiveCommand.CreateFromObservable <Unit, IEnumerable <CategoryModel> >(GetCategoriesAsync); _categories = GetCategories .Select(categories => new ObservableCollection <CategoryModel>(categories)) .Select(categories => new ReadOnlyObservableCollection <CategoryModel>(categories)) .ToProperty(this, vm => vm.Categories); AddTransactionCommand.ThrownExceptions.Subscribe(ex => userDialogs.Alert(ex.Message)); AddTransactionCommand .Subscribe(Observer.Create <Unit>(OnAddTransactionComplete)); StateObservable .Where(s => s == ViewModelState.Disappered) .Subscribe(Observer.Create <ViewModelState>(ClearData)); StateObservable.Where(s => s == ViewModelState.Appeared) .Select(_ => Unit.Default) .InvokeCommand(GetCategories); }
private async Task DeleteComment(CommentResponse commentResponse) { await _commentsService.DeleteCommentAsync(commentResponse.Comment.Id); _userDialogs.Alert(message: "Удаление произведено успешно", okText: "OK"); await RequestComments(InitComment.Comment.Id); }
void LoginUser() { // TODO: Replace with actual logic try { _userService.Save(new User { CreatedBy = "Test", CreatedOn = DateTime.Now, Email = "*****@*****.**", FirstName = "Test", Id = "2f89db5ae1e04679a22cd48167969a08", LastName = "User" }); var user = _userService.GetByEmail(Username); if (user == null) { AddLoginError(); _userDialog.Alert("Error", "Login Failed!"); return; } // Navigate to the home view model. _navigationService.Navigate <HomeViewModel, User>(user); } catch (Exception ex) { // TODO: Implement logging service AddLoginError(); } }
public static Task Alert(this IUserDialogs dialogs, string message, string title = null, string okText = null) => dialogs.Alert(new AlertConfig { Title = title, Message = message, OkLabel = okText });
protected async Task CheckPasswordAsync() { if (string.IsNullOrWhiteSpace(PasswordCell.Entry.Text)) { await DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), AppResources.Ok); return; } var key = _cryptoService.MakeKeyFromPassword(PasswordCell.Entry.Text, _authService.Email); if (key.SequenceEqual(_cryptoService.Key)) { _settings.AddOrUpdateValue(Constants.Locked, false); await Navigation.PopModalAsync(); } else { // TODO: keep track of invalid attempts and logout? _userDialogs.Alert(AppResources.InvalidMasterPassword); PasswordCell.Entry.Text = string.Empty; PasswordCell.Entry.Focus(); } }
public ErrorLogsViewModel(SampleSqliteConnection conn, IUserDialogs dialogs) { this.Load = ReactiveCommand.CreateFromTask(async() => { var results = await conn .Errors .OrderByDescending(x => x.Timestamp) .ToListAsync(); this.Logs = results .Select(x => new CommandItem { Text = x.Timestamp.ToString(), Detail = x.Description, PrimaryCommand = ReactiveCommand.Create(() => dialogs.Alert(x.Description) ) }) .ToList(); this.HasErrors = results.Any(); }); this.Clear = ReactiveCommand.CreateFromTask(async() => { await conn.DeleteAllAsync <ErrorLog>(); await this.Load.Execute(); }); this.BindBusyCommand(this.Load); }
public ToastsViewModel(IUserDialogs dialogs) : base(dialogs) { this.SecondsDuration = 3; this.ActionText = "Ok"; this.Message = "This is a test of the emergency toast system"; this.ActionTextColor = ToHex(Color.White); this.MessageTextColor = ToHex(Color.White); this.BackgroundColor = ToHex(Color.Blue); this.Open = new Command(async() => { // var icon = await BitmapLoader.Current.LoadFromResource("emoji_cool_small.png", null, null); ToastConfig.DefaultBackgroundColor = System.Drawing.Color.AliceBlue; ToastConfig.DefaultMessageTextColor = System.Drawing.Color.Red; ToastConfig.DefaultActionTextColor = System.Drawing.Color.DarkRed; //var bgColor = FromHex(this.BackgroundColor); //var msgColor = FromHex(this.MessageTextColor); //var actionColor = FromHex(this.ActionTextColor); dialogs.Toast(new ToastConfig(this.Message) //.SetBackgroundColor(bgColor) //.SetMessageTextColor(msgColor) .SetDuration(TimeSpan.FromSeconds(this.SecondsDuration)) //.SetIcon(icon) .SetAction(x => x .SetText(this.ActionText) //.SetTextColor(actionColor) .SetAction(() => dialogs.Alert("You clicked the primary button")) ) ); }); }
public ToastsViewModel(IUserDialogs dialogs) : base(dialogs) { this.SecondsDuration = 3; this.ActionText = "Ok"; this.Message = "This is a test of the emergency toast system"; this.ActionTextColor = ToHex(Color.White); this.MessageTextColor = ToHex(Color.White); this.BackgroundColor = ToHex(Color.Blue); this.Open = new Command(() => { ToastConfig.DefaultBackgroundColor = System.Drawing.Color.AliceBlue; ToastConfig.DefaultMessageTextColor = System.Drawing.Color.Red; ToastConfig.DefaultActionTextColor = System.Drawing.Color.DarkRed; //var bgColor = FromHex(this.BackgroundColor); //var msgColor = FromHex(this.MessageTextColor); //var actionColor = FromHex(this.ActionTextColor); dialogs.Toast(new ToastConfig(this.Message) //.SetBackgroundColor(bgColor) //.SetMessageTextColor(msgColor) .SetDuration(TimeSpan.FromSeconds(this.SecondsDuration)) .SetAction(x => x .SetText(this.ActionText) //.SetTextColor(actionColor) .SetAction(() => dialogs.Alert("You clicked the primary button")) ) ); }); }
public CreateViewModel(INotificationManager notificationManager, IUserDialogs dialogs) { this.WhenAnyValue ( x => x.SelectedDate, x => x.SelectedTime ) .Select(x => new DateTime( x.Item1.Year, x.Item1.Month, x.Item1.Day, x.Item2.Hours, x.Item2.Minutes, x.Item2.Seconds) ) .ToPropertyEx(this, x => x.ScheduledTime); this.SelectedDate = DateTime.Now; this.SelectedTime = DateTime.Now.TimeOfDay.Add(TimeSpan.FromMinutes(10)); this.SendNow = ReactiveCommand.CreateFromTask(() => notificationManager.Send(new Notification { Title = "Test Now", Message = "This is a test of the sendnow stuff", Payload = this.Payload }) ); this.Send = ReactiveCommand.CreateFromTask( async() => { await notificationManager.Send(new Notification { Title = this.NotificationTitle, Message = this.NotificationMessage, Payload = this.Payload, BadgeCount = this.BadgeCount, ScheduleDate = this.ScheduledTime }); this.NotificationTitle = String.Empty; this.NotificationMessage = String.Empty; this.Payload = String.Empty; await dialogs.Alert("Notification Sent Successfully"); }, this.WhenAny( x => x.NotificationTitle, x => x.NotificationMessage, x => x.ScheduledTime, (title, msg, sch) => !title.GetValue().IsEmpty() && !msg.GetValue().IsEmpty() && sch.GetValue() > DateTime.Now ) ); this.PermissionCheck = ReactiveCommand.CreateFromTask(async() => { var result = await notificationManager.RequestAccess(); dialogs.Toast("Permission Check Result: " + result); }); }
public void Purchase_Ride_Credits() { RhodeITService rhodeITServices = new RhodeITService(); RhodeITDB db = new RhodeITDB(); IUserDialogs dialog = UserDialogs.Instance; dialog.ShowLoading("Purchasing Ride Credits..."); try { bool result = int.TryParse(amount.Text, out int rideCredit); if (!result) { throw new InvalidNumberException("Invalid"); } try { if (rideCredit <= 0) { throw new InvalidNumberException(""); } else { Details = db.GetUserDetails(); rhodeITServices.UpdateCreditRequestAsync(Details.Ethereum_Address, rideCredit).ConfigureAwait(false); Details.RideCredits += rideCredit; RhodesDataBase.ChargeUserRideCreditBalanceToAccount(Details).ConfigureAwait(false); db.UpdateLoginDetails(Details); dialog.HideLoading(); dialog.Alert(string.Format("Succesfully recharged ride credits with {0}", rideCredit), "Success", "OK"); } } catch (Exception e) { dialog.HideLoading(); PopupLayout.Dismiss(); Console.WriteLine("Error whilst purcasing credits: " + e.Message); dialog.Alert("Something went wrong whilst purchasing credit", "Insufficient Funds", "OK"); } } catch (InvalidNumberException e) { dialog.HideLoading(); PopupLayout.Dismiss(); Console.WriteLine("Error whilst purcasing credits: " + e.Message); dialog.Alert("Please ensure you entered a valid number e.g. 12", "Invalid Number", "OK"); } }
public DictationViewModel(ISpeechRecognizer speech, IUserDialogs dialogs) { IDisposable token = null; speech .WhenListeningStatusChanged() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => this.ListenText = x ? "Stop Listening" : "Start Dictation" ); this.ToggleListen = ReactiveCommand.Create(() => { if (token == null) { if (this.UseContinuous) { token = speech .ContinuousDictation() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe( x => this.Text += " " + x, ex => dialogs.Alert(ex.ToString()) ); } else { token = speech .ListenUntilPause() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe( x => this.Text = x, ex => dialogs.Alert(ex.ToString()) ); } } else { token.Dispose(); token = null; } }); }
public static async Task <bool> AlertAccess(this IUserDialogs dialogs, AccessState access) { switch (access) { case AccessState.Available: return(true); case AccessState.Restricted: await dialogs.Alert("WARNING: Access is restricted"); return(true); default: await dialogs.Alert("Invalid Access State: " + access); return(false); } }
private bool ValidateData() { if (string.IsNullOrEmpty(UserName) || string.IsNullOrWhiteSpace(UserName)) { _userDialogs.Alert("¡Ingrese el nombre de usuario!", "Error", "Aceptar"); return(false); } return(true); }
public void Show(AlertConfig config) { _userDialogsInstance.Alert(new Acr.UserDialogs.AlertConfig { Message = config.Message, OkText = config.OkText, OnAction = config.OnAction, Title = config.Title }); }
public static IDisposable Alert(this IUserDialogs instance, Exception ex) { var aEx = ex as AggregateException; if (aEx != null) { return(instance.Alert(ex.InnerException)); } else if (ex.InnerException == null) { return(instance.Alert(GetMessage(ex.Message))); } else { return(instance.Alert(ex.InnerException)); } string GetMessage(string text) => $"エラーが発生しました\nMessage: {text}"; }
private void EditUser() { if (user.UserType == "A") { ShowViewModel <UserListViewModel>(); } else { _dialogs.Alert("You are not logged as an Admin!"); } }
public void ShowAlert(string message, int?timeout = default(int?)) { var config = new AlertConfig { Message = string.Empty, OkText = "OK", Title = message }; Device.BeginInvokeOnMainThread(() => _userDialogs.Alert(config)); }
public ToastsViewModel(IUserDialogs dialogs) : base(dialogs) { this.SecondsDuration = 3; this.ActionText = "Ok"; this.ActionTextColor = Color.White.ToString(); this.Message = "This is a test of the emergency toast system"; this.MessageTextColor = Color.White.ToString (); this.Open = new Command(() => dialogs .Toast(new ToastConfig(this.Message) //.SetMessageTextColor(System.Drawing.Color.FromHex(this.MessageTextColor)) .SetDuration(TimeSpan.FromSeconds(this.SecondsDuration)) .SetAction(x => x .SetText(this.ActionText) //.SetTextColor(new System.Drawing.Color.FromHex(this.ActionTextColor)) .SetAction(() => dialogs.Alert("You clicked the primary button")) ) ) ); }