如何以xamarin形式获得更多输入的getUser? [英] How to getUser with more input in xamarin forms?
问题描述
我正在使用Firebase RealTimeDataBase,我也想使用名称(GetUser(字符串电子邮件,字符串名称))来获取用户,那么如何修改上一个查询来做到这一点? 因为当我注册时,我成功地显示了该名称,但是当我登录时却没有显示该名称,但是电子邮件显示了
I i'm using firebase RealTimeDataBase, i want to getUser also with the name(GetUser(string email, string name)), so how do i modify the last Query to do this? Because when i signup i succesfully visualize the name, but when i login i do not visualize the name, but the email yes
用户由 组成:电子邮件,姓名,类别,密码
Users are composed by: Email, Name, Category, Password
代码:
Code:
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}");
}
}
}
}
推荐答案
您可以使用if语句来决定使用email
或name
来查询用户:
You can use a if statement to decide use email
or name
to query user:
//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;
}
}
这篇关于如何以xamarin形式获得更多输入的getUser?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!