如何在MVVM,WPF中使用数据库中的值检查凭据?

时间:2018-03-06 13:43:32

标签: database wpf mvvm data-binding credentials

我正在尝试根据我在我的数据库中手动插入的值来验证凭据但没有任何运气。我有一个名为“凭据”的类来检查凭据,我使用的“PasswordHelper”类通过dependancy属性和我的viewmodel将它绑定到视图,这给了我一个糟糕的mojo.Here是我的类: 的 PasswordHelper.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows.Controls;

 namespace LastAndFinalVersion.Helpers
 {
 public static  class PasswordHelper
{
    public static readonly DependencyProperty BoundPassword =
     DependencyProperty.RegisterAttached("BoundPassword", typeof(string),  
  typeof(PasswordHelper), new PropertyMetadata(string.Empty, 
  OnBoundPasswordChanged));

    public static readonly DependencyProperty BindPassword = 
   DependencyProperty.RegisterAttached(
        "BindPassword", typeof(bool), typeof(PasswordHelper), new 
   PropertyMetadata(false, OnBindPasswordChanged));

    private static readonly DependencyProperty UpdatingPassword =
        DependencyProperty.RegisterAttached("UpdatingPassword", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false));

    private static void OnBoundPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PasswordBox box = d as PasswordBox;

        // only handle this event when the property is attached to a PasswordBox
        // and when the BindPassword attached property has been set to true
        if (d == null || !GetBindPassword(d))
        {
            return;
        }

        // avoid recursive updating by ignoring the box's changed event
        box.PasswordChanged -= HandlePasswordChanged;

        string newPassword = (string)e.NewValue;

        if (!GetUpdatingPassword(box))
        {
            box.Password = newPassword;
        }

        box.PasswordChanged += HandlePasswordChanged;
    }

    private static void OnBindPasswordChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        // when the BindPassword attached property is set on a PasswordBox,
        // start listening to its PasswordChanged event

        PasswordBox box = dp as PasswordBox;

        if (box == null)
        {
            return;
        }

        bool wasBound = (bool)(e.OldValue);
        bool needToBind = (bool)(e.NewValue);

        if (wasBound)
        {
            box.PasswordChanged -= HandlePasswordChanged;
        }

        if (needToBind)
        {
            box.PasswordChanged += HandlePasswordChanged;
        }
    }

    private static void HandlePasswordChanged(object sender, RoutedEventArgs e)
    {
        PasswordBox box = sender as PasswordBox;

        // set a flag to indicate that we're updating the password
        SetUpdatingPassword(box, true);
        // push the new password into the BoundPassword property
        SetBoundPassword(box, box.Password);
        SetUpdatingPassword(box, false);
    }

    public static void SetBindPassword(DependencyObject dp, bool value)
    {
        dp.SetValue(BindPassword, value);
    }

    public static bool GetBindPassword(DependencyObject dp)
    {
        return (bool)dp.GetValue(BindPassword);
    }

    public static string GetBoundPassword(DependencyObject dp)
    {
        return (string)dp.GetValue(BoundPassword);
    }

    public static void SetBoundPassword(DependencyObject dp, string value)
    {
        dp.SetValue(BoundPassword, value);
    }

    private static bool GetUpdatingPassword(DependencyObject dp)
    {
        return (bool)dp.GetValue(UpdatingPassword);
    }

    private static void SetUpdatingPassword(DependencyObject dp, bool value)
    {
        dp.SetValue(UpdatingPassword, value);
    }
}
 }

Credentials.cs:

       using System;
       using System.Collections.Generic;
       using System.Linq;
       using System.Text;
       using System.Threading.Tasks;

       namespace LastAndFinalVersion.Commands
   {
    static class Credentials
{
    static System.Collections.Hashtable credentials;
    static Credentials()
    {
        credentials = new System.Collections.Hashtable();
        credentials.Add("Guest", GetHash(0));
        credentials.Add("Administrator", GetHash(11223344));
    }

    internal static bool Check(string login, int pwd)
    {
        return object.Equals(credentials[login], GetHash(pwd));
    }
    static object GetHash(int password)
    {
        return password;
    }
    internal static IEnumerable<string> GetUserNames()
    {
        foreach (string item in credentials.Keys)
            yield return item;
    }
}


}

LoginViewModel.cs:

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data.SqlClient;
      using System.Linq;
      using System.Runtime.InteropServices;
      using System.Security;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows;


   namespace LastAndFinalVersion.ViewModel
{
class LoginViewModel : INotifyPropertyChanged
{

    private DelegateCommand loginCommand;
    private  Login _UserName;
    private  Login _pwd;
    private Login CurrentUser { get; set; }

