如何在 xamarin 表单中获得更多输入?

Posted

技术标签:

【中文标题】如何在 xamarin 表单中获得更多输入?【英文标题】:How to getUser with more input in xamarin forms? 【发布时间】:2020-08-28 23:34:01 【问题描述】:

我正在使用firebase RealTimeDataBase,我也想使用名称(GetUser(字符串电子邮件,字符串名称))来获取用户,那么我如何修改最后一个查询来做到这一点? 因为当我注册时我成功地看到了名字,但是当我登录时我没有看到名字,但是电子邮件是的

用户由组成:电子邮件、姓名、类别、密码

代码:

FirebaseHelper.cs

namespace yourActivity.ViewModel


public class FirebaseHelper

    public static byte[] GetHash(string inputString)
    
        using (HashAlgorithm algorithm = SHA256.Create())
        return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
    
    public static string GetHashString(string inputString)
    
        StringBuilder sb = new StringBuilder();
        foreach (byte b in GetHash(inputString))
            sb.Append(b.ToString("X2"));
        return sb.ToString();
    
    public static FirebaseClient firebase = new 
    FirebaseClient("https://youractivity-5acac.firebaseio.com/");

    //Read All    
    public static async Task<List<Users>> GetAllUser()
    
        try
        
            var userlist = (await firebase
            .Child("Users")
            .OnceAsync<Users>()).Select(item =>
            new Users
            
                Email = item.Object.Email,
                Password = item.Object.Password,
                Nome = item.Object.Nome,
                Categoria = item.Object.Categoria
            ).ToList();
            return userlist;
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
            return null;
        
    

    //Read     
    public static async Task<Users> GetUser(string email)
    
        try
        
            var allUsers = await GetAllUser();
            await firebase
            .Child("Users")
            .OnceAsync<Users>();
            return allUsers.Where(a => a.Email == email).FirstOrDefault();
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
            return null;
        
    


    //Insert a user    
    public static async Task<bool> AddUser(string email, string password, string nome, string categoria)
    
        try
        
            await firebase
            .Child("Users")
            .PostAsync(new Users()  Email = email, Password = GetHashString(password), Nome = nome, Categoria = categoria);
            return true;
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
            return false;
        
    

    //Update     
    public static async Task<bool> UpdateUser(string email, string password, string nome, string categoria)
    
        try
        
            var toUpdateUser = (await firebase
            .Child("Users")
            .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
            await firebase
            .Child("Users")
            .Child(toUpdateUser.Key)
            .PutAsync(new Users()  Email = email, Password = GetHashString(password) , Nome = nome, Categoria = categoria);
            return true;
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
            return false;
        
    

    //Delete User    
    public static async Task<bool> DeleteUser(string email)
    
        try
        
            var toDeletePerson = (await firebase
            .Child("Users")
            .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
            await firebase.Child("Users").Child(toDeletePerson.Key).DeleteAsync();
            return true;
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
            return false;
        
    



SignupPage.xaml.cs

namespace yourActivity.View

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SignupPage : ContentPage

    SignupViewModel signUpVM;
    public SignupPage()
    
        InitializeComponent();
        signUpVM = new SignupViewModel();
        //set binding
        BindingContext = signUpVM;
    


SignupViewModel.cs

namespace yourActivity.ViewModel


public class SignupViewModel : INotifyPropertyChanged

    private string email;
    public string Email
    
        get  return email; 
        set
        
            email = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Email"));
        
    

    private string nome;
    public string Nome
    
        get  return nome; 
        set
        
            nome = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Nome"));
        
    

    private string categoria;
    public string Categoria
    
        get  return categoria; 
        set
        
            categoria = value;
            PropertyChanged(this, new 
  PropertyChangedEventArgs("Categoria"));
        
    

    private string password;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Password
    
        get  return password; 
        set
        
            password = value;
            PropertyChanged(this, new 
   PropertyChangedEventArgs("Password"));
        
    
    private string confirmpassword;
    public string ConfirmPassword
    
        get  return confirmpassword; 
        set
        
            confirmpassword = value;
            PropertyChanged(this, new 
  PropertyChangedEventArgs("ConfirmPassword"));
        
    
    public Command SignUpCommand
    
        get
        
            return new Command(() =>
            
                if (Password == ConfirmPassword)
                    SignUp();
                else
                    App.Current.MainPage.DisplayAlert("", "Password must be same as above!", "OK");
            );
        
    
    private async void SignUp()
    
        //null or empty field validation, check weather email and password is null or empty
        if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Nome) || string.IsNullOrEmpty(Categoria))
            await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter all the values", "OK");
        else
        
            //call AddUser function which we define in Firebase helper class
            var user = await FirebaseHelper.AddUser(Email, Password, Nome, Categoria);
            //AddUser return true if data insert successfuly 
            if (user)
            
                await App.Current.MainPage.DisplayAlert("SignUp Success", "", "Ok");
                //Navigate to Wellcom page after successfuly SignUp
                //pass user email to welcom page

                await App.Current.MainPage.Navigation.PushAsync(new TabbedPage1(email, nome));
            
            else
                await App.Current.MainPage.DisplayAlert("Error", "SignUp Fail", "OK");
        
    


LoginPage.xaml.cs

namespace yourActivity.View

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage

    LoginViewModel loginViewModel;
    public LoginPage()
    
        loginViewModel = new LoginViewModel();
        InitializeComponent();
        BindingContext = loginViewModel;
    



LoginViewModel.cs

namespace yourActivity.ViewModel

