Error during implementing credential service

Can anyone help me to understand why is my app suddenly appear blank page after i login and i reopen it.

AppShell.xaml

    <Shell.Resources>
        <ResourceDictionary>
            <Color x:Key="NavigationPrimary">#FEFEFE</Color>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource NavigationPrimary}" />
                <Setter Property="Shell.ForegroundColor" Value="#ED6237" />
                <Setter Property="Shell.TitleColor" Value="Black" />
                <Setter Property="Shell.UnselectedColor" Value="#757575" />
                <Setter Property="Shell.TabBarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
                <Setter Property="Shell.TabBarForegroundColor" Value="#ED6237" />
                <Setter Property="Shell.TabBarUnselectedColor" Value="#757575" />
                <Setter Property="Shell.TabBarTitleColor" Value="#ED6237" />
            </Style>
            <Style TargetType="ShellItem" BasedOn="{StaticResource BaseStyle}" />
            <Style TargetType="FlyoutItem" BasedOn="{StaticResource BaseStyle}" />
        </ResourceDictionary>
    </Shell.Resources>

    <!-- Image inside side navigation -->
    <Shell.FlyoutHeader>
        <local:FlayoutHeader/>
    </Shell.FlyoutHeader>

    <!-- Flyout is the root menu for a Shell application, and is accessible through navigation side bar-->
    <FlyoutItem Title="Home">
        <Tab Icon="home_black.png" Title="Home">
            <ShellContent ContentTemplate="{DataTemplate local:PageHome}" />
        </Tab>
        <Tab Icon="history_black.png" Title="Recents">
            <ShellContent ContentTemplate="{DataTemplate local:PageRecents}" />
        </Tab>
        <Tab Icon="library_music_black.png" Title="Library">
            <ShellContent Title="PLAYLISTS" ContentTemplate="{DataTemplate local:PagePlaylists}" />
            <ShellContent Title="STATIONS" ContentTemplate="{DataTemplate local:PageStations}" />
            <ShellContent Title="ALBUMS" ContentTemplate="{DataTemplate local:PageAlbum}" />
        </Tab>
        <Tab Icon="stars_black.png" Title="Browse">
            <ShellContent ContentTemplate="{DataTemplate local:PageBrowse}" />
        </Tab>
    </FlyoutItem>


    <!-- To customized the flyoutitem -->
    <Shell.ItemTemplate>
        <DataTemplate>
            <Grid VerticalOptions="Start">
                <Label Margin="10" Text="{Binding Title}"
                       Style="{StaticResource Menu_BlackLabel}"
                       VerticalTextAlignment="Center" />
            </Grid>
        </DataTemplate>
    </Shell.ItemTemplate>

    <!-- To customized the menuitem -->
    <Shell.MenuItemTemplate>
        <DataTemplate>
            <Grid>
                <Label Margin="10" Text="{Binding Text}"
                       Style="{StaticResource Menu_BlackLabel}"
                       VerticalTextAlignment="Center" />
            </Grid>
        </DataTemplate>
    </Shell.MenuItemTemplate>

    <!-- MenuItem is the item that didn't appear on Homepage item-->
    <MenuItem Text="Downloaded Only" Command="{Binding RandomPageCommand}">
        <Shell.MenuItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Label Grid.Column="0" Margin="10" Text="{Binding Text}"
                           Style="{StaticResource Menu_BlackLabel}"
                           VerticalTextAlignment="Center" />
                    <Switch Margin="10,0" HorizontalOptions="Center" Grid.Column="1" OnColor="#ED6237" />
                </Grid>
            </DataTemplate>
        </Shell.MenuItemTemplate>
    </MenuItem>

    <MenuItem Text="Settings"
              Command="{Binding RandomPageCommand}" />

    <MenuItem Text="Send Feedback"
              Command="{Binding RandomPageCommand}" />
</Shell>

App.xaml.cs

namespace EBI_Application
{
    [Obsolete]
    public partial class App : Application
    {
        public static string AppName { get { return "StoreAccountInfoApp"; } }
        public static ICredentialsService CredentialsService { get; private set; }

