private async Task GetExternalLoginProviders() { var bounds = UIScreen.MainScreen.Bounds; // show the loading overlay on the UI thread using the correct orientation sizing loadPop = new LoadingOverlay(bounds); View.Add(loadPop); string fullUrl = "/api/Account/ExternalLogins?returnUrl=/callback&generateState=true"; ServerResponse <ExternalLogin[]> res = await ServerUtils.Get <ExternalLogin[]>(fullUrl, false); loadPop.Hide(); if (res.Success) { providers = res.Data; for (int i = 0; i < providers.Length; i++) { UIButton button = new UIButton(); nfloat buttonWidth = PromptLabel.Frame.Width; nfloat buttonYPos = PromptLabel.Frame.GetMaxY() + 20f + (60 * i); button.Frame = new CGRect(0f, buttonYPos, buttonWidth, 60f); button.SetTitle(providers[i].Name, UIControlState.Normal); button.TitleLabel.Font = UIFont.SystemFontOfSize(19); button.TouchUpInside += (sender, e) => { notificationToken = NSNotificationCenter.DefaultCenter.AddObserver(new NSString("ParkLearnLoginCallback"), OnLoginResult); // Use the button's title to find the appropriate provider ExternalLogin thisLogin = providers.FirstOrDefault(p => p.Name == ((UIButton)sender).Title(UIControlState.Normal)); if (thisLogin == null) { Console.WriteLine("Provider button is null"); return; } LoginAfterTerms(thisLogin.Url); }; PromptLabel.Superview.AddSubview(button); } } else { // Show error and retry button var errorAlert = UIAlertController.Create("Connection Error", "Couldn't load login info from the server. Please try again.", UIAlertControllerStyle.Alert); errorAlert.AddAction(UIAlertAction.Create("Retry", UIAlertActionStyle.Default, (a) => { var suppressAsync = GetExternalLoginProviders(); })); PresentViewController(errorAlert, true, null); } }
private async void GetExternalLoginProviders() { ProgressDialog dialog = new ProgressDialog(this); dialog.SetTitle(Resources.GetString(Resource.String.Connecting)); dialog.SetMessage(Resources.GetString(Resource.String.PleaseWait)); dialog.SetCancelable(false); dialog.Show(); const string fullUrl = "/api/Account/ExternalLogins?returnUrl=/callback&generateState=true"; ServerResponse <ExternalLogin[]> res = await ServerUtils.Get <ExternalLogin[]>(fullUrl, false); dialog.Dismiss(); if (res != null && res.Success) { providers = res.Data; if (providers == null || providers.Length <= 0) { return; } LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams.SetMargins(5, 15, 5, 15); foreach (ExternalLogin ext in providers) { Button thisButton = new Button(this) { Text = ext.Name }; thisButton.SetBackgroundResource(Resource.Color.app_purple); thisButton.SetTextColor(Color.White); thisButton.LayoutParameters = layoutParams; thisButton.Click += LoginActivity_Click; buttonLayout.AddView(thisButton); } } else { new global::Android.Support.V7.App.AlertDialog.Builder(this) .SetTitle(Resource.String.ErrorTitle) .SetMessage(res?.Message) .Show(); } }
private async void GetAndOpenActivity(string code) { ProgressDialog dialog = new ProgressDialog(this); dialog.SetMessage(Resources.GetString(Resource.String.PleaseWait)); dialog.Show(); ServerResponse <LearningActivity> result = await ServerUtils.Get <LearningActivity>("/api/LearningActivities/GetWithCode?code=" + code).ConfigureAwait(false); RunOnUiThread(() => { dialog.Dismiss(); dialog.Dispose(); }); if (result == null) { var suppress = AndroidUtils.ReturnToSignIn(this); RunOnUiThread(() => Toast.MakeText(this, Resource.String.ForceSignOut, ToastLength.Long).Show()); return; } if (result.Success) { await AndroidUtils.LaunchActivity(result.Data, this).ConfigureAwait(false); } else { // if token invalid, return to signin if (ServerUtils.CheckNeedsLogin(result.StatusCode)) { var suppress = AndroidUtils.ReturnToSignIn(this); return; } if (result.Message.StartsWith("404")) { RunOnUiThread(() => Toast.MakeText(this, Resource.String.searchFail, ToastLength.Long).Show()); } else { RunOnUiThread(() => Toast.MakeText(this, Resource.String.ConnectionError, ToastLength.Long).Show()); } } }
private async void LoadData() { ServerResponse <GMapsResultColl> resp = await ServerUtils.Get <GMapsResultColl>( string.Format("https://maps.googleapis.com/maps/api/place/nearbysearch/json?key={0}&location={1},{2}&radius=4000&type=park", Resources.GetString(Resource.String.MapsApiKey), targetLoc.Lat, targetLoc.Long)); dialog.Dismiss(); if (resp == null) { var suppress = AndroidUtils.ReturnToSignIn(this); Toast.MakeText(this, Resource.String.ForceSignOut, ToastLength.Long).Show(); return; } if (!resp.Success) { Toast.MakeText(this, Resource.String.ConnectionError, ToastLength.Long).Show(); return; } // Don't list places that have already been added List <GooglePlaceResult> final = new List <GooglePlaceResult>(); foreach (GooglePlaceResult res in resp.Data.results) { if (previouslyChosen.All(p => p.GooglePlaceId != res.place_id)) { final.Add(res); } } adapter = new PlacesAdapter(this, final); adapter.ItemClick += Adapter_ItemClick;; recyclerView = FindViewById <RecyclerView>(Resource.Id.recyclerView); recyclerView.SetAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.SetLayoutManager(layoutManager); }
private async void GetAndReturnWithActivity(string code) { ProgressDialog dialog = new ProgressDialog(this); dialog.SetMessage(Resources.GetString(Resource.String.PleaseWait)); dialog.Show(); ServerResponse <LearningActivity> result = await ServerUtils.Get <LearningActivity>("/api/LearningActivities/GetWithCode?code=" + code).ConfigureAwait(false); dialog.Dismiss(); if (result == null) { _ = AndroidUtils.ReturnToSignIn(this); Toast.MakeText(this, Resource.String.ForceSignOut, ToastLength.Long).Show(); return; } if (result.Success) { ActivityChosen(result.Data); } else { // if token invalid, return to signin if (ServerUtils.CheckNeedsLogin(result.StatusCode)) { _ = AndroidUtils.ReturnToSignIn(this); return; } if (result.StatusCode == System.Net.HttpStatusCode.NotFound) { Toast.MakeText(this, Resource.String.searchFail, ToastLength.Long).Show(); } else { Toast.MakeText(this, Resource.String.ConnectionError, ToastLength.Long).Show(); } } }
private async void OnLoginResult(NSNotification notification) { try { var bounds = UIScreen.MainScreen.Bounds; loadPop = new LoadingOverlay(bounds); View.Add(loadPop); // Login return format: // parklearn://logincallback?access_token=TOKEN&token_type=bearer&expires_in=7257600&state=STATE" NSObject returned = notification.UserInfo?[new NSString("url")]; if (returned == null) { throw new Exception("Error retrieving data from server"); } await safariController.DismissViewControllerAsync(true); NSNotificationCenter.DefaultCenter.RemoveObserver(notificationToken); Uri uri = new Uri(returned.ToString()); accessToken = Common.Helpers.GetUrlParam(uri, "access_token"); if (string.IsNullOrWhiteSpace(accessToken)) { throw new Exception("No access token returned"); } refreshToken = Common.Helpers.GetUrlParam(uri, "refresh_token"); if (string.IsNullOrWhiteSpace(refreshToken)) { throw new Exception("No refresh token returned"); } string expiresInSecs = Common.Helpers.GetUrlParam(uri, "expires_in"); if (string.IsNullOrWhiteSpace(expiresInSecs)) { throw new Exception("No access token expiry information"); } accessExpiresAt = DateTime.UtcNow.AddSeconds(int.Parse(expiresInSecs)); string refreshExpiry = Common.Helpers.GetUrlParam(uri, "refresh_token_expires"); if (string.IsNullOrWhiteSpace(refreshExpiry)) { throw new Exception("No refresh token expiry information"); } refreshExpiresAt = new DateTime(long.Parse(refreshExpiry), DateTimeKind.Utc); ApplicationUser tempUser = new ApplicationUser() { AccessToken = accessToken, AccessExpiresAt = accessExpiresAt, RefreshToken = refreshToken, RefreshExpiresAt = refreshExpiresAt }; (await Storage.GetDatabaseManager()).AddUser(tempUser); ServerResponse <ApplicationUser> res = await ServerUtils.Get <ApplicationUser>("api/account/"); if (res != null && res.Success) { ApplicationUser updatedUser = res.Data; updatedUser.AccessToken = tempUser.AccessToken; updatedUser.AccessExpiresAt = tempUser.AccessExpiresAt; updatedUser.RefreshToken = tempUser.RefreshToken; updatedUser.RefreshExpiresAt = tempUser.RefreshExpiresAt; (await Storage.GetDatabaseManager()).AddUser(updatedUser); loadPop.Hide(); NavigationController.SetNavigationBarHidden(false, true); var storyBoard = UIStoryboard.FromName("Main", null); var mainScreen = storyBoard.InstantiateViewController("MainTabController"); UIApplication.SharedApplication.KeyWindow.RootViewController = new UINavigationController(mainScreen); NavigationController.PopToRootViewController(true); } else { throw new Exception("Login failed"); } } catch (Exception e) { loadPop.Hide(); var errorAlert = UIAlertController.Create("Login Error", e.Message, UIAlertControllerStyle.Alert); PresentViewController(errorAlert, true, null); Console.WriteLine(e.Message); } }