public class LoginViewModel : INotifyPropertyChanged

    public static byte[] GetHash(string inputString)
    
        using (HashAlgorithm algorithm = SHA256.Create())
            return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
    
    public static string GetHashString(string inputString)
    
        StringBuilder sb = new StringBuilder();
        foreach (byte b in GetHash(inputString))
            sb.Append(b.ToString("X2"));
        return sb.ToString();
    


    private string email;
    public string Email
    
        get  return email; 
        set
        
            email = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Email"));
        
    
    private string nome;
    public string Nome
    
        get  return nome; 
        set
        
            nome = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Nome"));
        
    
    private string password;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Password
    
        get  return password; 
        set
        
            password = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Password"));
        
    
    public Command LoginCommand
    
        get
        
            return new Command(Login);
        
    
    public Command SignUp
    
        get
        
            return new Command(() =>  App.Current.MainPage.Navigation.PushAsync(new SignupPage()); );
        
    
    private async void Login()
    
        //null or empty field validation, check weather email and password is null or empty
        if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
            await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
        else
        
            //call GetUser function which we define in Firebase helper class
            var user = await FirebaseHelper.GetUser(Email);
            //firebase return null valuse if user data not found in database
            if (user != null)
                if (Email == user.Email && GetHashString(Password) == user.Password)
                
                    await App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
                    //Navigate to Wellcom page after successfuly login
                    //pass user email to welcom page

                    await App.Current.MainPage.Navigation.PushAsync(new TabbedPage1(email, nome));
                
                else
                    await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
            else
                await App.Current.MainPage.DisplayAlert("Login Fail", "User not found", "OK");
        
    


TabbedPage1.xaml.cs

namespace yourActivity

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TabbedPage1 : TabbedPage

    TabbedPage1ViewModel TabbedPageVM;
    readonly FirebaseHelper firebaseHelper = new FirebaseHelper();
    public TabbedPage1(string email, string nome)
    
        InitializeComponent();
        TabbedPageVM = new TabbedPage1ViewModel(email, nome);
        BindingContext = TabbedPageVM;


    



TabbedPage1ViewModel

namespace yourActivity.ViewModel

public class TabbedPage1ViewModel : INotifyPropertyChanged

    public TabbedPage1ViewModel(string email2, string nome2)
    
        Email = email2;
        Nome = nome2;
    

    private string email;

    public string Email
    
        get  return email; 
        set  email = value; 
    

    private string nome;

    public string Nome
    
        get  return nome; 
        set  nome = value; 

    

    private string categoria;

    public string Categoria
    
        get  return categoria; 
        set  categoria = value; 
    

    private string password;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Password
    
        get  return password; 
        set
        
            password = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Password"));
        
    
    public Command UpdateCommand
    
        get  return new Command(Update); 
    
    public Command DeleteCommand
    
        get  return new Command(Delete); 
    
    //For Logout
    public Command LogoutCommand
    
        get
        
            return new Command(() =>
            
                App.Current.MainPage.Navigation.PushAsync(new LoginPage());
            );
        
    



    //Update user data
    private async void Update()
    
        try
        
            if (!string.IsNullOrEmpty(Password))
            
                var isupdate = await FirebaseHelper.UpdateUser(Email, Password, Nome, Categoria);
                if (isupdate)
                    await App.Current.MainPage.DisplayAlert("Update Success", "", "Ok");
                else
                    await App.Current.MainPage.DisplayAlert("Error", "Record not update", "Ok");
            
            else
                await App.Current.MainPage.DisplayAlert("Password Require", "Please Enter your password", "Ok");
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
        
    

    //Delete user data
    private async void Delete()
    
        try
        
            var isdelete = await FirebaseHelper.DeleteUser(Email);
            if (isdelete)
                await App.Current.MainPage.Navigation.PopAsync();
            else
                await App.Current.MainPage.DisplayAlert("Error", "Record not delete", "Ok");
        
        catch (Exception e)
        
            Debug.WriteLine($"Error:e");
        
    


【问题讨论】:

【参考方案1】:

您可以使用 if 语句来决定使用emailname 来查询用户:

//Read     
public static async Task<Users> GetUser(string email = null, string name = null)

    try
    
        var allUsers = await GetAllUser();
        await firebase
        .Child("Users")
        .OnceAsync<Users>();

        if (email != null && email.Length> 0)
        
            return allUsers.Where(a => a.Email == email).FirstOrDefault();
        

        return allUsers.Where(a => a.Name == name).FirstOrDefault();
    
    catch (Exception e)
    
        Debug.WriteLine($"Error:e");
        return null;
    

【讨论】:

对不起,我没有看到问题中的更新。哪个部分不适用于您的问题?你能澄清一下吗? 我尝试添加这些 linea 但在登录时我无法看到名称 在代码中,如果无法可视化名称,则可以传递正确的电子邮件,名称等于null,然后它将返回allUsers.Where(a =&gt; a.Email == email).FirstOrDefault();。我用默认值的名称和电子邮件更新了我的答案。 这里不工作是什么意思?你有任何例外或其他什么吗?你能补充更详细的信息吗?

以上是关于如何在 xamarin 表单中获得更多输入?的主要内容,如果未能解决你的问题,请参考以下文章

如何创建xamarin表单按钮左角半径

如何在 xamarin 表单上添加室内地图

如何在 Xamarin 表单跨平台中添加服务引用?

如何在 xamarin 表单中进行可单击和可缩放的网格 (10000 x 10000)

当条目字段不可见时,如何隐藏 Xamarin 表单中的错误标签?

如何使用 xamarin 表单设置视觉材料输入的边框颜色?