AdminViewModel.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Runtime.CompilerServices;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using ReactiveUI;
  8. using RegAuth.Models;
  9. namespace RegAuth.ViewModels
  10. {
  11. internal class AdminViewModel : ViewModelBase, INotifyPropertyChanged
  12. {
  13. private readonly validViewModel _otherViewModel;
  14. public AdminViewModel()
  15. {
  16. _otherViewModel = new validViewModel(); // Create an instance of the other ViewModel
  17. }
  18. public void ToAdmin()
  19. {
  20. MainWindowViewModel.Instance.Uc = new CreateAdmin();
  21. }
  22. User _newAdmin = new User();
  23. public User NewAdmin { get => _newAdmin; set => this.RaiseAndSetIfChanged(ref _newAdmin, value); }
  24. string _password;
  25. private string _passwordError;
  26. public string Password
  27. {
  28. get => _password;
  29. set
  30. {
  31. if (this.RaiseAndSetIfChanged(ref _password, value))
  32. {
  33. // Ïðîâåðÿåì ïàðîëü è óñòàíàâëèâàåì ñîîáùåíèå îá îøèáêå
  34. PasswordError = _otherViewModel.ValidatePassword(value);
  35. }
  36. }
  37. }
  38. public string PasswordError
  39. {
  40. get => _passwordError;
  41. private set
  42. {
  43. this.RaiseAndSetIfChanged(ref _passwordError, value); // Óâåäîìëÿåì îá èçìåíåíèè
  44. }
  45. }
  46. public event PropertyChangedEventHandler PropertyChanged;
  47. public void addAdmin()//ôóíêöèÿ äëÿ äîáàâëåíèÿ àäìèíà â áàçó
  48. {
  49. Console.WriteLine("Àäìèíà â áàçå íåò");
  50. if (!string.IsNullOrEmpty(Password) && string.IsNullOrEmpty(PasswordError))//åñëè ó íàñ ïàðîëü íå ïóñò è îøèáîê íå íàáëþäàåòñÿ, òîãäà ìåòîä ðàáîòàåò äàëüøå è ðåàëèçóåò äîáàâëåíèå â áä
  51. {
  52. NewAdmin.Password = MD5.HashData(Encoding.ASCII.GetBytes(Password));
  53. NewAdmin.Roleid = 1;
  54. MainWindowViewModel.myConnection.Users.Add(NewAdmin);
  55. MainWindowViewModel.myConnection.SaveChanges();
  56. MainWindowViewModel.Instance.Uc = new Main();
  57. }
  58. }
  59. protected bool RaiseAndSetIfChanged<T>(ref T field, T value, [CallerMemberName] string propertyName = null)//ýòî íàì íàäî, ÷òîáû êîððåêòíî îáðàáîòàòü ðåçóëüòàò â RaiseAndSetIfChanged
  60. {
  61. if (EqualityComparer<T>.Default.Equals(field, value)) return false; // Åñëè çíà÷åíèå íå èçìåíèëîñü, âîçâðàùàåì false
  62. field = value; // Îáíîâëÿåì ïîëå
  63. OnPropertyChanged(propertyName); // Âûçûâàåì ñîáûòèå èçìåíåíèÿ ñâîéñòâà
  64. return true; // Âîçâðàùàåì true, åñëè çíà÷åíèå èçìåíèëîñü
  65. }
  66. public void OnPropertyChanged(string propertyName)
  67. {
  68. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  69. }
  70. }
  71. }