    public event PropertyChangedEventHandler OnPropertyChanged;
    public event PropertyChangedEventHandler PropertyChanged;
    public bool IsCurrentUserCredentialsValid { get; private set; }
    public Login UserName
    {
        get { return _UserName; }
        set
        {
            _UserName = value;
           NotifyPropertyChanged("UserName");
        }


    }


public Login pwd
    {
        get { return _pwd; }
        set
        {
            if(_pwd!=value)
            {
                _pwd = value;
                NotifyPropertyChanged("pwd");
            }
        }
    }


public LoginViewModel():base()
{
    ButtonCommand = new DelegateCommand(SubmitButton);


}
public DelegateCommand ButtonCommand
{
    get { return loginCommand; }
    set
    {
        if (loginCommand != value)
            loginCommand = value;
        NotifyPropertyChanged("ButtonCommand");
    }
}

protected void NotifyPropertyChanged(string propertyName)
{
    if (OnPropertyChanged != null)
    {
        OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

    private object ConvertToUnsecureString(SecureString securePassword)
    {
        if(securePassword==null)
        {
            return string.Empty;
        }
        IntPtr unmanagedString = IntPtr.Zero;
        try
        {
            unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
            return Marshal.PtrToStringUni(unmanagedString);
        }
        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
        }
    }

    public void SubmitButton()
{

    SqlConnection conn = new SqlConnection(

   @"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=
  C:\Users\User\source\repos\VIAApp2Demo\
  VIAApp2Demo\DB\DatabaseStudents.mdf;Integrated Security=True;Connect 
  Timeout=30");
    try
    {
        if (conn.State == System.Data.ConnectionState.Closed)
            conn.Open();
        String query = "SELECT * FROM Login WHERE UserName=@UserName AND pwd=@pwd";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.CommandType = System.Data.CommandType.Text;
            SqlParameter Username = cmd.Parameters.AddWithValue("@UserName", _UserName);
            if(_UserName==null)
            {
                Username.Value = DBNull.Value;
            }
            SqlParameter password = cmd.Parameters.AddWithValue("@pwd", _pwd);
            if(_pwd==null)
            {
                password.Value = DBNull.Value;
            }
        if(IsCurrentUserCredentialsValid==true)

        {
                IsCurrentUserCredentialsValid = Credentials.Check(CurrentUser.UserName, CurrentUser.pwd);
            MainWindow main = new MainWindow();
            main.Show();
            main.Hide();
        }
        else
        {
            MessageBox.Show("Username or password is incorrect!");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }
}
 }
}

最后我的 Login.xaml(查看)

  <Window x:Class="LastAndFinalVersion.View.Login"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:LastAndFinalVersion.Helpers"
    xmlns:ff="clr-namespace:LastAndFinalVersion.ViewModel"

    mc:Ignorable="d"
  Title="Login" Height="300" Width="300" FontSize="14" Background="#04c582">
<Window.DataContext>
    <ff:LoginViewModel/>
</Window.DataContext>

<Border Background="#2e3137" CornerRadius="20" Margin="20">
    <StackPanel Margin="20">

        <Label Content="Login" 
           Foreground="White" FontSize="25" HorizontalAlignment="Center"/>
        <Separator></Separator>
        <Label Content="Username" Foreground="White"/>
        <TextBox Name="txtusername" Text="{Binding UserName}"   
Background="#545d6a" Foreground="White" FontSize="18"/>
        <Label Content="Password"     Foreground="White"/>
        <PasswordBox x:Name="passwordBox" 
                     MaxLength="10"
                local:PasswordHelper.BindPassword="true"
                     local:PasswordHelper.BoundPassword="{Binding 
Path=PasswordBox, Mode=TwoWay, 
ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}"
            PasswordChar="*" 
                     Background="#545d6a" 
                     Foreground="White"
         FontSize="18"/>

        <StackPanel>

        </StackPanel>
        <Button x:Name="btnSubmit" Command="{Binding Path=ButtonCommand}" 
   Click="btnSubmit_Click"  Content="Submit" Margin="60 10" 
  Background="#545d6a" Foreground="White" FontSize="18"/>
        <TextBlock Height="50" 
               HorizontalAlignment="Left"
               Margin="24,48,0,0"
               Name="textBlockHeading" 
               VerticalAlignment="Top"
               FontSize="12" 
                  Foreground="Crimson"
               FontStyle="Italic" 
               Padding="5">

        Note: Please login here to view the features of this site. If you 
  are new on this site then <LineBreak /><!--line break-->
        please click on
   <TextBlock>
   <Hyperlink Click="Hyperlink_Click"  FontSize="14" 
FontStyle="Normal">Register</Hyperlink>
 </TextBlock>
 button
    </TextBlock>
    </StackPanel>

</Border>

</Window>

Login.xaml.cs:

 using LastAndFinalVersion.Helpers;
 using LastAndFinalVersion.ViewModel;
 using System.Security;
 using System.Windows;
 using System.Windows.Controls;

 namespace LastAndFinalVersion.View
 {
/// <summary>
/// Interaction logic for Login.xaml
/// </summary>
public partial class Login : UserControl,IHavePassword
{
   private LoginViewModel lg;
    public Login()
    {
        InitializeComponent();
        lg = new LoginViewModel();
        this.DataContext = lg;
    }


    public SecureString Password
    {
        get
        {
            return passwordBox.SecurePassword;
        }
    }
    private void btnSubmit_Click(object sender, RoutedEventArgs e)
    {
        lg.SubmitButton();
    }

    private void Hyperlink_Click(object sender, RoutedEventArgs e)
    {
        Register reg = new Register();
        reg.Show();
        this.Close();
    }
  }

我真的很感激有关如何使用数据库检查凭据的一些提示,因为我已经搜索过,我发现在我的情况下没有任何可行的工作。我在Login.xaml.cs中有一个错误,说我不能指定不同基类。这就是为什么我试图用Login:UserControl或local:IHavePassword替换Login.xaml中的Window但仍然无效。我是MVVM的新手,所以任何建议都会受到赞赏。谢谢你提前!

0 个答案:

没有答案