RegViewModel.cs 2.9 KB

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