/// <summary> /// Stop recording and save the voice recording file /// </summary> /// <returns>file path to save audio file</returns> public string Save() { if ((_recorder.State == RecorderState.Idle) || (_recorder.State == RecorderState.Ready)) { Console.WriteLine("AudioRecordService.Save : No need to cancel in State (" + _recorder.State + ") "); return(null); } try { // Stop recording and save the result in file _recorder.Commit(); if (_recorder.State != RecorderState.Ready) { Console.WriteLine(" AudioRecordService.Save state error"); // TODO : Handle error case Toast.DisplayText("Fail to save audio file because of recording fw issue."); } string name = filepath.Substring(filepath.IndexOf(' ')); string final = name.Substring(0, name.IndexOf("_T_")); //string final = name.Substring(name.IndexOf("_T_"), name.Length - name.IndexOf("_T_")); numbering = Convert.ToInt32(final); Console.WriteLine(" ###### Voice File name - " + name + " --> final : " + final + " , numbering : " + numbering); } catch (Exception e) { HandleError("Commit", e); } return(filepath); }
/// <summary> /// Get all trackers by token in secureStorage /// </summary> public static async Task GetTrackersAsync(Action <List <TrackerModel> > action) { HttpClient httpClient = InitHttpClient(); // Get token auth from secure storage var token = await SecureStorage.GetAsync("token"); Log.Debug(Constants.logTag, "Token : " + token); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); HttpResponseMessage response = await httpClient.GetAsync(Constants.baseUrlApiGeoride + Constants.trackersEndpointApiGeoride); if (response.StatusCode == HttpStatusCode.OK) { try { var trackers = JsonConvert.DeserializeObject <List <TrackerModel> >(await response.Content.ReadAsStringAsync()); action(trackers); } catch (JsonSerializationException ex) { Toast.DisplayText(ex.Message, 5000); Log.Error(Constants.logTag, ex.Message); action(new List <TrackerModel>()); } } else { action(new List <TrackerModel>()); } }
async private void Button_OnClicked2(object sender, EventArgs e) { // save this record to DB AlarmRecordViewModelEnum result = ((AlarmRecordViewModel)BindingContext).SaveToDb(); if (result == AlarmRecordViewModelEnum.FailureNew) { Toast.DisplayText("Failed to add a new alarm (existing)."); } else if (result == AlarmRecordViewModelEnum.SuccessCancelAndUpdateExisting) { originalAlarmListViewModel.Items.Remove(originalAlarmViewModel); Toast.DisplayText("The time is already existing so delete existing one"); } else if (result == AlarmRecordViewModelEnum.SuccessUpdateExceptTime) { Toast.DisplayText("Success. In this row, change except time"); originalAlarmViewModel.DeepCopy(newAlarmViewModel); } else if (result == AlarmRecordViewModelEnum.SuccessUpdateNonexisting) { Toast.DisplayText("Success. In this row, change time"); originalAlarmViewModel.DeepCopy(newAlarmViewModel); } else if (result == AlarmRecordViewModelEnum.SuccessNew) { originalAlarmListViewModel.Items.Add((AlarmRecordViewModel)BindingContext); Toast.DisplayText("Added a new alarm successfully"); } await Navigation.PopAsync(false); }
/// <summary> /// Event when "Sign out" button is clicked. /// </summary> /// <param name="sender"> Parameter about which object is invoked the current event. </param> /// <param name="args"> Event arguments. </param> public async void SignOutClicked(object sender, EventArgs args) { accountAPIs.AccountSignOut(account); Toast.DisplayText($"{account.UserName} signed out"); await Navigation.PopAsync(); }
public static bool ValidateForm(string email, string password) { if (string.IsNullOrEmpty(email)) { Toast.DisplayText(Constants.emailEmpty, 3000); return(false); } else { try { MailAddress mailCheck = new MailAddress(email); } catch (FormatException) { Toast.DisplayText(Constants.emailInvalid, 3000); return(false); } } if (string.IsNullOrEmpty(password)) { Toast.DisplayText(Constants.passwordEmpty, 3000); return(false); } else { return(true); } }
private async Task reportToApiServer( string message = default(string), string path = default(string), Task postTransferTask = null) { if (message != default(string)) { HttpResponseMessage result = await Tools.post(Tools.API_NOTIFY, new Dictionary <string, string> { { "username", Tizen.Applications.Preference.Get <string>("username") }, { "password", Tizen.Applications.Preference.Get <string>("password") }, { "message", message } }); if (result.IsSuccessStatusCode) { JsonValue resJson = JsonValue.Parse(await result.Content.ReadAsStringAsync()); log($"RESULT: {resJson["result"]}"); Debug.WriteLine(Tools.TAG, $"Message has been submitted to the Server. length={message.Length}"); } else { Toast.DisplayText("Failed to submit a notification to server!"); } } else if (path != null) { HttpResponseMessage result = await Tools.post( Tools.API_SUBMIT_DATA, new Dictionary <string, string> { { "username", Tizen.Applications.Preference.Get <string>("username") }, { "password", Tizen.Applications.Preference.Get <string>("password") } }, File.ReadAllBytes(path) ); if (result == null) { Toast.DisplayText("Please check your WiFi connection first!"); return; } if (result.IsSuccessStatusCode) { JsonValue resJson = JsonValue.Parse(await result.Content.ReadAsStringAsync()); ServerResult resCode = (ServerResult)int.Parse(resJson["result"].ToString()); if (resCode == ServerResult.OK) { postTransferTask?.Start(); } else { log($"Failed to upload {path.Substring(path.LastIndexOf(Path.PathSeparator) + 1)}"); } } else { log($"Failed to upload {path.Substring(path.LastIndexOf(Path.PathSeparator) + 1)}"); } } }
/// <summary> /// Creates a StackLayout with DeviceListView and ScanLabel /// on a ContentPage. Then creates a new NavigationPage using /// the ContentPage, because NaviagtionPage manages navigation /// and user-experience of a stack of other pages.And then /// it pushes this NaviagationPage on top of MainPage. /// After pushing, LE scan is initiated. Once it is /// completed it creates a new page in which all the /// discoverd devices are populated in list view. /// </summary> public async void RenderDevicePage() { if (DeviceListView == null) { CreateDeviceListView(); } ScanLabel.Text = "Scanning"; ScanLabel.FontAttributes = FontAttributes.Bold; ScanLabel.FontSize = 24; ContentPage content = new ContentPage { Title = "Device List", Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { ScanLabel, DeviceListView, } }, }; DevicePage = new NavigationPage(content); await MainPage.Navigation.PushAsync(DevicePage); await LeScanSetup(); ScanLabel.Text = "Scan completed"; DeviceListView.ItemsSource = null; DeviceListView.ItemsSource = DeviceList; Toast.DisplayText("Tap device address to initate GATT connect."); }
/// <summary> /// Scans for APs and sets NetworkList with scan result. /// </summary> private async void SetNetworkListAsync() { try { WiFiApiManager wifi = new WiFiApiManager(); await wifi.Scan(); var net = wifi.ScanResult(); NetworkList.Clear(); if (net != null) { foreach (var n in net) { NetworkList.Add(n.Name); } } } catch (NotSupportedException e) { Toast.DisplayText("Not supported"); Logger.Log(e.Message); } catch (Exception e) { Toast.DisplayText("Retrieving list failed!"); Logger.Log(e.Message); } }
/// <summary> /// Scans for APs and sets NetworkList with scan result. /// </summary> private void SetNetworkListAsync() { try { ConnectionProfileInfo info = new ConnectionProfileInfo(); var profileList = info.GetProfileList(); ProfileList.Clear(); foreach (var n in profileList) { ProfileList.Add(n.Name); } } catch (NotSupportedException e) { Toast.DisplayText("Not supported"); Logger.Log(e.Message); } catch (Exception e) { Toast.DisplayText("Retrieving list failed!"); Logger.Log(e.Message); } }
private async void OnButtonClicked(object sender, EventArgs e) { var action = string.Empty; var newState = DoorState.opening; if (doorState == DoorState.open) { action = Constants.ActionClose; newState = DoorState.closing; } else if (doorState == DoorState.closed) { action = Constants.ActionOpen; newState = DoorState.opening; } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { Toast.DisplayText("Couldn't set"); }); return; } var set = await api.SetDoorState(garageDoor.SerialNumber, action); if (set) { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { UpdateUi(newState); }); } }
public App() { try { MessagePort messagePort = null; messagePort = new MessagePort(uiAppPortName, true); // You need to first call Listen even you need to send a message. messagePort.Listen(); // Register MessageReceived event callback messagePort.MessageReceived += (s, e) => { Console.WriteLine("UI application received a message"); if (e.Message.Contains("greetingReturn")) { Toast.DisplayText("Received:" + e.Message.GetItem("greetingReturn") + ", Array: " + BitConverter.ToInt32((byte[])e.Message.GetItem("intByteArray"), 0)); } }; // The root page of your application MainPage = new CirclePage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { HorizontalTextAlignment = TextAlignment.Center, Text = "Talk over message port APIs" }, new Button { Text = "Send a message", Command = new Command(() => { Bundle bundleToSend = new Bundle(); bundleToSend.AddItem("greeting", "hello"); bundleToSend.AddItem("intByteArray", BitConverter.GetBytes(1024 * 1024)); try { // Need to call Listen() before calling Send messagePort.Send(bundleToSend, "org.tizen.example.ServiceApp", serviceAppPortName, false); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message + ", " + e); Toast.DisplayText("An exception occurs!! " + e.Message + ", " + e, 10000); } }) } } } }; } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } }
private void OnRecordingLimitReached(object sender, RecordingLimitReachedEventArgs e) { Toast.DisplayText(LocalizedStrings.VoiceMessageLimit); recordButton.ImageSource = ImageResources.RecordSymbol; isRecording = false; sendButton.IsEnabled = true; Logger.Error("Audio message time limit reached"); }
/// <summary> /// Invoked when "Reorder" more menu is choosed /// </summary> /// <param name="menu">string</param> private void ShowReorderPage(string menu) { // Make MoreMenuDialog invisible dialog.Hide(); Toast.DisplayText("[TODO] need to make WorldclockReorderPage visible."); // Temporarily added. Need to be delete when WorldclockReorderPage is created and shown. MenuKeyListener.Start(this, MenuKeyPressed); }
async private void ListItemTapped(object sender, ItemTappedEventArgs e) { var result = await WolProvider.WakeUp(((LanPc)e.Item).MacAddress); Toast.DisplayText(result ? Resx.AppResources.SendSuccess : Resx.AppResources.SendError); }
private void ShowMessage(string message, string debugLog = null) { Toast.DisplayText(message, 1000); if (debugLog != null) { debugLog = message; } Console.WriteLine("[DEBUG] " + message); }
private void ShowMessage(string message, string debugLog = null) { Toast.DisplayText(message, 3000); if (debugLog != null) { Console.WriteLine(TAG + debugLog); } Console.WriteLine(TAG + message); }
/// <summary> /// Called when the floating button has been clicked /// Launchs org.tizen.worldclock-efl application when a floating button is pressed /// Adds city /// </summary> /// <param name="sender">floating button object</param> /// <seealso cref="System.object"> /// <param name="e">Event argument for event of floating button.</param> /// <seealso cref="System.EventArgs"> public void OnFloatingButtonClicked(object sender, EventArgs e) { if (App.ClockInfo.CityRecordList.Count >= WorldclockCityList.MAX_ITEMS_LIMIT) { Toast.DisplayText("Maximum number of cities " + WorldclockCityList.MAX_ITEMS_LIMIT + " reached."); return; } DependencyService.Get <IAppControl>().ApplicationLaunchRequest("org.tizen.worldclock-efl", AppControlOperation.PICK, AppControlLaunchType.GROUP); }
protected virtual void ShowToast(string text, FileImageSource iconMediaSource = null, int duration = 3) { if (iconMediaSource == null) { Toast.DisplayText(text, duration); } else { Toast.DisplayIconText(text, iconMediaSource, duration); } }
private bool CheckDevice() { if (!AudioManager.GetConnectedDevices().Any(e => e.Type == AudioDeviceType.BuiltinSpeaker || e.Type == AudioDeviceType.BluetoothMedia)) { Toast.DisplayText(LocalizedStrings.CantPlayAudioMessageNoHeadphones); return(false); } return(true); }
/// <summary> /// This function is called when "BLE Scan" button is clicked. /// It checks for BT status and notify the user /// "Please turn on Bluetooth" incase the BT state is OFF. /// If BT state is ON, it proceeds to scan LE devices and /// start rendering the device page. /// </summary> /// <param name="s">object</param> /// <param name="e">EventArgs</param> void OnScanButtonClicked(object s, EventArgs e) { if (!BluetoothAdapter.IsBluetoothEnabled) { Toast.DisplayText("Please turn on Bluetooth."); } else { RenderDevicePage(); } }
private void deleteDB() { string dataPath = global::Tizen.Applications.Application.Current.DirectoryInfo.Data; string DBFileName = "SQLite3.db3"; string databasePath = Path.Combine(dataPath, DBFileName); if (File.Exists(databasePath)) { try { File.Delete(databasePath); } catch { Toast.DisplayText("DB_DELETE_ERR"); } } }
public MessagePage(Message message) { NavigationPage.SetHasNavigationBar(this, false); wrapperLayout.Children.Add(CreateLabel(message.FullText, true)); foreach (var item in message.AttachmentMessages) { var text = LocalizedStrings.ForwardedMessage + (item.Profile?.Name != null ? $" {LocalizedStrings.From} " + item.Profile.Name : string.Empty) + $":\n\"{item.Text}\""; wrapperLayout.Children.Add(CreateLabel(text)); } foreach (var item in message.AttachmentUris) { var uri = CreateUri(item.ToString()); wrapperLayout.Children.Add(uri); var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (s, e) => { AppControl.SendLaunchRequest(new AppControl { Operation = AppControlOperations.View, Uri = item.ToString() }); Toast.DisplayText(LocalizedStrings.OpeningBrowser); }; uri.GestureRecognizers.Add(tapGestureRecognizer); } foreach (var item in message.AttachmentImages) { var image = CreateImage(item.Url); wrapperLayout.Children.Add(image); } var emptyLabel = new Label { Margin = new Thickness(0, 0, 0, 70) }; wrapperLayout.Children.Add(emptyLabel); scrollView.Content = wrapperLayout; Content = scrollView; SetBinding(RotaryFocusObjectProperty, new Binding { Source = scrollView }); }
/// <summary> /// Overrides method handling hardware "back" button press. /// Depending on GPS location state, navigates to workout main page or displays toast popup. /// </summary> protected override bool OnBackButtonPressed() { if (LocationService.Instance.IsGPSLocationEnabled()) { PageNavigationService.Instance.GoToWorkoutMainPage(); } else { Toast.DisplayText(_toastMessage, _toastDuration); } return(true); }
private static void Connection_StatusChanged(object sender, ConnectionStatusEventArgs e) { Toast.DisplayText(e.Reason.ToString()); if (e.Reason == ConnectionStatus.ConnectionClosed || e.Reason == ConnectionStatus.ConnectionLost) { connection.DataReceived -= Connection_DataReceived; connection.StatusChanged -= Connection_StatusChanged; connection.Close(); connection = null; peer = null; } }
/// <summary> /// Forgets current Access Point /// </summary> private void ForgetClicked() { try { _wifi.Forget(APName); RefreshBindings(); Toast.DisplayText("Forgotten!"); } catch (Exception ex) { Toast.DisplayText("Forget failed!"); Logger.Log(ex.Message); } }
protected override void OnAppearing() { terminateFilesCounterThread(); try { startFilesCounterThread(); } catch (Exception e) { Toast.DisplayText(e.Message); } base.OnAppearing(); }
public static async Task SecureSaveValue(string value, string valueName) { try { // Remove begin because method SetAsync not overwriting value SecureStorage.Remove(valueName); await SecureStorage.SetAsync(valueName, value); } catch (Exception ex) { Toast.DisplayText(ex.Message, 3000); Log.Error(Constants.logTag, ex.Message); } }
/// <summary> /// Regenerate token /// </summary> public static async Task <bool> RegenerateTokenAsync() { var url = Constants.baseUrlApiGeoride + Constants.regenerateTokenEndpointApiGeoride; Log.Debug(Constants.logTag, "Url : " + url); try { HttpClient httpClient = InitHttpClient(); // Get token auth from secure storage var token = await SecureStorage.GetAsync("token"); Log.Debug(Constants.logTag, "Token : " + token); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await httpClient.GetAsync(url); var json = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK) { var tokenResult = JObject.Parse(json)["authToken"]; Log.Debug(Constants.logTag, "Token result : " + token); // Update token in secure storage await UtilsHelper.SecureSaveValue(tokenResult.ToString(), "token"); // Save timestamp for expiration date of token var timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(); await UtilsHelper.SecureSaveValue(timestamp, "timestamp"); return(true); } else { Toast.DisplayText(Constants.errorRegenerateToken, 5000); return(false); } } catch (HttpRequestException ex) { Toast.DisplayText(ex.Message, 5000); Log.Error(Constants.logTag, ex.Message); return(false); } }
private void ExitApp() { Toast.DisplayText("Permission is required for the app to work. Please change this on device settings.\n" + "You can also uninstall & reinstall and you'll be asked again."); var timer = new Timer(5000) { AutoReset = false, Enabled = true }; timer.Elapsed += (s, e) => { _log.Fatal("App closed due insufficient permissions"); Quit(); }; }
/// <summary> /// Called when the floating button has been clicked /// Show a page for editing an alarm /// When the floating button is clicked (new alarm request), new alarm will be created and call /// Alarm Edit Page with the created alarm record /// </summary> /// <param name="sender">floating button object</param> /// <seealso cref="System.object"> /// <param name="e">Event argument for event of floating button.</param> /// <seealso cref="System.EventArgs"> public void OnFloatingButtonClicked(object sender, EventArgs e) { if (AlarmModel.ObservableAlarmList.Count >= MAX_ITEMS_LIMIT) { Toast.DisplayText("Maximum number of alarms(" + MAX_ITEMS_LIMIT + ") reached."); return; } /// Creates default alarm record AlarmRecord defaultAlarmRecord = new AlarmRecord(); defaultAlarmRecord.SetDefault(); /// Call via alarm page controller which instantiates page once Navigation.PushAsync(AlarmPageController.GetInstance(AlarmPages.EditPage, defaultAlarmRecord), false); }