// Click handler for the login button. private void LoginButtonClick(object sender, EventArgs e) { try { // Get information for the login. string username = _usernameTextbox.Text; string password = _passwordTextbox.Text; // Make sure all required info was entered. if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password)) { throw new Exception("Please enter a username and password."); } // Create a new OnEnterCredentialsEventArgs object to store the information entered by the user. OnEnterCredentialsEventArgs credentialsEnteredArgs = new OnEnterCredentialsEventArgs(username, password); // Raise the OnLoginClicked event so the main activity can handle the event and try to authenticate with the credentials. OnLoginClicked?.Invoke(this, credentialsEnteredArgs); // Close the dialog. this.Dismiss(); } catch (Exception ex) { // Show the exception message (dialog will stay open so user can try again). AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this.Activity); alertBuilder.SetTitle("Error"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } }
// Handler for the OnLoginClicked event defined in the LoginDialogFragment. // OnEnterCredentialsEventArgs contains the username and password the user entered. private async void LoginClicked(object sender, OnEnterCredentialsEventArgs e) { // If no login information is available from the Task, return. if (_loginTaskCompletionSource == null || _loginTaskCompletionSource.Task == null || _loginTaskCompletionSource.Task.AsyncState == null) { return; } try { // Get the associated CredentialRequestInfo (will need the URI of the service being accessed). CredentialRequestInfo requestInfo = (CredentialRequestInfo)_loginTaskCompletionSource.Task.AsyncState; // Create a token credential using the provided username and password. TokenCredential userCredentials = await AuthenticationManager.Current.GenerateCredentialAsync (requestInfo.ServiceUri, e.Username, e.Password, requestInfo.GenerateTokenOptions); // Set the result on the task completion source. _loginTaskCompletionSource.TrySetResult(userCredentials); } catch (Exception ex) { _loginTaskCompletionSource.TrySetException(ex); } finally { // Set the task completion source to null to indicate authentication is complete. _loginTaskCompletionSource = null; } }