Xamarin Forms - Gerenciando usuários no Firebase - III
 Neste artigo vamos concluir o gerenciamento de dados de usuários usando o banco de dados Realtime Database do Firebase.

Continuando a segunda parte do artigo vamos concluir nosso projeto criando as view models e as respectivas views.

Na pasta ViewModels vamos criar a view model RegisterViewModel :

using Xamarin.Forms;
using XF_FirebaseUsuarios.Services;
using XF_FirebaseUsuarios.Views;
namespace XF_FirebaseUsuarios.ViewModels
{
    public class RegisterViewModel : BaseViewModel
    {
        private readonly IMessageService _messageService;
        public RegisterViewModel()
        {
            _messageService = DependencyService.Get<IMessageService>();
        }
        private string email;
        public string Email
        {
            get { return email; }
            set
            {
                email = value;
                OnPropertyChanged();
            }
        }
        private string password;
        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnPropertyChanged();
            }
        }
        private string confirmpassword;
        public string ConfirmPassword
        {
            get { return confirmpassword; }
            set
            {
                confirmpassword = value;
                OnPropertyChanged();
            }
        }
        public Command SignUpCommand
        {
            get
            {
                return new Command(() =>
                {
                    if (Password == ConfirmPassword)
                        SignUp();
                    else
                        _messageService.AlertaAsync("A senha não confere");
                });
            }
        }
        private async void SignUp()
        {
            if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
                await _messageService.AlertaAsync("Informe o email e/ou senha");
            else
            {
                var user = await FirebaseUserService.AddUser(Email, Password);
                if (user)
                {
                    await _messageService.AlertaAsync("Registro feito com sucesso");
                    await NavigationDispatcher.Instance.Navigation.PushAsync(new WelComePage(Email));
                }
                else
                    await _messageService.AlertaAsync("O Registro Falhou");
            }
        }
    }
}

Note que no código estamos herdando da classe BaseViewModel e usando os serviços:

A seguir na pasta Views crie a view RegisterPage.xaml :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:vm="clr-namespace:XF_FirebaseUsuarios.ViewModels"
             x:Class="XF_FirebaseUsuarios.Views.RegisterPage"
              BackgroundColor="WhiteSmoke"
             Title="Registar Usuário">
    <ContentPage.BindingContext>
        <vm:RegisterViewModel />
    </ContentPage.BindingContext>
    <StackLayout>

        <Entry x:Name="Emailentery" Placeholder="Email" 
                   PlaceholderColor="Black" 
                   TextColor="Black"
               Text="{Binding Email}" Keyboard="Email" />
        <Entry x:Name="passwordentery" Placeholder="Senha" 
                PlaceholderColor="Black" 
                   TextColor="Black"
               Text="{Binding Password}"     
                   IsPassword="True"/>
        <Entry x:Name="cfmpasswordentery" 
               Placeholder="Confirma Senha" 
                PlaceholderColor="Black" 
                   TextColor="Black"
               Text="{Binding ConfirmPassword}"     
                   IsPassword="True" />
        <Button x:Name="signup" Text="Registrar novo Usuário" 
                 TextColor="White"
                BackgroundColor="DarkGoldenrod"
                Command="{Binding SignUpCommand}" 
                HorizontalOptions="Center"/>
    </StackLayout>
</ContentPage>

Para concluir vamos criar a view model WelcomeViewModel na pasta ViewModels:

using System;
using System.Diagnostics;
using Xamarin.Forms;
using XF_FirebaseUsuarios.Services;
namespace XF_FirebaseUsuarios.ViewModels
{
    public class WelcomeViewModel : BaseViewModel
    {
        private readonly IMessageService _messageService;
        public WelcomeViewModel(string _email)
        {
            Email = _email;
            _messageService = DependencyService.Get<IMessageService>();
        }
        private string email;
        public string Email
        {
            get { return email; }
            set 
            { 
                email = value;
                OnPropertyChanged();
            }
        }
        private string password;
        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnPropertyChanged();
            }
        }
        public Command UpdateCommand
        {
            get { return new Command(Update); }
        }
        public Command DeleteCommand
        {
            get { return new Command(Delete); }
        }
        public Command LogoutCommand
        {
            get
            {
                return new Command(() =>
                {
                    NavigationDispatcher.Instance.Navigation.PopAsync();
                });
            }
        }
        private async void Update()
        {
            try
            {
                if (!string.IsNullOrEmpty(Password))
                {
                    var isupdate = await FirebaseUserService.UpdateUser(Email, Password);
                    if (isupdate)
                        await _messageService.AlertaAsync("Senha do usuário atualizada com sucesso");
                    else
                        await _messageService.AlertaAsync("Não foi possível atualizar a senha");
                }
                else
                    await _messageService.AlertaAsync("Informe a senha para alterar");
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
            }
        }
        private async void Delete()
        {
            try
            {
                var isdelete = await FirebaseUserService.DeleteUser(Email);
                if (isdelete)
                    await NavigationDispatcher.Instance.Navigation.PopAsync();
                else
                    await _messageService.AlertaAsync("Não possível deletar");
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error:{e}");
            }
        }
    }
}

E finalmente vamos criar a View WelcomePage.xaml na pasta Views:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XF_FirebaseUsuarios.Views.WelComePage"
             Title="Gerenciar Conta">

    <StackLayout>
        <Label Text="{Binding Email, StringFormat='Bem-Vindo {0}'}" 
               FontSize="Large"
               TextColor="Blue"
               Margin="10"/>

        <Entry Text="{Binding Password}" IsPassword="True" 
                PlaceholderColor="Black"
                   TextColor="Black"
               Margin="5,5" Placeholder="Informe a nova senha"/>

        <Button x:Name="updatebtn" Text="Alterar Senha do usuário" 
                 TextColor="White"
                BackgroundColor="DarkGoldenrod"
                Command="{Binding UpdateCommand}" />

        <Button x:Name="deletebtn" Text="Deletar Conta do usuário" 
                 TextColor="White"
                BackgroundColor="DarkGoldenrod"
                Command="{Binding DeleteCommand}"/>

        <Button x:Name="logoutbtn" Text="Fazer o Logout" 
                 TextColor="White"
                BackgroundColor="DarkGoldenrod"
                Command="{Binding LogoutCommand}"/>

    </StackLayout>
</ContentPage>

Executando o projeto iremos obter o resultado a seguir realizando operações para registrar, fazer login, alterar a senha, fazer o logout e deletar o usuário :

Note que as atualizações são feitas em tempo real no Firebase Realtime Database.

Pegue o código do projeto compartilhado aqui: XF_FirebaseUsuarios.zip

"Porque pela graça sois salvos, por meio da fé; e isto não vem de vós, é dom de Deus.
Não vem das obras, para que ninguém se glorie;"
Efésios 2:8,9

Referências:


José Carlos Macoratti