private void UndoButton_Clicked(object sender, EventArgs e) { Snackbar snackbar = Snackbar.Make(statInputSwitcher, myViewModel.Undo(), Snackbar.LengthLong); snackbar.SetAction("Dismis", v => snackbar.Dismiss()); snackbar.Show(); }
public MessageBarCreator(View rootView, string message, string buttonName, Action method) : this(rootView, message) { this.buttonName = buttonName; snackbar.SetAction(buttonName, delegate { method(); }); }
public void OnWeatherError(WeatherException wEx) { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { Snackbar snackBar = Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long); snackBar.SetAction(App.ResLoader.GetString("Action_Retry"), async() => { await RefreshLocations(); }); snackBar.Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; default: // Show error message // Only warn once if (!ErrorCounter[(int)wEx.ErrorStatus]) { Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long).Show(); ErrorCounter[(int)wEx.ErrorStatus] = true; } break; } }
private static void AddDefaultButtonsToSnackbar(TaskCompletionSource <int> tcs, Snackbar snackbar, IList <string> defaultButtonTexts) { for (var i = 0; i < defaultButtonTexts.Count; i++) { snackbar.SetAction(defaultButtonTexts[i], CreateSnackbarAction(tcs, i)); } }
private async void bntRecoverClick(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(email.Text) || string.IsNullOrEmpty(email.Text)) { Snackbar bar = Snackbar.Make(parentForgot, Html.FromHtml("<font color=\"#000000\">Fill email</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); } else { string txtEmailForgot = email.Text; var httpClient = new HttpClient(); var content = new StringContent(JsonConvert.SerializeObject(new { Email = txtEmailForgot }), Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync("UrlApi" + "api/account/forgotpassword", content); var response = await result.Content.ReadAsStringAsync(); Toast.MakeText(this, "Check your email please.", ToastLength.Long).Show(); StartActivity(typeof(LogIn)); } } catch (HttpRequestException httpEx) { Snackbar bar = Snackbar.Make(parentForgot, Html.FromHtml("<font color=\"#000000\">Check your internet connection</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); } catch (Exception ex) { Snackbar bar = Snackbar.Make(parentForgot, Html.FromHtml("<font color=\"#000000\">Error: " + ex + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); } }
public void showUndoSnackBar() { View vista = ((MainActivity)mContexto).Window.DecorView.FindViewById(Resource.Id.container); Snackbar sbMessage = Snackbar.Make(vista, "Eliminado", Snackbar.LengthLong); sbMessage.SetAction("Deshacer", (View view) => { lstData.Insert(mRecentlyDeletedItemPosition, mRecentlyDeletedItem); NotifyItemInserted(mRecentlyDeletedItemPosition); }); sbMessage.Show(); }
protected virtual IDisposable ToastAppCompat(AppCompatActivity activity, ToastConfig cfg) { Snackbar snackBar = null; activity.SafeRunOnUi(() => { var view = activity.Window.DecorView.RootView.FindViewById(Android.Resource.Id.Content); var msg = this.GetSnackbarText(cfg); snackBar = Snackbar.Make( view, msg, (int)cfg.Duration.TotalMilliseconds ); if (cfg.BackgroundColor != null) { snackBar.View.SetBackgroundColor(cfg.BackgroundColor.Value.ToNative()); } if (cfg.Position == ToastPosition.Top) { // watch for this to change in future support lib versions var layoutParams = snackBar.View.LayoutParameters as FrameLayout.LayoutParams; if (layoutParams != null) { layoutParams.Gravity = GravityFlags.Top; layoutParams.SetMargins(0, 80, 0, 0); snackBar.View.LayoutParameters = layoutParams; } } if (cfg.Action != null) { snackBar.SetAction(cfg.Action.Text, x => { cfg.Action?.Action?.Invoke(); snackBar.Dismiss(); }); var color = cfg.Action.TextColor; if (color != null) { snackBar.SetActionTextColor(color.Value.ToNative()); } } snackBar.Show(); }); return(new DisposableAction(() => { if (snackBar.IsShown) { activity.SafeRunOnUi(snackBar.Dismiss); } })); }
internal static void ShowSnackBar_WithOKButtonToClose(Context context, View view, int iResourceStringID) { Snackbar bar = Snackbar.Make(view, iResourceStringID, Snackbar.LengthIndefinite); bar.View.SetBackgroundColor(new Android.Graphics.Color(ContextCompat.GetColor(context, Resource.Color.primary_dark))); bar.SetAction(Resource.String.snackbar_OK, (v) => { }); bar.SetActionTextColor(new Android.Graphics.Color(ContextCompat.GetColor(context, Resource.Color.primary_light))); bar.Show(); }
protected virtual IDisposable ToastAppCompat(AppCompatActivity activity, ToastConfig cfg) { Snackbar snackBar = null; activity.RunOnUiThread(() => { var view = activity.Window.DecorView.RootView.FindViewById(Android.Resource.Id.Content); var msg = this.GetSnackbarText(cfg); snackBar = Snackbar.Make( view, msg, (int)cfg.Duration.TotalMilliseconds ); if (cfg.BackgroundColor != null) { snackBar.View.SetBackgroundColor(cfg.BackgroundColor.Value.ToNative()); } if (cfg.Action != null) { snackBar.SetAction(cfg.Action.Text, x => { cfg.Action?.Action?.Invoke(); snackBar.Dismiss(); }); var color = cfg.Action.TextColor; if (color != null) { snackBar.SetActionTextColor(color.Value.ToNative()); } } snackBar.Show(); }); return(new DisposableAction(() => { if (snackBar.IsShown) { activity.RunOnUiThread(() => { try { snackBar.Dismiss(); } catch { // catch and swallow } }); } })); }
private void displaySnackBar(string text) { Snackbar bar = Snackbar.Make(view, Html.FromHtml("<font color=\"#000000\">" + text + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 20; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); }
private void ShowSnackbar(String message, Int32 actionId = 0, Action callback = null) { Snackbar snackbar = Snackbar.Make(_contentLayout, message, Snackbar.LengthLong); if (actionId != 0) { snackbar.SetAction(actionId, (v) => callback()); } TextView text = snackbar.View.FindViewById <TextView>(Resource.Id.snackbar_text); text.SetTextSize(ComplexUnitType.Px, Resources.GetDimension(Resource.Dimension.normalTextSize)); text.SetMaxLines(3); snackbar.Show(); }
private void ShowSnackbar(Int32 messageId, Int32 actionId = 0, Action callback = null) { Snackbar snackbar = Snackbar.Make(_content, messageId, Snackbar.LengthLong); if (actionId != 0) { snackbar.SetAction(actionId, (v) => callback()); } TextView message = snackbar.View.FindViewById <TextView>(Resource.Id.snackbar_text); message.TextSize = 16; message.SetMaxLines(3); snackbar.Show(); // RunOnUiThread(snackbar.Show); }
private void SetStatisticLayout() { switch (myCurrentStatToGet) { case EStatisticType.DefensiveRebound: statInputSwitcher.DisplayedChild = statInputSwitcher.IndexOfChild(statInputSwitcher.FindViewById <LinearLayout>(Resource.Id.twoChoice)); actionButtonLayout.Visibility = ViewStates.Visible; statInputSwitcher.CurrentView.FindViewById <MultiLineRadioGroup>(Resource.Id.radioGroup1).SetToDefault(); break; case EStatisticType.Goal: case EStatisticType.ConcededGoal: case EStatisticType.ConcededShot: case EStatisticType.Interception: case EStatisticType.Turnover: case EStatisticType.Shot: case EStatisticType.Assist: case EStatisticType.Rebound: statInputSwitcher.DisplayedChild = statInputSwitcher.IndexOfChild(statInputSwitcher.FindViewById <LinearLayout>(Resource.Id.four4Choice)); SetPlayers(); break; case EStatisticType.GoalType: statInputSwitcher.DisplayedChild = statInputSwitcher.IndexOfChild(statInputSwitcher.FindViewById <LinearLayout>(Resource.Id.goaltype)); statInputSwitcher.CurrentView.FindViewById <MultiLineRadioGroup>(Resource.Id.radioGroup1).SetToDefault(); break; default: statInputSwitcher.DisplayedChild = statInputSwitcher.IndexOfChild(statInputSwitcher.FindViewById <LinearLayout>(Resource.Id.buttonLayout)); actionButtonLayout.Visibility = ViewStates.Gone; Snackbar snackbar = Snackbar.Make(statInputSwitcher, myViewModel.ExecuteCommand(), Snackbar.LengthLong); snackbar.SetAction("Dismis", v => snackbar.Dismiss()); snackbar.Show(); break; } TextView header = statInputSwitcher.CurrentView.FindViewById <TextView>(Resource.Id.headerText); if (header != null) { header.Text = myCurrentStatToGet.GetDescription(); } }
private void GetStoragePermission() { const string permission = Android.Manifest.Permission.WriteExternalStorage; if (CheckSelfPermission(permission) == (int)Permission.Granted) { return; } if (ShouldShowRequestPermissionRationale(permission)) { Snackbar snackbar = Snackbar.Make(transferLayout, Resources.GetString(Resource.String.storage_perm), Snackbar.LengthIndefinite); snackbar.SetAction("OK", v => RequestPermissions(PermissionsStorage, RequestStorageId)); snackbar.Show(); return; } RequestPermissions(PermissionsStorage, RequestStorageId); }
public override void OnBackPressed() { if (unsavedChanges && lastSnackbar?.IsShown != true) { try { TryDecode(out _); } catch (Exception e) { Logging.exception(e, Logging.Level.Error, "OnBackPressed() decoding"); MakeSnackbar(Resources.GetString(R.String.saving_error) + e.Message, Snackbar.LengthShort).Show(); } lastSnackbar = MakeSnackbar(R.String.press_again_to_quit, Snackbar.LengthShort); lastSnackbar.SetAction(R.String.save_and_quit, (x) => { if (Save()) { Finish(); } }) .Show(); return; } base.OnBackPressed(); }
public Snackbar ShowSnackbar(View attachToView, string message, Action <View> action = null, int actionTextId = 0) { // don't show the message if there already if (_snackbar != null) { return(_snackbar); } _snackbar = Snackbar.Make( attachToView, message, Snackbar.LengthIndefinite); if (action != null && actionTextId != 0) { _snackbar.SetAction(actionTextId, action); } _snackbar.Show(); return(this._snackbar); }
public void OnWeatherError(WeatherException wEx) { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh Snackbar snackBar = Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long); snackBar.SetAction(App.ResLoader.GetString("Action_Retry"), () => { Task.Run(async() => await RefreshWeather(false)); }); snackBar.Show(); break; default: // Show error message Snackbar.Make(Content as Grid, wEx.Message, SnackbarDuration.Long).Show(); break; } }
public void OnWeatherError(WeatherException wEx) { AppCompatActivity?.RunOnUiThread(() => { switch (wEx.ErrorStatus) { case WeatherUtils.ErrorStatus.NetworkError: case WeatherUtils.ErrorStatus.NoWeather: // Show error message and prompt to refresh Snackbar snackBar = Snackbar.Make(mainView, wEx.Message, Snackbar.LengthLong); snackBar.SetAction(Resource.String.action_retry, async(View v) => { await RefreshWeather(false); }); snackBar.Show(); break; default: // Show error message Snackbar.Make(mainView, wEx.Message, Snackbar.LengthLong).Show(); break; } }); }
public async void Refresh() { await Task.Run(() => { TimeStep[] timeSteps; DateTime now = DateTime.Now; RunOnUiThread(OnRefreshing); // Online time steps try { if (TramUrWayApplication.Config.OfflineMode) { throw new Exception(); } /*timeSteps = App.Service.GetLiveTimeSteps() * .Where(t => t.Step.Route.Line == line) * .OrderBy(t => t.Date) * .ToArray();*/ timeSteps = TramUrWayApplication.Service.GetLiveTimeSteps(line) .OrderBy(t => t.Date) .ToArray(); snackbar?.Dismiss(); } catch (Exception e) { timeSteps = line.Routes.SelectMany(r => { TimeTable timeTable = r.TimeTable; // Offline data if (timeTable != null) { TimeStep[] routeSteps = r.Steps.SelectMany(s => timeTable.GetStepsFromStep(s, now).Take(3)).ToArray(); if (snackbar == null) { snackbar = Snackbar.Make(viewPager, "Données hors-ligne", Snackbar.LengthIndefinite); if (TramUrWayApplication.Config.OfflineMode) { snackbar = snackbar.SetAction("Activer", Snackbar_Activate); } else { snackbar = snackbar.SetAction("Réessayer", Snackbar_Retry); } snackbar.Show(); } return(routeSteps); } // No data else { if (snackbar == null) { snackbar = Snackbar.Make(viewPager, "Aucune donnée disponible", Snackbar.LengthIndefinite); if (TramUrWayApplication.Config.OfflineMode) { snackbar = snackbar.SetAction("Activer", Snackbar_Activate); } else { snackbar = snackbar.SetAction("Réessayer", Snackbar_Retry); } snackbar.Show(); } return(Enumerable.Empty <TimeStep>()); } }).ToArray(); } // Update transports with new data transports.Update(timeSteps, now); RunOnUiThread(() => OnRefreshed(timeSteps, transports)); }); }
public static void ShowSnackbar(Activity activity, SnackbarConfig config) { var view = activity.Window.DecorView.RootView.FindViewById(global::Android.Resource.Id.Content); if (_snackbar == null) { _snackbar = Snackbar.Make(view, config.Message, (int)config.Duration.TotalMilliseconds); } if (_snackbar.IsShownOrQueued) { _snackbar = Snackbar.Make(view, config.Message, (int)config.Duration.TotalMilliseconds); } _snackbar.SetDuration((int)config.Duration.TotalMilliseconds); _snackbar.SetText(config.Message); if (!string.IsNullOrWhiteSpace(config.ActionText)) { _snackbar.SetAction(config.ActionText, (v) => { config.Action?.Invoke(); _snackbar.Dismiss(); }); if (config.ActionTextColor.HasValue) { _snackbar.SetActionTextColor(config.ActionTextColor.Value.ToNativeColor()); } } if (config.TextColor.HasValue) { //TextView textView = _snackbar.View.FindViewById<TextView>(Resource.Id.snackbar_text); //textView.SetTextColor(config.TextColor.Value.ToNativeColor()); // TODO } if (config.BackgroundColor.HasValue) { //TextView textView = _snackbar.View.FindViewById<TextView>(Resource.Id.snackbar_text); //textView.SetBackgroundColor(config.BackgroundColor.Value.ToNativeColor()); // TODO } //if (config.Position != ToastPosition.Default) //{ // // watch for this to change in future support lib versions // var layoutParams = _snackbar.View.LayoutParameters as FrameLayout.LayoutParams; // if (layoutParams != null) // { // if (config.Position == ToastPosition.Top) // { // layoutParams.Gravity = GravityFlags.Top; // layoutParams.SetMargins(0, 80, 0, 0); // } // else if (config.Position == ToastPosition.Center) // { // layoutParams.Gravity = GravityFlags.Center; // } // else if (config.Position == ToastPosition.Bottom) // { // layoutParams.Gravity = GravityFlags.Bottom; // layoutParams.SetMargins(0, 0, 0, 30); // } // _snackbar.View.LayoutParameters = layoutParams; // } //} _snackbar.Show(); }
async Task <bool> ValidateChanges(bool displayActionIfMountFail = false) { System.Console.WriteLine("&Validaing changes"); if (song.Title == title.Text && song.Artist == artist.Text && song.YoutubeID == youtubeID.Text && song.Album == album.Text && artURI == null) { return(true); } System.Console.WriteLine("&Requesting permission"); const string permission = Manifest.Permission.WriteExternalStorage; hasPermission = Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, permission) == (int)Permission.Granted; if (!hasPermission) { string[] permissions = new string[] { permission }; RequestPermissions(permissions, RequestCode); while (!hasPermission) { await Task.Delay(1000); } } if (!Environment.MediaMounted.Equals(Environment.GetExternalStorageState(new Java.IO.File(song.Path)))) { Snackbar snackBar = Snackbar.Make(FindViewById <CoordinatorLayout>(Resource.Id.snackBar), Resource.String.mount_error, Snackbar.LengthLong); snackBar.View.FindViewById <TextView>(Resource.Id.snackbar_text).SetTextColor(Color.White); if (displayActionIfMountFail) { snackBar.SetAction(Resource.String.mount_error_action, (v) => { Finish(); }); } snackBar.Show(); return(false); } try { System.Console.WriteLine("&Creating write stream"); Stream stream = new FileStream(song.Path, FileMode.Open, FileAccess.ReadWrite); var meta = TagLib.File.Create(new StreamFileAbstraction(song.Path, stream, stream)); System.Console.WriteLine("&Writing tags"); meta.Tag.Title = title.Text; song.Title = title.Text; meta.Tag.Performers = new string[] { artist.Text }; song.Artist = artist.Text; meta.Tag.Album = album.Text; song.Album = album.Text; meta.Tag.Comment = youtubeID.Text; if (queuePosition != -1 && MusicPlayer.queue.Count > queuePosition) { MusicPlayer.queue[queuePosition] = song; Player.instance?.RefreshPlayer(); Queue.instance.NotifyItemChanged(queuePosition); } if (ytThumbUri != null) { System.Console.WriteLine("&Writing YT Thumb"); await Task.Run(() => { IPicture[] pictures = new IPicture[1]; Bitmap bitmap = Picasso.With(Application.Context).Load(ytThumbUri).Transform(new RemoveBlackBorder(true)).Get(); byte[] data; using (var MemoryStream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, MemoryStream); data = MemoryStream.ToArray(); } bitmap.Recycle(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; ytThumbUri = null; }); } else if (artURI != null) { System.Console.WriteLine("&Writing ArtURI"); IPicture[] pictures = new IPicture[1]; Bitmap bitmap = null; if (tempFile) { await Task.Run(() => { bitmap = Picasso.With(this).Load(artURI).Transform(new RemoveBlackBorder(true)).Get(); }); } else { await Task.Run(() => { bitmap = Picasso.With(this).Load(artURI).Get(); }); } MemoryStream memoryStream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, memoryStream); byte[] data = memoryStream.ToArray(); pictures[0] = new Picture(data); meta.Tag.Pictures = pictures; if (!tempFile) { artURI = null; } ContentResolver.Delete(ContentUris.WithAppendedId(Android.Net.Uri.Parse("content://media/external/audio/albumart"), song.AlbumArt), null, null); } System.Console.WriteLine("&Saving"); meta.Save(); stream.Dispose(); } catch (System.Exception e) { Toast.MakeText(this, Resource.String.format_unsupported, ToastLength.Long).Show(); System.Console.WriteLine("&EditMetadata Validate exception: (probably due to an unsupported format) - " + e.Message); } System.Console.WriteLine("&Deleting temp file"); if (tempFile) { tempFile = false; System.IO.File.Delete(artURI.Path); artURI = null; } System.Console.WriteLine("&Scanning file"); await Task.Delay(10); Android.Media.MediaScannerConnection.ScanFile(this, new string[] { song.Path }, null, null); Toast.MakeText(this, Resource.String.changes_saved, ToastLength.Short).Show(); return(true); }
private async void clickBtnLogIn(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(username.Text) || string.IsNullOrEmpty(username.Text)) { Snackbar bar = Snackbar.Make(parentLayout, "Fill username", Snackbar.LengthLong); bar.SetText(Html.FromHtml("<font color=\"#000000\">Fill username</font>")); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); } else if (string.IsNullOrWhiteSpace(password.Text) || string.IsNullOrEmpty(password.Text)) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Fill password</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); } else { var progressDialog = new ProgressDialog(this); try { progressDialog.SetIcon(2130968582); progressDialog.SetCancelable(true); progressDialog.SetMessage("Please wait!"); progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner); progressDialog.Show(); var client = new HttpClient(); var keyValueLogIn = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("username", username.Text), new KeyValuePair <string, string>("password", password.Text), new KeyValuePair <string, string>("grant_type", "password") }; var request = new HttpRequestMessage(HttpMethod.Post, "UrlApiToken"); request.Content = new FormUrlEncodedContent(keyValueLogIn); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { TokenModel tokenFromServer = JsonConvert.DeserializeObject <TokenModel>(content); var jsonContent = JsonConvert.SerializeObject(username.Text); var LogIncontent = new StringContent(jsonContent, Encoding.ASCII, "application/json"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenFromServer.access_token); response = await client.PostAsync("UrlApi" + "api/Account/userdata", LogIncontent); var userData = await response.Content.ReadAsStringAsync(); User user = JsonConvert.DeserializeObject <User>(userData); var userSession = new UserSession { FirstName = user.FirstName, LastName = user.LastName, userId = user.userId, Token = tokenFromServer.access_token, user_image = user.user_image }; con.Insert(userSession); progressDialog.Cancel(); StartActivity(typeof(MainActivity)); } else { LogInError logInError = JsonConvert.DeserializeObject <LogInError>(content); var alertLogInError = new Android.App.AlertDialog.Builder(this); alertLogInError.SetTitle(logInError.error); alertLogInError.SetMessage(logInError.error_description); username.Text = ""; password.Text = ""; Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">" + logInError.error + " - " + logInError.error_description + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } } catch (HttpRequestException httpEx) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Please check your internet connection!</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } catch (Exception ex) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Error: " + ex + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } } }
private async void Refresh() { await Task.Run(() => { // Online time steps try { if (TramUrWayApplication.Config.OfflineMode) { throw new Exception(); } swipeRefresh.Post(() => swipeRefresh.Refreshing = true); timeSteps = TramUrWayApplication.Lines.Where(l => l.Stops.Any(s => s.Name == stop.Name)) .SelectMany(l => TramUrWayApplication.Service.GetLiveTimeSteps(l)) .Where(t => t.Step.Stop.Name == stop.Name) .OrderBy(t => t.Date) .ToArray(); snackbar?.Dismiss(); } catch (Exception e) { DateTime now = DateTime.Now; timeSteps = TramUrWayApplication.Lines.SelectMany(l => l.Routes) .SelectMany(r => r.Steps.Where(s => s.Stop.Name == stop.Name)) .SelectMany(s => s.Route.TimeTable?.GetStepsFromStep(s, now)?.Take(3) ?? Enumerable.Empty <TimeStep>()) .ToArray(); if (timeSteps.Length != 0) { if (snackbar == null) { snackbar = Snackbar.Make(swipeRefresh, "Données hors-ligne", Snackbar.LengthIndefinite); if (TramUrWayApplication.Config.OfflineMode) { snackbar = snackbar.SetAction("Activer", Snackbar_Activate); } else { snackbar = snackbar.SetAction("Réessayer", Snackbar_Retry); } snackbar.Show(); } } else { timeSteps = null; if (snackbar == null) { snackbar = Snackbar.Make(swipeRefresh, "Aucune donnée disponible", Snackbar.LengthIndefinite); if (TramUrWayApplication.Config.OfflineMode) { snackbar = snackbar.SetAction("Activer", Snackbar_Activate); } else { snackbar = snackbar.SetAction("Réessayer", Snackbar_Retry); } snackbar.Show(); } } } swipeRefresh.Post(() => swipeRefresh.Refreshing = false); RunOnUiThread(OnRefreshed); }); }
private async void clickBtnRegister(object sender, EventArgs e) { if (string.IsNullOrEmpty(Email.Text) || string.IsNullOrWhiteSpace(Email.Text)) { displaySnackBar("Fill Email!"); } else if (string.IsNullOrEmpty(Username.Text) || string.IsNullOrWhiteSpace(Username.Text)) { displaySnackBar("Fill username!"); } else if (string.IsNullOrEmpty(Password.Text) || string.IsNullOrWhiteSpace(Password.Text)) { displaySnackBar("Fill password!"); } else if (string.IsNullOrEmpty(ConfirmPassword.Text) || string.IsNullOrWhiteSpace(ConfirmPassword.Text)) { displaySnackBar("Fill column confirm password!"); } else if (string.IsNullOrEmpty(FirstName.Text) || string.IsNullOrWhiteSpace(FirstName.Text)) { displaySnackBar("Fill First name!"); } else if (string.IsNullOrEmpty(LastName.Text) || string.IsNullOrWhiteSpace(LastName.Text)) { displaySnackBar("Fill Last name!"); } else if (Password.Text != ConfirmPassword.Text) { displaySnackBar("Confirm password do not match with password. Please check them."); } else { var progressDialog = new ProgressDialog(this); progressDialog.SetCancelable(true); progressDialog.SetMessage("Please wait!"); progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner); progressDialog.Show(); string email = Email.Text; string username = Username.Text; string password = Password.Text; string confirmPassword = ConfirmPassword.Text; string fistName = FirstName.Text; string lastName = LastName.Text; string phoneNumber = PhoneNumber.Text; httpClient = new HttpClient(); var resultForUsername = await httpClient.PostAsync("UrlApiapi/account/checkUsername", new StringContent(JsonConvert.SerializeObject(username), Encoding.UTF8, "application/json")); var responseForUsername = await resultForUsername.Content.ReadAsStringAsync(); var resultForEmail = await httpClient.PostAsync("UrlApiapi/account/checkEmail", new StringContent(JsonConvert.SerializeObject(email), Encoding.UTF8, "application/json")); var responseForEmail = await resultForEmail.Content.ReadAsStringAsync(); if (responseForUsername == "true") { displaySnackBar("There exist user with this username."); progressDialog.Hide(); } else if (responseForEmail == "true") { displaySnackBar("There exisit new user with this mail."); progressDialog.Hide(); } else { string base64Image = ""; try { UserImage.BuildDrawingCache(true); BitmapDrawable bd = (BitmapDrawable)UserImage.Drawable; Bitmap bitmap = bd.Bitmap; byte[] imageData; using (MemoryStream stream = new MemoryStream()) { bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); imageData = stream.ToArray(); } base64Image = Convert.ToBase64String(imageData); } catch (Exception ex) { } try { var signUp = new SignUp { Email = email, UserName = username, FirstName = fistName, LastName = lastName, BirthDate = DateTime.Now.ToString(), Password = password, PhoneNumber = phoneNumber, user_image = base64Image, ConfirmPassword = confirmPassword, Gender = "M" }; var httpClient = new HttpClient(); var jsonContent = JsonConvert.SerializeObject(signUp); var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync("UrlApiapi/account/Register", content); var responseString = await response.Content.ReadAsStringAsync(); Toast.MakeText(this, "Check your email for further details.", ToastLength.Long).Show(); progressDialog.Cancel(); StartActivity(typeof(LogIn)); } catch (HttpRequestException httpEx) { Snackbar bar = Snackbar.Make(linearLayout2, "Please check your internet connection!", Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } catch (Exception ex) { progressDialog.Cancel(); Toast.MakeText(this, "Error: " + ex, ToastLength.Long).Show(); } } } }