Untitled
unknown
plain_text
9 months ago
3.4 kB
5
Indexable
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Input;
using Airline_Reservation_System.Common;
using Airline_Reservation_System.Models;
using Newtonsoft.Json;
namespace Airline_Reservation_System.ViewModels
{
public class RegistrationViewModel : INotifyPropertyChanged
{
private string _name;
private string _email;
private string _password;
private string _errorMessage;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
public string Email
{
get => _email;
set
{
_email = value;
OnPropertyChanged(nameof(Email));
}
}
public string Password
{
get => _password;
set
{
_password = value;
OnPropertyChanged(nameof(Password));
}
}
public string ErrorMessage
{
get => _errorMessage;
set
{
_errorMessage = value;
OnPropertyChanged(nameof(ErrorMessage));
}
}
public ICommand SignupCommand { get; }
public RegistrationViewModel()
{
SignupCommand = new RelayCommand(SaveRegistrationData, CanExecuteSignup);
}
private bool CanExecuteSignup(object parameter)
{
return !string.IsNullOrEmpty(Name) &&
!string.IsNullOrEmpty(Email) &&
!string.IsNullOrEmpty(Password);
}
private void SaveRegistrationData(object parameter)
{
var user = new UserRegistrationModel
{
Name = Name,
Email = Email,
Password = Password
};
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UserData.json");
List<UserRegistrationModel> users;
if (File.Exists(filePath))
{
var existingJson = File.ReadAllText(filePath);
users = JsonConvert.DeserializeObject<List<UserRegistrationModel>>(existingJson) ?? new List<UserRegistrationModel>();
}
else
{
users = new List<UserRegistrationModel>();
}
if (users.Any(u => u.Email.Equals(user.Email, System.StringComparison.OrdinalIgnoreCase)))
{
ErrorMessage = "User with this email already exists.";
return;
}
users.Add(user);
string jsonData = JsonConvert.SerializeObject(users, Formatting.Indented);
File.WriteAllText(filePath, jsonData);
// Reset fields and error message
Name = string.Empty;
Email = string.Empty;
Password = string.Empty;
ErrorMessage = string.Empty;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}Editor is loading...
Leave a Comment