Daniel Andrei Popescu Ответов: 0

Как сделать метод входа в систему на основе индикатора выполнения?


Привет,

I have my method which checks if the user is in the database or not upon login.I would like this to be done by using a progress bar,so every time the progress bar reaches 100,during the loading process,the method will check the credentials with the database and automatically will load the window if the credentials are correct,without involving any button at all.Can someone please tell me if this s this possible?And if yes,how should I do it?I have searched examples over the internet,but there is nothing that can be found,only basic explanations about how to make it work and some basic functionalities of it.I would really appreciate an advice,and hope someone will make a topic about it in time,since it's useful to learn when you have a project where you have to avoid buttons and see how can you establish a relation between the database and the progress bar.I'm using WPF with MVVM,my strategy was database first.Thank you in advance!

Что я уже пробовал:

Я уже пробовал это сделать:
class LoginWithCardreaderViewModel : INotifyPropertyChanged
    {
        private readonly BackgroundWorker worker;
        private readonly DelegateCommand instigateWorkCommand;
        private int currentProgress;
        private bool isDataFetched;
        public bool IsDataFetched//i made a boolean to check if the data is fetched durring the loading process but i don't know how to use it in the context...
        {
            get { return isDataFetched; }
            set
            {
                if(isDataFetched=value)
                {
                    NotifyOnPropertyChange("IsDataFetched");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyOnPropertyChange(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        private DelegateCommand loginCommand;




        private int pwd;
        public int PWD
        {
            get { return pwd; }
            set
            {
                if (pwd != value)
                {
                    pwd = value;
                    NotifyOnPropertyChange("PWD");
                }
            }
        }
        public LoginWithCardreaderViewModel()// in the contructor I am creating the Background worker along with a command that checks if the worker is busy or not.
        {
            // ButtonCommand = new DelegateCommand(SubmitButton);
            this.instigateWorkCommand = new DelegateCommand(o => this.worker.RunWorkerAsync(), o => !this.worker.IsBusy);
            this.worker = new BackgroundWorker();
            this.worker.DoWork += this.DoWork;
            this.worker.ProgressChanged += this.ProgressChanged;
        }
      private void ProgressChanged(object sender,ProgressChangedEventArgs e)
        {
            this.currentProgress = e.ProgressPercentage;//the progress percentage of the progress bar
        }
       
       public int CurrentProgress
        {
            get { return currentProgress; }
            set
            {
                currentProgress = value;
                NotifyOnPropertyChange("CurrentProgress");
            }
        }
 private void DoWork(object sender, DoWorkEventArgs e)//this is my actual method to check the credentials with the database and load the form
        {
            for (int i = 0; i < 100; i++)//I think I'm mistaken,but here I tried to connect to the database while the progress bar is loading
            {
                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 COUNT (*) FROM Login WHERE pwd=@pwd";
                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.CommandType = CommandType.Text;


                    SqlParameter Pwd = cmd.Parameters.AddWithValue("@pwd", SqlDbType.Int);
                    cmd.Parameters["@pwd"].Value = pwd;
                    if (Pwd.Value == null)
                    {
                        Pwd.Value = DBNull.Value;
                    }
                    SqlDataReader reader = cmd.ExecuteReader();
                    Thread.Sleep(300);

                    int count = Convert.ToInt32(cmd.ExecuteScalar());
                    if (currentProgress == 100 && count > 0)//here I'm trying to check if the progress bar reached 100% and if the credentials are correct
                    {
                        MainWindow main = new MainWindow();
                        main.Show();

                    }
                    else
                    {
                        MessageBox.Show("Username or password is incorrect!");
                        Thread.Sleep(500);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }

        }


Это привязка с представлением(.cs):
public partial class LoginWithCardreader : Window
   {
       public LoginWithCardreader()
       {
           InitializeComponent();
           LoginWithCardreaderViewModel vm = new LoginWithCardreaderViewModel();
           this.DataContext = vm;

       }
   }


А это уже часть .xaml:
<Window x:Class="LastAndFinalVersion.View.LoginWithCardreader"
        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:mm="clr-namespace:LastAndFinalVersion.ViewModel"
        mc:Ignorable="d"
         <Window.DataContext>
                    <mm:LoginWithCardreaderViewModel/>
  </Window.DataContext>
      <pre>  Title="LoginWithCardreader" Height="400" Width="400">
    <Grid>
 
        <Border Background="#2e3137" CornerRadius="20" Margin="20">
            <StackPanel Margin="20">

                <Label Content="Login" 
               Foreground="White" FontSize="25" HorizontalAlignment="Center"/>
                <Separator></Separator>
                <TextBlock Height="50" 
                   HorizontalAlignment="Center"
                   Margin="24,48,0,0"
                   Name="textBlockHeading" 
                   VerticalAlignment="Top"
                          
                   FontSize="12" 
                      Foreground="Crimson"
                   FontStyle="Italic" 
                   Padding="5">
                    Please swipe the card on the<LineBreak></LineBreak> card reader for authentication!
                </TextBlock>
                <ProgressBar x:Name="loginProgress" Height="10" Margin="0,0,-0.4,0" />

                <Label Content="Password"     Foreground="White"/>
                <PasswordBox x:Name="passwordBox" 
                         MaxLength="10"
                    local:PasswordHelper.BindPassword="true"
                         local:PasswordHelper.BoundPassword="{Binding Path=PWD, Mode=TwoWay, ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}"
                PasswordChar="*" 
                         Background="#545d6a" 
                         Foreground="White"
             FontSize="18"/>

            </StackPanel>
        </Border>
    </Grid>
</Window>

Richard MacCutchan

Вы не проверяете идентификаторы пользователей и сохраняете пароли в открытом тексте, поэтому ваша система не имеет никакой безопасности.

Daniel Andrei Popescu

Да,я знаю, потому что у меня есть еще одна форма входа, которая делает это.Этот человек в основном должен проверить пароль(пароль-это серийный номер nr от тега NFC).Я использовал фокус на текстовом поле, чтобы сразу же прочитать SN.В принципе, мне нужен способ автоматического входа в систему, когда пользователь наводит NFC-метку на устройство чтения карт.Считыватель карт уже настроен на считывание значений с тега NFC.Что касается пароля,то я знаю,что он небезопасен, но я работаю над ним(я все еще учусь этому, потому что я новичок в MVVM).

0 Ответов