        public App()
        {
            InitializeComponent();

            MainPage = new NavigationPage(new SplashPage());
            CredentialsService = new CredentialsService();
            if (CredentialsService.DoCredentialsExist()) //User has not logged in
            {
                MainPage = new NavigationPage(new AppShell());
            }
            else //User is logged in
            {
                MainPage = new NavigationPage(new LoginPage());
            }
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

LoginPage.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"
             x:Class="EBI_Application.Views.Login.LoginPage"
             NavigationPage.HasNavigationBar="false">  <!-- To remove navigation bar function -->

    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="Android" Value="0,0,0,0"/>
            <On Platform="iOS" Value="0,20,0,0"/>
        </OnPlatform>
    </ContentPage.Padding>

    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="45"/>
            </Grid.RowDefinitions>

            <Grid Grid.Row="0" Margin="20,0,20,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="40"/>
                    <RowDefinition Height="40"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="starting.png" HeightRequest="400" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>

                <Entry Grid.Row="1" Placeholder="Email or Phone Number" PlaceholderColor="#bababa" FontSize="16" x:Name="usernameEntry"/>

                <Entry Grid.Row="2" Placeholder="Password" PlaceholderColor="#bababa" FontSize="16" x:Name="passwordEntry" IsPassword="True"/>

                <Button Grid.Row="3" Margin="10,0,10,0" Clicked="OnLoginButtonClicked" Text="Log In" 
                        BackgroundColor="#3897F0" TextColor="White" HeightRequest="50"
                        VerticalOptions="Start"/>

                <Label Grid.Row="4"  x:Name="messageLabel" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>

                <Label Grid.Row="5" Text="Forgot your password? Click here." HorizontalOptions="Center"
                       Margin="0,10,0,0" FontSize="11">
                    <!-- Function allow label to be clicked-->
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer Tapped="Lbl_ForgotPassword"/>
                    </Label.GestureRecognizers>
                </Label>

                <Grid Grid.Row="6">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Label BackgroundColor="#bababa" HeightRequest="1" HorizontalOptions="FillAndExpand" VerticalOptions="Center"/>
                    <Label Grid.Column="1" Text="OR" VerticalOptions="Center" Margin="10,0,10,0"/>
                    <Label Grid.Column="2" BackgroundColor="#bababa" HeightRequest="1" HorizontalOptions="FillAndExpand" VerticalOptions="Center"/>
                </Grid>

                <StackLayout Orientation="Horizontal" Grid.Row="7" HorizontalOptions="Center">
                    <Image Source="facebook.png" HeightRequest="20" WidthRequest="20"/>
                    <Label Text="Log In With Facebook" TextColor="#483992" />
                </StackLayout>
            </Grid>

            <StackLayout Grid.Row="1" BackgroundColor="#ffffff">
                <Label HeightRequest="1" BackgroundColor="#E3E3E3" />
                <Label Text="Doesn't have any account yet? Register Now!." VerticalOptions="FillAndExpand" VerticalTextAlignment="Center" HorizontalOptions="Center">
                    <!-- Function allow label to be clicked-->
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer Tapped="Btn_Register"/>
                    </Label.GestureRecognizers>
                </Label>
            </StackLayout>

        </Grid>
    </ContentPage.Content>
</ContentPage>

LoginPage.xaml.cs

namespace EBI_Application.Views.Login
{
    [Obsolete]
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPage()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
        }

        private void Btn_Register(object sender, EventArgs e)
        {
            if (Device.OS == TargetPlatform.Android)
            {
                //await Navigation.PushModalAsync(new NavigationPage(new AppShell())); //Allow the next page to return to this page but don't have return buttton
                //Application.Current.MainPage = new RegisterPage(); //Can't return to this page //Remove await kalau xnk async function
                Navigation.PushAsync(new NavigationPage(new RegisterPage())); // Allow the user to return to this page with button tabbar function
            }
            else if (Device.OS == TargetPlatform.iOS)
            {
                Application.Current.MainPage = new RegisterPage();
            }
        }

        //Label Forgot Password
        private void Lbl_ForgotPassword(object sender, EventArgs e)
        {
            if (Device.OS == TargetPlatform.Android)
            {
                Navigation.PushAsync(new NavigationPage(new ForgotPassword())); 
            }
            else if (Device.OS == TargetPlatform.iOS)
            {
                Application.Current.MainPage = new ForgotPassword();
            }
        }

        public void OnLoginButtonClicked(object sender, EventArgs e)
        {
            string userName = usernameEntry.Text;
            string password = passwordEntry.Text;

            var isValid = AreCredentialsCorrect(userName, password);
            if (isValid)
            {
                bool doCredentialsExist = App.CredentialsService.DoCredentialsExist();
                if (!doCredentialsExist)
                {
                    App.CredentialsService.SaveCredentials(userName, password);
                }

                if (Device.OS == TargetPlatform.Android)
                {
                    Application.Current.MainPage = new AppShell();
                }
                else if (Device.OS == TargetPlatform.iOS)
                {
                    Application.Current.MainPage = new AppShell();
                }
            }
            else
            {
                messageLabel.Text = "Login failed";
                passwordEntry.Text = string.Empty;
            }
        }

        bool AreCredentialsCorrect(string username, string password)
        {
            return username == Constants.Username && password == Constants.Password;
        }
    }
}

CredientalsService.cs

namespace EBI_Application.Services
{
    [System.Obsolete]
    public class CredentialsService : ICredentialsService
    {
        public string UserName
        {
            get
            {
                var account = AccountStore.Create().FindAccountsForService(App.AppName).FirstOrDefault();
                return (account != null) ? account.Username : null;
            }
        }

        public string Password
        {
            get
            {
                var account = AccountStore.Create().FindAccountsForService(App.AppName).FirstOrDefault();
                return (account != null) ? account.Properties["Password"] : null;
            }
        }

        public void SaveCredentials(string userName, string password)
        {
            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                Account account = new Account
                {
                    Username = userName
                };
                account.Properties.Add("Password", password);
                AccountStore.Create().Save(account, App.AppName);
            }

        }

        public void DeleteCredentials()
        {
            var account = AccountStore.Create().FindAccountsForService(App.AppName).FirstOrDefault();
            if (account != null)
            {
                AccountStore.Create().Delete(account, App.AppName);
            }
        }

        public bool DoCredentialsExist()
        {
            return AccountStore.Create().FindAccountsForService(App.AppName).Any() ? true : false;
        }
    }
}

Best Answer

Answers

Sign In or Register to comment.